From aad45ad592e57d8eeda6dcd0549ab88cc4a5c75a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20Andr=C3=A9=20Pearce?= Date: Sat, 12 May 2018 14:15:17 +0100 Subject: [PATCH] ARTEMIS-1783 Remove need for guava Replace guava Preconditions with artemis Preconditions Replace guava Predicate with java Predicate Replace guava Ordering with java Comparator Replace guava Immutable, with ArrayList/Set and then wrap with unmodifiable --- artemis-cli/pom.xml | 4 - artemis-commons/pom.xml | 4 - .../activemq/artemis/utils/ByteUtil.java | 4 + .../activemq/artemis/utils/IPV6Util.java | 2 - .../activemq/artemis/utils/InetAddresses.java | 571 ++++++++++++++++++ .../activemq/artemis/utils/Preconditions.java | 84 +++ .../activemq/artemis/utils/Suppliers.java | 16 +- .../collections/ConcurrentLongHashMap.java | 11 +- .../collections/ConcurrentLongHashSet.java | 2 +- .../ConcurrentLongHashMapTest.java | 14 +- .../ConcurrentLongHashSetTest.java | 10 +- artemis-server/pom.xml | 4 - .../impl/view/ActiveMQAbstractView.java | 50 +- .../predicate/ActiveMQFilterPredicate.java | 4 +- .../predicate/AddressFilterPredicate.java | 2 +- .../predicate/ConnectionFilterPredicate.java | 2 +- .../predicate/ConsumerFilterPredicate.java | 2 +- .../predicate/ProducerFilterPredicate.java | 2 +- .../view/predicate/QueueFilterPredicate.java | 2 +- .../predicate/SessionFilterPredicate.java | 2 +- .../impl/QueuePendingMessageMetrics.java | 2 +- pom.xml | 6 - tests/integration-tests/pom.xml | 4 - 23 files changed, 713 insertions(+), 91 deletions(-) create mode 100644 artemis-commons/src/main/java/org/apache/activemq/artemis/utils/InetAddresses.java create mode 100644 artemis-commons/src/main/java/org/apache/activemq/artemis/utils/Preconditions.java diff --git a/artemis-cli/pom.xml b/artemis-cli/pom.xml index 88a48db478..92f1589da1 100644 --- a/artemis-cli/pom.xml +++ b/artemis-cli/pom.xml @@ -82,10 +82,6 @@ javax.inject javax.inject - - com.google.guava - guava - org.apache.geronimo.specs geronimo-jms_2.0_spec diff --git a/artemis-commons/pom.xml b/artemis-commons/pom.xml index 45172e7624..fb47dccd1f 100644 --- a/artemis-commons/pom.xml +++ b/artemis-commons/pom.xml @@ -70,10 +70,6 @@ commons-beanutils commons-beanutils - - com.google.guava - guava - junit junit diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ByteUtil.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ByteUtil.java index 8835797ab5..85f7fcd99c 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ByteUtil.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/ByteUtil.java @@ -329,4 +329,8 @@ public class ByteUtil { } return true; } + + public static int intFromBytes(byte b1, byte b2, byte b3, byte b4) { + return b1 << 24 | (b2 & 0xFF) << 16 | (b3 & 0xFF) << 8 | (b4 & 0xFF); + } } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/IPV6Util.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/IPV6Util.java index 486c699fbc..0df8b11206 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/IPV6Util.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/IPV6Util.java @@ -17,8 +17,6 @@ package org.apache.activemq.artemis.utils; -import com.google.common.net.InetAddresses; - public class IPV6Util { /** diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/InetAddresses.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/InetAddresses.java new file mode 100644 index 0000000000..3d4f089d2c --- /dev/null +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/InetAddresses.java @@ -0,0 +1,571 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.activemq.artemis.utils; + +import java.net.Inet4Address; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.Locale; + +import static org.apache.activemq.artemis.utils.ByteUtil.intFromBytes; + +/** + * Static utility methods pertaining to {@link InetAddress} instances. + * + *

Important note: Unlike {@code InetAddress.getByName()}, the + * methods of this class never cause DNS services to be accessed. For + * this reason, you should prefer these methods as much as possible over + * their JDK equivalents whenever you are expecting to handle only + * IP address string literals -- there is no blocking DNS penalty for a + * malformed string. + * + *

When dealing with {@link Inet4Address} and {@link Inet6Address} + * objects as byte arrays (vis. {@code InetAddress.getAddress()}) they + * are 4 and 16 bytes in length, respectively, and represent the address + * in network byte order. + * + *

Examples of IP addresses and their byte representations: + *

+ * + *

A few notes about IPv6 "IPv4 mapped" addresses and their observed + * use in Java. + *

+ * "IPv4 mapped" addresses were originally a representation of IPv4 + * addresses for use on an IPv6 socket that could receive both IPv4 + * and IPv6 connections (by disabling the {@code IPV6_V6ONLY} socket + * option on an IPv6 socket). Yes, it's confusing. Nevertheless, + * these "mapped" addresses were never supposed to be seen on the + * wire. That assumption was dropped, some say mistakenly, in later + * RFCs with the apparent aim of making IPv4-to-IPv6 transition simpler. + * + *

Technically one can create a 128bit IPv6 address with the wire + * format of a "mapped" address, as shown above, and transmit it in an + * IPv6 packet header. However, Java's InetAddress creation methods + * appear to adhere doggedly to the original intent of the "mapped" + * address: all "mapped" addresses return {@link Inet4Address} objects. + * + *

For added safety, it is common for IPv6 network operators to filter + * all packets where either the source or destination address appears to + * be a "compat" or "mapped" address. Filtering suggestions usually + * recommend discarding any packets with source or destination addresses + * in the invalid range {@code ::/3}, which includes both of these bizarre + * address formats. For more information on "bogons", including lists + * of IPv6 bogon space, see: + * + *

+ * + */ +public final class InetAddresses { + private static final int IPV4_PART_COUNT = 4; + private static final int IPV6_PART_COUNT = 8; + private static final Inet4Address LOOPBACK4 = (Inet4Address) forString("127.0.0.1"); + private static final Inet4Address ANY4 = (Inet4Address) forString("0.0.0.0"); + + private InetAddresses() { + } + + /** + * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address. + * + * @param bytes byte array representing an IPv4 address (should be of length 4) + * @return {@link Inet4Address} corresponding to the supplied byte array + * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created + */ + private static Inet4Address getInet4Address(byte[] bytes) { + Preconditions.checkArgument(bytes.length == 4, + "Byte array has invalid length for an IPv4 address: %s != 4.", + bytes.length); + + // Given a 4-byte array, this cast should always succeed. + return (Inet4Address) bytesToInetAddress(bytes); + } + + /** + * Returns the {@link InetAddress} having the given string representation. + * + *

This deliberately avoids all nameservice lookups (e.g. no DNS). + * + * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. + * {@code "192.168.0.1"} or {@code "2001:db8::1"} + * @return {@link InetAddress} representing the argument + * @throws IllegalArgumentException if the argument is not a valid IP string literal + */ + public static InetAddress forString(String ipString) { + byte[] addr = ipStringToBytes(ipString); + + // The argument was malformed, i.e. not an IP string literal. + if (addr == null) { + throw formatIllegalArgumentException("'%s' is not an IP string literal.", ipString); + } + + return bytesToInetAddress(addr); + } + + /** + * Returns {@code true} if the supplied string is a valid IP string + * literal, {@code false} otherwise. + * + * @param ipString {@code String} to evaluated as an IP string literal + * @return {@code true} if the argument is a valid IP string literal + */ + public static boolean isInetAddress(String ipString) { + return ipStringToBytes(ipString) != null; + } + + private static byte[] ipStringToBytes(String ipString) { + // Make a first pass to categorize the characters in this string. + boolean hasColon = false; + boolean hasDot = false; + for (int i = 0; i < ipString.length(); i++) { + char c = ipString.charAt(i); + if (c == '.') { + hasDot = true; + } else if (c == ':') { + if (hasDot) { + return null; // Colons must not appear after dots. + } + hasColon = true; + } else if (Character.digit(c, 16) == -1) { + return null; // Everything else must be a decimal or hex digit. + } + } + + // Now decide which address family to parse. + if (hasColon) { + if (hasDot) { + ipString = convertDottedQuadToHex(ipString); + if (ipString == null) { + return null; + } + } + return textToNumericFormatV6(ipString); + } else if (hasDot) { + return textToNumericFormatV4(ipString); + } + return null; + } + + private static byte[] textToNumericFormatV4(String ipString) { + String[] address = ipString.split("\\.", IPV4_PART_COUNT + 1); + if (address.length != IPV4_PART_COUNT) { + return null; + } + + byte[] bytes = new byte[IPV4_PART_COUNT]; + try { + for (int i = 0; i < bytes.length; i++) { + bytes[i] = parseOctet(address[i]); + } + } catch (NumberFormatException ex) { + return null; + } + + return bytes; + } + + private static byte[] textToNumericFormatV6(String ipString) { + // An address can have [2..8] colons, and N colons make N+1 parts. + String[] parts = ipString.split(":", IPV6_PART_COUNT + 2); + if (parts.length < 3 || parts.length > IPV6_PART_COUNT + 1) { + return null; + } + + // Disregarding the endpoints, find "::" with nothing in between. + // This indicates that a run of zeroes has been skipped. + int skipIndex = -1; + for (int i = 1; i < parts.length - 1; i++) { + if (parts[i].length() == 0) { + if (skipIndex >= 0) { + return null; // Can't have more than one :: + } + skipIndex = i; + } + } + + int partsHi; // Number of parts to copy from above/before the "::" + int partsLo; // Number of parts to copy from below/after the "::" + if (skipIndex >= 0) { + // If we found a "::", then check if it also covers the endpoints. + partsHi = skipIndex; + partsLo = parts.length - skipIndex - 1; + if (parts[0].length() == 0 && --partsHi != 0) { + return null; // ^: requires ^:: + } + if (parts[parts.length - 1].length() == 0 && --partsLo != 0) { + return null; // :$ requires ::$ + } + } else { + // Otherwise, allocate the entire address to partsHi. The endpoints + // could still be empty, but parseHextet() will check for that. + partsHi = parts.length; + partsLo = 0; + } + + // If we found a ::, then we must have skipped at least one part. + // Otherwise, we must have exactly the right number of parts. + int partsSkipped = IPV6_PART_COUNT - (partsHi + partsLo); + if (!(skipIndex >= 0 ? partsSkipped >= 1 : partsSkipped == 0)) { + return null; + } + + // Now parse the hextets into a byte array. + ByteBuffer rawBytes = ByteBuffer.allocate(2 * IPV6_PART_COUNT); + try { + for (int i = 0; i < partsHi; i++) { + rawBytes.putShort(parseHextet(parts[i])); + } + for (int i = 0; i < partsSkipped; i++) { + rawBytes.putShort((short) 0); + } + for (int i = partsLo; i > 0; i--) { + rawBytes.putShort(parseHextet(parts[parts.length - i])); + } + } catch (NumberFormatException ex) { + return null; + } + return rawBytes.array(); + } + + private static String convertDottedQuadToHex(String ipString) { + int lastColon = ipString.lastIndexOf(':'); + String initialPart = ipString.substring(0, lastColon + 1); + String dottedQuad = ipString.substring(lastColon + 1); + byte[] quad = textToNumericFormatV4(dottedQuad); + if (quad == null) { + return null; + } + String penultimate = Integer.toHexString(((quad[0] & 0xff) << 8) | (quad[1] & 0xff)); + String ultimate = Integer.toHexString(((quad[2] & 0xff) << 8) | (quad[3] & 0xff)); + return initialPart + penultimate + ":" + ultimate; + } + + private static byte parseOctet(String ipPart) { + // Note: we already verified that this string contains only hex digits. + int octet = Integer.parseInt(ipPart); + // Disallow leading zeroes, because no clear standard exists on + // whether these should be interpreted as decimal or octal. + if (octet > 255 || (ipPart.startsWith("0") && ipPart.length() > 1)) { + throw new NumberFormatException(); + } + return (byte) octet; + } + + private static short parseHextet(String ipPart) { + // Note: we already verified that this string contains only hex digits. + int hextet = Integer.parseInt(ipPart, 16); + if (hextet > 0xffff) { + throw new NumberFormatException(); + } + return (short) hextet; + } + + /** + * Convert a byte array into an InetAddress. + * + * {@link InetAddress#getByAddress} is documented as throwing a checked + * exception "if IP address is of illegal length." We replace it with + * an unchecked exception, for use by callers who already know that addr + * is an array of length 4 or 16. + * + * @param addr the raw 4-byte or 16-byte IP address in big-endian order + * @return an InetAddress object created from the raw IP address + */ + private static InetAddress bytesToInetAddress(byte[] addr) { + try { + return InetAddress.getByAddress(addr); + } catch (UnknownHostException e) { + throw new AssertionError(e); + } + } + + /** + * Returns the string representation of an {@link InetAddress}. + * + *

For IPv4 addresses, this is identical to + * {@link InetAddress#getHostAddress()}, but for IPv6 addresses, the output + * follows RFC 5952 + * section 4. The main difference is that this method uses "::" for zero + * compression, while Java's version uses the uncompressed form. + * + *

This method uses hexadecimal for all IPv6 addresses, including + * IPv4-mapped IPv6 addresses such as "::c000:201". The output does not + * include a Scope ID. + * + * @param ip {@link InetAddress} to be converted to an address string + * @return {@code String} containing the text-formatted IP address + * @since 10.0 + */ + public static String toAddrString(InetAddress ip) { + Preconditions.checkNotNull(ip); + if (ip instanceof Inet4Address) { + // For IPv4, Java's formatting is good enough. + return ip.getHostAddress(); + } + Preconditions.checkArgument(ip instanceof Inet6Address); + byte[] bytes = ip.getAddress(); + int[] hextets = new int[IPV6_PART_COUNT]; + for (int i = 0; i < hextets.length; i++) { + hextets[i] = intFromBytes((byte) 0, (byte) 0, bytes[2 * i], bytes[2 * i + 1]); + } + compressLongestRunOfZeroes(hextets); + return hextetsToIPv6String(hextets); + } + + /** + * Identify and mark the longest run of zeroes in an IPv6 address. + * + *

Only runs of two or more hextets are considered. In case of a tie, the + * leftmost run wins. If a qualifying run is found, its hextets are replaced + * by the sentinel value -1. + * + * @param hextets {@code int[]} mutable array of eight 16-bit hextets + */ + private static void compressLongestRunOfZeroes(int[] hextets) { + int bestRunStart = -1; + int bestRunLength = -1; + int runStart = -1; + for (int i = 0; i < hextets.length + 1; i++) { + if (i < hextets.length && hextets[i] == 0) { + if (runStart < 0) { + runStart = i; + } + } else if (runStart >= 0) { + int runLength = i - runStart; + if (runLength > bestRunLength) { + bestRunStart = runStart; + bestRunLength = runLength; + } + runStart = -1; + } + } + if (bestRunLength >= 2) { + Arrays.fill(hextets, bestRunStart, bestRunStart + bestRunLength, -1); + } + } + + /** + * Convert a list of hextets into a human-readable IPv6 address. + * + *

In order for "::" compression to work, the input should contain negative + * sentinel values in place of the elided zeroes. + * + * @param hextets {@code int[]} array of eight 16-bit hextets, or -1s + */ + private static String hextetsToIPv6String(int[] hextets) { + /* + * While scanning the array, handle these state transitions: + * start->num => "num" start->gap => "::" + * num->num => ":num" num->gap => "::" + * gap->num => "num" gap->gap => "" + */ + StringBuilder buf = new StringBuilder(39); + boolean lastWasNumber = false; + for (int i = 0; i < hextets.length; i++) { + boolean thisIsNumber = hextets[i] >= 0; + if (thisIsNumber) { + if (lastWasNumber) { + buf.append(':'); + } + buf.append(Integer.toHexString(hextets[i])); + } else { + if (i == 0 || lastWasNumber) { + buf.append("::"); + } + } + lastWasNumber = thisIsNumber; + } + return buf.toString(); + } + + /** + * Returns the string representation of an {@link InetAddress} suitable + * for inclusion in a URI. + * + *

For IPv4 addresses, this is identical to + * {@link InetAddress#getHostAddress()}, but for IPv6 addresses it + * compresses zeroes and surrounds the text with square brackets; for example + * {@code "[2001:db8::1]"}. + * + *

Per section 3.2.2 of + * http://tools.ietf.org/html/rfc3986, + * a URI containing an IPv6 string literal is of the form + * {@code "http://[2001:db8::1]:8888/index.html"}. + * + *

Use of either {@link InetAddresses#toAddrString}, + * {@link InetAddress#getHostAddress()}, or this method is recommended over + * {@link InetAddress#toString()} when an IP address string literal is + * desired. This is because {@link InetAddress#toString()} prints the + * hostname and the IP address string joined by a "/". + * + * @param ip {@link InetAddress} to be converted to URI string literal + * @return {@code String} containing URI-safe string literal + */ + public static String toUriString(InetAddress ip) { + if (ip instanceof Inet6Address) { + return "[" + toAddrString(ip) + "]"; + } + return toAddrString(ip); + } + + /** + * Returns an InetAddress representing the literal IPv4 or IPv6 host + * portion of a URL, encoded in the format specified by RFC 3986 section 3.2.2. + * + *

This function is similar to {@link InetAddresses#forString(String)}, + * however, it requires that IPv6 addresses are surrounded by square brackets. + * + *

This function is the inverse of + * {@link InetAddresses#toUriString(java.net.InetAddress)}. + * + * @param hostAddr A RFC 3986 section 3.2.2 encoded IPv4 or IPv6 address + * @return an InetAddress representing the address in {@code hostAddr} + * @throws IllegalArgumentException if {@code hostAddr} is not a valid + * IPv4 address, or IPv6 address surrounded by square brackets + */ + public static InetAddress forUriString(String hostAddr) { + Preconditions.checkNotNull(hostAddr); + + // Decide if this should be an IPv6 or IPv4 address. + String ipString; + int expectBytes; + if (hostAddr.startsWith("[") && hostAddr.endsWith("]")) { + ipString = hostAddr.substring(1, hostAddr.length() - 1); + expectBytes = 16; + } else { + ipString = hostAddr; + expectBytes = 4; + } + + // Parse the address, and make sure the length/version is correct. + byte[] addr = ipStringToBytes(ipString); + if (addr == null || addr.length != expectBytes) { + throw formatIllegalArgumentException("Not a valid URI IP literal: '%s'", hostAddr); + } + + return bytesToInetAddress(addr); + } + + /** + * Returns {@code true} if the supplied string is a valid URI IP string + * literal, {@code false} otherwise. + * + * @param ipString {@code String} to evaluated as an IP URI host string literal + * @return {@code true} if the argument is a valid IP URI host + */ + public static boolean isUriInetAddress(String ipString) { + try { + forUriString(ipString); + return true; + } catch (IllegalArgumentException e) { + return false; + } + } + + /** + * Evaluates whether the argument is an IPv6 "compat" address. + * + *

An "IPv4 compatible", or "compat", address is one with 96 leading + * bits of zero, with the remaining 32 bits interpreted as an + * IPv4 address. These are conventionally represented in string + * literals as {@code "::192.168.0.1"}, though {@code "::c0a8:1"} is + * also considered an IPv4 compatible address (and equivalent to + * {@code "::192.168.0.1"}). + * + *

For more on IPv4 compatible addresses see section 2.5.5.1 of + * http://tools.ietf.org/html/rfc4291 + * + *

NOTE: This method is different from + * {@link Inet6Address#isIPv4CompatibleAddress} in that it more + * correctly classifies {@code "::"} and {@code "::1"} as + * proper IPv6 addresses (which they are), NOT IPv4 compatible + * addresses (which they are generally NOT considered to be). + * + * @param ip {@link Inet6Address} to be examined for embedded IPv4 compatible address format + * @return {@code true} if the argument is a valid "compat" address + */ + public static boolean isCompatIPv4Address(Inet6Address ip) { + if (!ip.isIPv4CompatibleAddress()) { + return false; + } + + byte[] bytes = ip.getAddress(); + if ((bytes[12] == 0) && (bytes[13] == 0) && (bytes[14] == 0) + && ((bytes[15] == 0) || (bytes[15] == 1))) { + return false; + } + + return true; + } + + /** + * Returns the IPv4 address embedded in an IPv4 compatible address. + * + * @param ip {@link Inet6Address} to be examined for an embedded IPv4 address + * @return {@link Inet4Address} of the embedded IPv4 address + * @throws IllegalArgumentException if the argument is not a valid IPv4 compatible address + */ + public static Inet4Address getCompatIPv4Address(Inet6Address ip) { + Preconditions.checkArgument(isCompatIPv4Address(ip), + "Address '%s' is not IPv4-compatible.", toAddrString(ip)); + + return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16)); + } + + private static IllegalArgumentException formatIllegalArgumentException( + String format, Object... args) { + return new IllegalArgumentException(String.format(Locale.ROOT, format, args)); + } + +} diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/Preconditions.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/Preconditions.java new file mode 100644 index 0000000000..c826bfbb39 --- /dev/null +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/Preconditions.java @@ -0,0 +1,84 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.activemq.artemis.utils; + +public class Preconditions { + + /** + * Ensures that an object reference passed as a parameter to the calling method is not null. + * + * @param reference an object reference + * @return the non-null reference that was validated + * @throws NullPointerException if {@code reference} is null + */ + public static T checkNotNull(T reference) { + if (reference == null) { + throw new NullPointerException(); + } + return reference; + } + /** + * Ensures the truth of an expression involving one or more parameters to the calling method. + * + * @param expression a boolean expression + * @param errorMessage the exception message to use if the check fails; will be converted to a + * string using {@link String#valueOf(Object)} + * @throws IllegalArgumentException if {@code expression} is false + */ + public static void checkArgument(boolean expression, Object errorMessage) { + if (!expression) { + throw new IllegalArgumentException(String.valueOf(errorMessage)); + } + } + + /** + * Ensures the truth of an expression involving one or more parameters to the calling method. + * + * @param expression a boolean expression + * @param errorMessageTemplate a template for the exception message should the check fail. The + * message is formed by replacing each {@code %s} placeholder in the template with an + * argument. These are matched by position - the first {@code %s} gets {@code + * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message + * in square braces. Unmatched placeholders will be left as-is. + * @param errorMessageArgs the arguments to be substituted into the message template. Arguments + * are converted to strings using {@link String#valueOf(Object)}. + * @throws IllegalArgumentException if {@code expression} is false + * @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or + * {@code errorMessageArgs} is null (don't let this happen) + */ + public static void checkArgument( + boolean expression, + String errorMessageTemplate, + Object... errorMessageArgs) { + if (!expression) { + throw new IllegalArgumentException(String.format(errorMessageTemplate, errorMessageArgs)); + } + } + + /** + * Ensures the truth of an expression involving one or more parameters to the calling method. + * + * @param expression a boolean expression + * @throws IllegalArgumentException if {@code expression} is false + */ + public static void checkArgument(boolean expression) { + if (!expression) { + throw new IllegalArgumentException(); + } + } +} diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/Suppliers.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/Suppliers.java index 59ccd7782f..c184f09727 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/Suppliers.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/Suppliers.java @@ -22,6 +22,8 @@ package org.apache.activemq.artemis.utils; import java.io.Serializable; import java.util.function.Supplier; +import static org.apache.activemq.artemis.utils.Preconditions.checkNotNull; + public class Suppliers { /** @@ -79,17 +81,5 @@ public class Suppliers { private static final long serialVersionUID = 0; } - /** - * Ensures that an object reference passed as a parameter to the calling method is not null. - * - * @param reference an object reference - * @return the non-null reference that was validated - * @throws NullPointerException if {@code reference} is null - */ - public static T checkNotNull(T reference) { - if (reference == null) { - throw new NullPointerException(); - } - return reference; - } + } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashMap.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashMap.java index 29917c997f..10001b25d1 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashMap.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashMap.java @@ -20,16 +20,15 @@ */ package org.apache.activemq.artemis.utils.collections; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.locks.StampedLock; import java.util.function.LongFunction; -import com.google.common.collect.Lists; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; +import static org.apache.activemq.artemis.utils.Preconditions.checkArgument; +import static org.apache.activemq.artemis.utils.Preconditions.checkNotNull; /** * Map from long to an Object. @@ -178,7 +177,7 @@ public class ConcurrentLongHashMap { * @return a new list of all keys (makes a copy) */ public List keys() { - List keys = Lists.newArrayListWithExpectedSize((int) size()); + List keys = new ArrayList<>(size()); forEach((key, value) -> keys.add(key)); return keys; } @@ -190,7 +189,7 @@ public class ConcurrentLongHashMap { } public List values() { - List values = Lists.newArrayListWithExpectedSize((int) size()); + List values = new ArrayList<>(size()); forEach((key, value) -> values.add(value)); return values; } diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashSet.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashSet.java index d2fb907c1d..90efca13f4 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashSet.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashSet.java @@ -26,7 +26,7 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.locks.StampedLock; -import static com.google.common.base.Preconditions.checkArgument; +import static org.apache.activemq.artemis.utils.Preconditions.checkArgument; /** * Concurrent hash set for primitive longs diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashMapTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashMapTest.java index b08251fe44..1bef2b2847 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashMapTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashMapTest.java @@ -21,6 +21,7 @@ package org.apache.activemq.artemis.utils.collections; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -33,7 +34,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.LongFunction; -import com.google.common.collect.Lists; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -218,8 +218,8 @@ public class ConcurrentLongHashMapTest { map.put(0, "zero"); - assertEquals(map.keys(), Lists.newArrayList(0L)); - assertEquals(map.values(), Lists.newArrayList("zero")); + assertEquals(map.keys(), Arrays.asList(0L)); + assertEquals(map.values(), Arrays.asList("zero")); map.remove(0); @@ -232,21 +232,21 @@ public class ConcurrentLongHashMapTest { List keys = map.keys(); Collections.sort(keys); - assertEquals(keys, Lists.newArrayList(0L, 1L, 2L)); + assertEquals(keys, Arrays.asList(0L, 1L, 2L)); List values = map.values(); Collections.sort(values); - assertEquals(values, Lists.newArrayList("one", "two", "zero")); + assertEquals(values, Arrays.asList("one", "two", "zero")); map.put(1, "uno"); keys = map.keys(); Collections.sort(keys); - assertEquals(keys, Lists.newArrayList(0L, 1L, 2L)); + assertEquals(keys, Arrays.asList(0L, 1L, 2L)); values = map.values(); Collections.sort(values); - assertEquals(values, Lists.newArrayList("two", "uno", "zero")); + assertEquals(values, Arrays.asList("two", "uno", "zero")); map.clear(); assertTrue(map.isEmpty()); diff --git a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashSetTest.java b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashSetTest.java index 24337f10bd..d294243d08 100644 --- a/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashSetTest.java +++ b/artemis-commons/src/test/java/org/apache/activemq/artemis/utils/collections/ConcurrentLongHashSetTest.java @@ -21,15 +21,15 @@ package org.apache.activemq.artemis.utils.collections; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; +import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -194,7 +194,7 @@ public class ConcurrentLongHashSetTest { set.add(0L); - assertEquals(set.items(), Sets.newHashSet(0L)); + assertEquals(set.items(), new HashSet<>(Arrays.asList(0L))); set.remove(0L); @@ -204,9 +204,9 @@ public class ConcurrentLongHashSetTest { set.add(1L); set.add(2L); - List values = Lists.newArrayList(set.items()); + List values = new ArrayList<>(set.items()); Collections.sort(values); - assertEquals(values, Lists.newArrayList(0L, 1L, 2L)); + assertEquals(values, Arrays.asList(0L, 1L, 2L)); set.clear(); assertTrue(set.isEmpty()); diff --git a/artemis-server/pom.xml b/artemis-server/pom.xml index eaafe5d3a5..05b1740a6f 100644 --- a/artemis-server/pom.xml +++ b/artemis-server/pom.xml @@ -138,10 +138,6 @@ geronimo-json_1.0_spec 1.0-alpha-1 - - com.google.guava - guava - junit junit diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/ActiveMQAbstractView.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/ActiveMQAbstractView.java index 7a2d347edd..265fb4215e 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/ActiveMQAbstractView.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/ActiveMQAbstractView.java @@ -19,13 +19,14 @@ package org.apache.activemq.artemis.core.management.impl.view; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; +import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; -import com.google.common.base.Predicate; -import com.google.common.collect.Collections2; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Ordering; import org.apache.activemq.artemis.api.core.JsonUtil; import org.apache.activemq.artemis.core.management.impl.view.predicate.ActiveMQFilterPredicate; import org.apache.activemq.artemis.utils.JsonLoader; @@ -64,7 +65,7 @@ public abstract class ActiveMQAbstractView { public String getResultsAsJson(int page, int pageSize) { JsonObjectBuilder obj = JsonLoader.createObjectBuilder(); JsonArrayBuilder array = JsonLoader.createArrayBuilder(); - collection = Collections2.filter(collection, getPredicate()); + collection = collection.stream().filter(getPredicate()).collect(Collectors.toList()); for (T element : getPagedResult(page, pageSize)) { JsonObjectBuilder jsonObjectBuilder = toJson(element); //toJson() may return a null @@ -78,42 +79,39 @@ public abstract class ActiveMQAbstractView { } public List getPagedResult(int page, int pageSize) { - ImmutableList.Builder builder = ImmutableList.builder(); + List builder = new ArrayList<>(); int start = (page - 1) * pageSize; int end = Math.min(page * pageSize, collection.size()); int i = 0; - for (T e : getOrdering().sortedCopy(collection)) { + for (T e : collection.stream().sorted(getComparator()).collect(Collectors.toList())) { if (i >= start && i < end) { builder.add(e); } i++; } - return builder.build(); + return Collections.unmodifiableList(builder); } - public Predicate getPredicate() { + public Predicate getPredicate() { return predicate; } - public Ordering getOrdering() { - return new Ordering() { - @Override - public int compare(T left, T right) { - try { - Object leftValue = getField(left, sortColumn); - Object rightValue = getField(right, sortColumn); - if (leftValue instanceof Comparable && rightValue instanceof Comparable) { - if (sortOrder.equals("desc")) { - return ((Comparable) rightValue).compareTo(leftValue); - } else { - return ((Comparable) leftValue).compareTo(rightValue); - } + public Comparator getComparator() { + return (left, right) -> { + try { + Object leftValue = getField(left, sortColumn); + Object rightValue = getField(right, sortColumn); + if (leftValue instanceof Comparable && rightValue instanceof Comparable) { + if (sortOrder.equals("desc")) { + return ((Comparable) rightValue).compareTo(leftValue); + } else { + return ((Comparable) leftValue).compareTo(rightValue); } - return 0; - } catch (Exception e) { - //LOG.info("Exception sorting destinations", e); - return 0; } + return 0; + } catch (Exception e) { + //LOG.info("Exception sorting destinations", e); + return 0; } }; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/predicate/ActiveMQFilterPredicate.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/predicate/ActiveMQFilterPredicate.java index 595b3bf9d9..fd951b8373 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/predicate/ActiveMQFilterPredicate.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/predicate/ActiveMQFilterPredicate.java @@ -17,8 +17,8 @@ package org.apache.activemq.artemis.core.management.impl.view.predicate; import java.util.Collection; +import java.util.function.Predicate; -import com.google.common.base.Predicate; public class ActiveMQFilterPredicate implements Predicate { @@ -40,7 +40,7 @@ public class ActiveMQFilterPredicate implements Predicate { } @Override - public boolean apply(T input) { + public boolean test(T input) { return true; } diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/predicate/AddressFilterPredicate.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/predicate/AddressFilterPredicate.java index 54081f4771..6c7789abfb 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/predicate/AddressFilterPredicate.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/predicate/AddressFilterPredicate.java @@ -35,7 +35,7 @@ public class AddressFilterPredicate extends ActiveMQFilterPredicate } @Override - public boolean apply(AddressInfo address) { + public boolean test(AddressInfo address) { if (f == null) return true; try { diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/predicate/ConnectionFilterPredicate.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/predicate/ConnectionFilterPredicate.java index 14996063e0..0b441f4a8b 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/predicate/ConnectionFilterPredicate.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/predicate/ConnectionFilterPredicate.java @@ -39,7 +39,7 @@ public class ConnectionFilterPredicate extends ActiveMQFilterPredicate } @Override - public boolean apply(QueueControl queue) { + public boolean test(QueueControl queue) { // Using switch over enum vs string comparison is better for perf. try { if (f == null) diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/predicate/SessionFilterPredicate.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/predicate/SessionFilterPredicate.java index 481e986a08..33c81dd10a 100644 --- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/predicate/SessionFilterPredicate.java +++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/view/predicate/SessionFilterPredicate.java @@ -31,7 +31,7 @@ public class SessionFilterPredicate extends ActiveMQFilterPredicate${hawtbuff.version} - - com.google.guava - guava - ${guava.version} - - org.jboss.logging jboss-logging diff --git a/tests/integration-tests/pom.xml b/tests/integration-tests/pom.xml index 98d67ce926..0558075876 100644 --- a/tests/integration-tests/pom.xml +++ b/tests/integration-tests/pom.xml @@ -387,10 +387,6 @@ spring-jms test - - com.google.guava - guava - commons-io commons-io