http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/main/java/org/apache/sshd/common/util/Base64.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/Base64.java b/sshd-core/src/main/java/org/apache/sshd/common/util/Base64.java index 7a897c7..8b3b3cb 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/util/Base64.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/util/Base64.java @@ -1,21 +1,20 @@ /* - * 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 + * 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. + * 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.sshd.common.util; @@ -24,24 +23,24 @@ import java.security.InvalidParameterException; /** * Provides Base64 encoding and decoding as defined by RFC 2045. + * <p/> + * <p>This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> + * from RFC 2045 <cite>Multipurpose Internet Mail Extensions (MIME) Part One: + * Format of Internet Message Bodies</cite> by Freed and Borenstein.</p> * - * <p>This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> - * from RFC 2045 <cite>Multipurpose Internet Mail Extensions (MIME) Part One: - * Format of Internet Message Bodies</cite> by Freed and Borenstein.</p> - * - * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a> - * - * This class was * @author Apache Software Foundation commons codec (http://commons.apache.org/codec/) * @author <a href="http://mina.apache.org">Apache MINA Project</a> - * TODO replace this class with {@code java.util.Base64} when upgrading to JDK 1.8 + * TODO replace this class with {@code java.util.Base64} when upgrading to JDK 1.8 + * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a> + * <p/> + * This class was */ public class Base64 { /** * Chunk size per RFC 2045 section 6.8. - * - * <p>The {@value} character limit does not count the trailing CRLF, but counts + * <p/> + * <p>The {@value} character limit does not count the trailing CRLF, but counts * all other characters, including any equal signs.</p> * * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a> @@ -136,13 +135,7 @@ public class Base64 { } private static boolean isBase64(byte octect) { - if (octect == PAD) { - return true; - } else if (base64Alphabet[octect] == -1) { - return false; - } else { - return true; - } + return octect == PAD || base64Alphabet[octect] != -1; } /** @@ -151,7 +144,7 @@ public class Base64 { * * @param arrayOctect byte array to test * @return true if all bytes are valid characters in the Base64 - * alphabet or if the byte array is empty; false, otherwise + * alphabet or if the byte array is empty; false, otherwise */ public static boolean isArrayByteBase64(byte[] arrayOctect) { @@ -170,7 +163,7 @@ public class Base64 { return true; } - public static String encodeToString(byte ... bytes) { + public static String encodeToString(byte... bytes) { return new String(encodeBase64(bytes), StandardCharsets.UTF_8); } @@ -203,10 +196,10 @@ public class Base64 { * supplied object is not of type byte[]. * * @param pObject Object to decode - * @return An object (of type byte[]) containing the - * binary data which corresponds to the byte[] supplied. + * @return An object (of type byte[]) containing the + * binary data which corresponds to the byte[] supplied. * @throws InvalidParameterException if the parameter supplied is not - * of type byte[] + * of type byte[] */ public Object decode(Object pObject) { if (!(pObject instanceof byte[])) { @@ -231,8 +224,8 @@ public class Base64 { * chunking the output into 76 character blocks. * * @param binaryData Array containing binary data to encode. - * @param isChunked if isChunked is true this encoder will chunk - * the base64 output into 76 character blocks + * @param isChunked if isChunked is true this encoder will chunk + * the base64 output into 76 character blocks * @return Base64-encoded data. */ public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { @@ -256,17 +249,21 @@ public class Base64 { // allow for extra length to account for the separator(s) if (isChunked) { - nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math.ceil((float) encodedDataLength / CHUNK_SIZE)); + nbrChunks = CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math.ceil((float) encodedDataLength / CHUNK_SIZE); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; - byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; + byte k; + byte l; + byte b1; + byte b2; + byte b3; int encodedIndex = 0; - int dataIndex = 0; - int i = 0; + int dataIndex; + int i; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; @@ -279,9 +276,9 @@ public class Base64 { l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); - byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); - byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); - byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc); + byte val1 = (b1 & SIGN) == 0 ? (byte) (b1 >> 2) : (byte) (b1 >> 2 ^ 0xc0); + byte val2 = (b2 & SIGN) == 0 ? (byte) (b2 >> 4) : (byte) (b2 >> 4 ^ 0xf0); + byte val3 = (b3 & SIGN) == 0 ? (byte) (b3 >> 6) : (byte) (b3 >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; @@ -308,7 +305,7 @@ public class Base64 { if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte) (b1 & 0x03); - byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) (b1 >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; @@ -320,8 +317,8 @@ public class Base64 { l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); - byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); - byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) (b1 >> 2 ^ 0xc0); + byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) (b2 >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; @@ -365,23 +362,27 @@ public class Base64 { int numberQuadruple = base64Data.length / FOURBYTE; byte decodedData[]; - byte b1, b2, b3, b4, marker0, marker1; + byte b1; + byte b2; + byte b3; + byte b4; + byte marker0; + byte marker1; // Throw away anything not in base64Data int encodedIndex = 0; int dataIndex; - { - // this sizes the output array properly - rlw - int lastData = base64Data.length; - // ignore the '=' padding - while (base64Data[lastData - 1] == PAD) { - if (--lastData == 0) { - return GenericUtils.EMPTY_BYTE_ARRAY; - } + + // this sizes the output array properly - rlw + int lastData = base64Data.length; + // ignore the '=' padding + while (base64Data[lastData - 1] == PAD) { + if (--lastData == 0) { + return GenericUtils.EMPTY_BYTE_ARRAY; } - decodedData = new byte[lastData - numberQuadruple]; } + decodedData = new byte[lastData - numberQuadruple]; for (int i = 0; i < numberQuadruple; i++) { dataIndex = i * 4; @@ -418,7 +419,7 @@ public class Base64 { * Discards any whitespace from a base-64 encoded block. * * @param data The base-64 encoded data to discard the whitespace - * from. + * from. * @return The data, less whitespace (see RFC 2045). */ static byte[] discardWhitespace(byte[] data) { @@ -451,7 +452,7 @@ public class Base64 { * encoded data." * * @param data The base-64 encoded data to groom - * @return The data, less non-base64 characters (see RFC 2045) - + * @return The data, less non-base64 characters (see RFC 2045) - * may be same as input if all data was base-64 */ public static byte[] discardNonBase64(byte[] data) { @@ -475,7 +476,8 @@ public class Base64 { if (groomedData == null) { groomedData = new byte[data.length - 1 /* the current character, which is NOT BASE64 */]; - if ((bytesCopied=i) > 0) { + bytesCopied = i; + if (bytesCopied > 0) { System.arraycopy(data, 0, groomedData, 0, bytesCopied); } } @@ -509,10 +511,10 @@ public class Base64 { * supplied object is not of type byte[]. * * @param pObject Object to encode - * @return An object (of type byte[]) containing the - * base64 encoded data which corresponds to the byte[] supplied. + * @return An object (of type byte[]) containing the + * base64 encoded data which corresponds to the byte[] supplied. * @throws InvalidParameterException if the parameter supplied is not - * of type byte[] + * of type byte[] */ public Object encode(Object pObject) { if (!(pObject instanceof byte[])) {
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/main/java/org/apache/sshd/common/util/CloseableUtils.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/CloseableUtils.java b/sshd-core/src/main/java/org/apache/sshd/common/util/CloseableUtils.java index 2acda50..6b81aae 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/util/CloseableUtils.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/util/CloseableUtils.java @@ -43,8 +43,12 @@ import org.apache.sshd.common.util.logging.AbstractLoggingBean; * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> */ public final class CloseableUtils { + + /** + * Private Constructor + */ private CloseableUtils() { - throw new UnsupportedOperationException("No instance"); + throw new UnsupportedOperationException("No instance allowed"); } // TODO once JDK 8+ becomes the minimum for this project, make it a static method in the Closeable interface @@ -54,7 +58,7 @@ public final class CloseableUtils { } if ((!closeable.isClosed()) && (!closeable.isClosing())) { - CloseFuture future=closeable.close(true); + CloseFuture future = closeable.close(true); future.await(); // TODO use verify + configurable timeout } } @@ -65,7 +69,7 @@ public final class CloseableUtils { return future; } - public static class Builder implements ObjectBuilder<Closeable> { + public static final class Builder implements ObjectBuilder<Closeable> { private final Object lock; private final List<Closeable> closeables = new ArrayList<Closeable>(); @@ -150,11 +154,11 @@ public final class CloseableUtils { } - public static abstract class IoBaseCloseable extends AbstractLoggingBean implements Closeable { + public abstract static class IoBaseCloseable extends AbstractLoggingBean implements Closeable { protected IoBaseCloseable() { super(); } - + protected IoBaseCloseable(String discriminator) { super(discriminator); } @@ -162,11 +166,7 @@ public final class CloseableUtils { // TODO once JDK 8+ becomes the minimum for this project, make it a default method instead of this class @Override public boolean isOpen() { - if (isClosed() || isClosing()) { - return false; - } else { - return true; - } + return !(isClosed() || isClosing()); } // TODO once JDK 8+ becomes the minimum for this project, make it a default method instead of this class @@ -190,10 +190,12 @@ public final class CloseableUtils { public boolean isClosed() { return future.isClosed(); } + @Override public boolean isClosing() { return closing.get(); } + @Override public CloseFuture close(boolean immediately) { if (closing.compareAndSet(false, true)) { @@ -207,7 +209,7 @@ public final class CloseableUtils { } } - private static class ParallelCloseable extends SimpleCloseable { + private static final class ParallelCloseable extends SimpleCloseable { private final Iterable<? extends Closeable> closeables; @@ -308,16 +310,23 @@ public final class CloseableUtils { } } - public static abstract class AbstractCloseable extends IoBaseCloseable { + public abstract static class AbstractCloseable extends IoBaseCloseable { protected enum State { Opened, Graceful, Immediate, Closed } - /** Lock object for this session state */ + + /** + * Lock object for this session state + */ protected final Object lock = new Object(); - /** State of this object */ + /** + * State of this object + */ protected final AtomicReference<State> state = new AtomicReference<>(State.Opened); - /** A future that will be set 'closed' when the object is actually closed */ + /** + * A future that will be set 'closed' when the object is actually closed + */ protected final CloseFuture closeFuture = new DefaultCloseFuture(lock); protected AbstractCloseable() { @@ -394,7 +403,7 @@ public final class CloseableUtils { /** * doCloseImmediately is called once and only once * with state == Immediate - * + * <p/> * Overriding methods should always call the base implementation. * It may be called concurrently while preClose() or doCloseGracefully is executing */ @@ -410,9 +419,7 @@ public final class CloseableUtils { } - public static abstract class AbstractInnerCloseable extends AbstractCloseable { - - protected abstract Closeable getInnerCloseable(); + public abstract static class AbstractInnerCloseable extends AbstractCloseable { protected AbstractInnerCloseable() { super(); @@ -422,6 +429,8 @@ public final class CloseableUtils { super(discriminator); } + protected abstract Closeable getInnerCloseable(); + @Override protected CloseFuture doCloseGracefully() { return getInnerCloseable().close(false); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/main/java/org/apache/sshd/common/util/DirectoryScanner.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/DirectoryScanner.java b/sshd-core/src/main/java/org/apache/sshd/common/util/DirectoryScanner.java index 95ab94d..f6f9c14 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/util/DirectoryScanner.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/util/DirectoryScanner.java @@ -25,12 +25,12 @@ import java.util.List; /** * <p>Class for scanning a directory for files/directories which match certain * criteria.</p> - * + * <p/> * <p>These criteria consist of selectors and patterns which have been specified. * With the selectors you can select which files you want to have included. * Files which are not selected are excluded. With patterns you can include * or exclude files based on their filename.</p> - * + * <p/> * <p>The idea is simple. A given directory is recursively scanned for all files * and directories. Each file/directory is matched against a set of selectors, * including special support for matching against filenames with include and @@ -38,12 +38,12 @@ import java.util.List; * pattern of the include pattern list or other file selector, and don't match * any pattern of the exclude pattern list or fail to match against a required * selector will be placed in the list of files/directories found.</p> - * + * <p/> * <p>When no list of include patterns is supplied, "**" will be used, which * means that everything will be matched. When no list of exclude patterns is * supplied, an empty list is used, such that nothing will be excluded. When * no selectors are supplied, none are applied.</p> - * + * <p/> * <p>The filename pattern matching is done as follows: * The name to be matched is split up in path segments. A path segment is the * name of a directory or file, which is bounded by @@ -51,11 +51,11 @@ import java.util.List; * For example, "abc/def/ghi/xyz.java" is split up in the segments "abc", * "def","ghi" and "xyz.java". * The same is done for the pattern against which should be matched.</p> - * + * <p/> * <p>The segments of the name and the pattern are then matched against each * other. When '**' is used for a path segment in the pattern, it matches * zero or more path segments of the name.</p> - * + * <p/> * <p>There is a special case regarding the use of <code>File.separator</code>s * at the beginning of the pattern and the string to match:<br> * When a pattern starts with a <code>File.separator</code>, the string @@ -64,12 +64,12 @@ import java.util.List; * string to match may not start with a <code>File.separator</code>. * When one of these rules is not obeyed, the string will not * match.</p> - * + * <p/> * <p>When a name path segment is matched against a pattern path segment, the * following special characters can be used:<br> * '*' matches zero or more characters<br> * '?' matches one character.</p> - * + * <p/> * <p>Examples: * <br> * <code>"**\*.class"</code> matches all <code>.class</code> files/dirs in a directory tree. @@ -82,10 +82,10 @@ import java.util.List; * <code>"**\test\**\XYZ*"</code> matches all files/dirs which start with <code>"XYZ"</code> and where * there is a parent directory called test (e.g. <code>"abc\test\def\ghi\XYZ123"</code>). * </p> - * + * <p/> * <p>Case sensitivity may be turned off if necessary. By default, it is * turned on.</p> - * + * <p/> * <p>Example of usage:</p> * <pre> * String[] includes = {"**\\*.class"}; @@ -182,7 +182,7 @@ public class DirectoryScanner { * <p>Sets the list of include patterns to use. All '/' and '\' characters * are replaced by <code>File.separatorChar</code>, so the separator used * need not match <code>File.separatorChar</code>.</p> - * + * <p/> * <p>When a pattern ends with a '/' or '\', "**" is appended.</p> * * @param includes A list of include patterns. @@ -276,7 +276,7 @@ public class DirectoryScanner { * The names are relative to the base directory. * * @return the names of the files which matched at least one of the - * include patterns and none of the exclude patterns. + * include patterns and none of the exclude patterns. */ public String[] getIncludedFiles() { String[] files = new String[filesIncluded.size()]; @@ -290,7 +290,7 @@ public class DirectoryScanner { * * @param name The name to match. Must not be {@code null}. * @return <code>true</code> when the name matches against at least one - * include pattern, or <code>false</code> otherwise. + * include pattern, or <code>false</code> otherwise. */ protected boolean isIncluded(String name) { for (String include : includes) { @@ -307,7 +307,7 @@ public class DirectoryScanner { * * @param name The name to match. Must not be {@code null}. * @return <code>true</code> when the name matches against the start of at - * least one include pattern, or <code>false</code> otherwise. + * least one include pattern, or <code>false</code> otherwise. */ protected boolean couldHoldIncluded(String name) { for (String include : includes) { @@ -347,7 +347,7 @@ public class DirectoryScanner { /** * <p>Replace a String with another String inside a larger String, * for the first <code>max</code> values of the search String.</p> - * + * <p/> * <p>A {@code null} reference passed to this method is a no-op.</p> * * @param text text to search and replace in @@ -362,7 +362,8 @@ public class DirectoryScanner { } StringBuilder buf = new StringBuilder(text.length()); - int start = 0, end; + int start = 0; + int end; while ((end = text.indexOf(repl, start)) != -1) { buf.append(text.substring(start, end)).append(with); start = end + repl.length(); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/main/java/org/apache/sshd/common/util/GenericUtils.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/GenericUtils.java b/sshd-core/src/main/java/org/apache/sshd/common/util/GenericUtils.java index d18efc4..8d17799 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/util/GenericUtils.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/util/GenericUtils.java @@ -36,23 +36,36 @@ import java.util.TreeSet; * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> */ public final class GenericUtils { - public static final byte[] EMPTY_BYTE_ARRAY = { }; - public static final String[] EMPTY_STRING_ARRAY = { }; - public static final Object[] EMPTY_OBJECT_ARRAY = { }; - + + public static final byte[] EMPTY_BYTE_ARRAY = {}; + public static final String[] EMPTY_STRING_ARRAY = {}; + public static final Object[] EMPTY_OBJECT_ARRAY = {}; + /** * The complement of {@link String#CASE_INSENSITIVE_ORDER} */ public static final Comparator<String> CASE_SENSITIVE_ORDER = new Comparator<String>() { - @Override - public int compare(String s1, String s2) { - if (s1 == s2) { - return 0; - } else { - return s1.compareTo(s2); - } + @Override + public int compare(String s1, String s2) { + if (s1 == s2) { + return 0; + } else { + return s1.compareTo(s2); } - }; + } + }; + + public static final String QUOTES = "\"'"; + + @SuppressWarnings("rawtypes") + private static final Comparator<Comparable> NATURAL_ORDER_COMPARATOR = new Comparator<Comparable>() { + // TODO for JDK-8 use Comparator.naturalOrder() + @Override + @SuppressWarnings("unchecked") + public int compare(Comparable c1, Comparable c2) { + return c1.compareTo(c2); + } + }; private GenericUtils() { throw new UnsupportedOperationException("No instance"); @@ -70,9 +83,9 @@ public final class GenericUtils { if (s1 == s2) { return 0; } else if (s1 == null) { - return (+1); // push null(s) to end + return +1; // push null(s) to end } else if (s2 == null) { - return (-1); // push null(s) to end + return -1; // push null(s) to end } else if (caseSensitive) { return s1.compareTo(s2); } else { @@ -81,19 +94,11 @@ public final class GenericUtils { } public static int length(CharSequence cs) { - if (cs == null) { - return 0; - } else { - return cs.length(); - } + return cs == null ? 0 : cs.length(); } public static boolean isEmpty(CharSequence cs) { - if (length(cs) <= 0) { - return true; - } else { - return false; - } + return length(cs) <= 0; } // a List would be better, but we want to be compatible with String.split(...) @@ -101,30 +106,33 @@ public final class GenericUtils { if (isEmpty(s)) { return EMPTY_STRING_ARRAY; } - - int lastPos=0, curPos=s.indexOf(ch); + + int lastPos = 0; + int curPos = s.indexOf(ch); if (curPos < 0) { - return new String[] { s }; + return new String[]{s}; } - - Collection<String> values=new LinkedList<String>(); + + Collection<String> values = new LinkedList<>(); do { - String v=s.substring(lastPos, curPos); + String v = s.substring(lastPos, curPos); values.add(v); - + // skip separator - if ((lastPos = curPos + 1) >= s.length()) { + lastPos = curPos + 1; + if (lastPos >= s.length()) { break; } - - if ((curPos = s.indexOf(ch, lastPos)) < lastPos) { + + curPos = s.indexOf(ch, lastPos); + if (curPos < lastPos) { break; // no more separators } - } while(curPos < s.length()); - + } while (curPos < s.length()); + // check if any leftovers if (lastPos < s.length()) { - String v=s.substring(lastPos); + String v = s.substring(lastPos); values.add(v); } @@ -138,21 +146,21 @@ public final class GenericUtils { public static String join(Iterable<?> iter, char ch) { return join((iter == null) ? null : iter.iterator(), ch); } - + public static String join(Iterator<?> iter, char ch) { if ((iter == null) || (!iter.hasNext())) { return ""; } - - StringBuilder sb=new StringBuilder(); + + StringBuilder sb = new StringBuilder(); do { // we already asked hasNext... - Object o=iter.next(); + Object o = iter.next(); if (sb.length() > 0) { sb.append(ch); } sb.append(Objects.toString(o)); - } while(iter.hasNext()); - + } while (iter.hasNext()); + return sb.toString(); } @@ -163,79 +171,51 @@ public final class GenericUtils { public static String join(Iterable<?> iter, CharSequence sep) { return join((iter == null) ? null : iter.iterator(), sep); } - + public static String join(Iterator<?> iter, CharSequence sep) { if ((iter == null) || (!iter.hasNext())) { return ""; } - - StringBuilder sb=new StringBuilder(); + + StringBuilder sb = new StringBuilder(); do { // we already asked hasNext... - Object o=iter.next(); + Object o = iter.next(); if (sb.length() > 0) { sb.append(sep); } sb.append(Objects.toString(o)); - } while(iter.hasNext()); - + } while (iter.hasNext()); + return sb.toString(); } - + public static int size(Collection<?> c) { - if (c == null) { - return 0; - } else { - return c.size(); - } + return c == null ? 0 : c.size(); } public static boolean isEmpty(Collection<?> c) { - if (size(c) <= 0) { - return true; - } else { - return false; - } + return size(c) <= 0; } - public static int size(Map<?,?> m) { - if (m == null) { - return 0; - } else { - return m.size(); - } + public static int size(Map<?, ?> m) { + return m == null ? 0 : m.size(); } - public static boolean isEmpty(Map<?,?> m) { - if (size(m) <= 0) { - return true; - } else { - return false; - } + public static boolean isEmpty(Map<?, ?> m) { + return size(m) <= 0; } public static boolean isEmpty(byte[] a) { - if (length(a) <= 0) { - return true; - } else { - return false; - } + return length(a) <= 0; } - public static int length(byte ... a) { - if (a == null) { - return 0; - } else { - return a.length; - } + public static int length(byte... a) { + return a == null ? 0 : a.length; } @SafeVarargs - public static <T> int length(T ... a) { - if (a == null) { - return 0; - } else { - return a.length; - } + public static <T> int length(T... a) { + return a == null ? 0 : a.length; } public static <T> boolean isEmpty(Iterable<? extends T> iter) { @@ -249,26 +229,16 @@ public final class GenericUtils { } public static <T> boolean isEmpty(Iterator<? extends T> iter) { - if (iter == null) { - return true; - } else if (iter.hasNext()) { - return false; // debug breakpoint - } else { - return true; - } + return iter == null || !iter.hasNext(); } @SafeVarargs - public static <T> boolean isEmpty(T ... a) { - if (length(a) <= 0) { - return true; - } else { - return false; - } + public static <T> boolean isEmpty(T... a) { + return length(a) <= 0; } @SafeVarargs // there is no EnumSet.of(...) so we have to provide our own - public static <E extends Enum<E>> Set<E> of(E ... values) { + public static <E extends Enum<E>> Set<E> of(E... values) { return of(isEmpty(values) ? Collections.<E>emptySet() : Arrays.asList(values)); } @@ -277,7 +247,7 @@ public final class GenericUtils { return Collections.emptySet(); } - Set<E> result=null; + Set<E> result = null; for (E v : values) { /* * A trick to compensate for the fact that we do not have @@ -293,20 +263,10 @@ public final class GenericUtils { return result; } - @SuppressWarnings("rawtypes") - private static final Comparator<Comparable> naturalOrderComparator=new Comparator<Comparable>() { - // TODO for JDK-8 use Comparator.naturalOrder() - @Override - @SuppressWarnings("unchecked") - public int compare(Comparable c1, Comparable c2) { - return c1.compareTo(c2); - } - }; - - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) public static <V extends Comparable<V>> Comparator<V> naturalComparator() { // TODO for JDK-8 use Comparator.naturalOrder() - return (Comparator) naturalOrderComparator; + return (Comparator) NATURAL_ORDER_COMPARATOR; } public static <V extends Comparable<V>> SortedSet<V> asSortedSet(Collection<? extends V> values) { @@ -315,22 +275,19 @@ public final class GenericUtils { } /** - * @param comp The (non-{@code null}) {@link Comparator} to use + * @param comp The (non-{@code null}) {@link Comparator} to use * @param values The values to be added (ignored if {@code null)) * @return A {@link SortedSet} containing the values (if any) sorted * using the provided comparator */ public static <V> SortedSet<V> asSortedSet(Comparator<? super V> comp, Collection<? extends V> values) { // TODO for JDK-8 return Collections.emptySortedSet() - SortedSet<V> set=new TreeSet<V>(ValidateUtils.checkNotNull(comp, "No comparator")); + SortedSet<V> set = new TreeSet<V>(ValidateUtils.checkNotNull(comp, "No comparator")); if (size(values) > 0) { set.addAll(values); } - return set; } - - public static final String QUOTES="\"'"; /** * @param s The {@link CharSequence} to be checked @@ -339,24 +296,24 @@ public final class GenericUtils { * nothing is done * @see #stripDelimiters(CharSequence, char) */ - public static CharSequence stripQuotes(CharSequence s) { + public static CharSequence stripQuotes(CharSequence s) { if (isEmpty(s)) { return s; } - - for (int index=0; index < QUOTES.length(); index++) { + + for (int index = 0; index < QUOTES.length(); index++) { char delim = QUOTES.charAt(index); CharSequence v = stripDelimiters(s, delim); if (v != s) { // if stripped one don't continue return v; } } - + return s; } /** - * @param s The {@link CharSequence} to be checked + * @param s The {@link CharSequence} to be checked * @param delim The expected delimiter * @return If the sequence contains the delimiter on <U>both</U> ends, * then it is are stripped, otherwise nothing is done @@ -365,7 +322,7 @@ public final class GenericUtils { if (isEmpty(s) || (s.length() < 2)) { return s; } - + int lastPos = s.length() - 1; if ((s.charAt(0) != delim) || (s.charAt(lastPos) != delim)) { return s; @@ -373,7 +330,7 @@ public final class GenericUtils { return s.subSequence(1, lastPos); } } - + /** * @param t The original {@link Throwable} - ignored if {@code null} * @return If {@link Throwable#getCause()} is non-{@code null} then @@ -384,7 +341,7 @@ public final class GenericUtils { if (t == null) { return t; } - + Throwable c = t.getCause(); if (c == null) { return t; @@ -398,8 +355,9 @@ public final class GenericUtils { * current exception is {@code null} then the new one becomes the current, * otherwise the new one is added as a <U>suppressed</U> exception to the * current one + * * @param current The current exception - * @param extra The extra/new exception + * @param extra The extra/new exception * @return The resolved exception * @see Throwable#addSuppressed(Throwable) */ @@ -407,18 +365,18 @@ public final class GenericUtils { if (current == null) { return extra; } - + if ((extra == null) || (extra == current)) { return current; } - + current.addSuppressed(extra); return current; } // TODO in JDK-8 use Long.hashCode(long) public static int hashCode(long value) { - return (int)(value ^ (value >>> 32)); + return (int) (value ^ (value >>> 32)); } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/main/java/org/apache/sshd/common/util/Int2IntFunction.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/Int2IntFunction.java b/sshd-core/src/main/java/org/apache/sshd/common/util/Int2IntFunction.java index 68b1588..ffaaef6 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/util/Int2IntFunction.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/util/Int2IntFunction.java @@ -23,25 +23,27 @@ package org.apache.sshd.common.util; * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> */ public interface Int2IntFunction { + + /** + * An {@link Int2IntFunction} that returns same value as input + */ + Int2IntFunction IDENTITY = new Int2IntFunction() { + @Override + public int apply(int value) { + return value; + } + }; + /** * @param value Argument * @return Function result */ int apply(int value); - /** - * An {@link Int2IntFunction} that returns same value as input - */ - Int2IntFunction IDENTITY = new Int2IntFunction() { - @Override - public int apply(int value) { - return value; - } - }; + final class Utils { - public static final class Utils { private Utils() { - throw new UnsupportedOperationException("No instance"); + throw new UnsupportedOperationException("No instance allowed"); } public static Int2IntFunction sub(int delta) { @@ -60,7 +62,7 @@ public interface Int2IntFunction { }; } } - + public static Int2IntFunction mul(final int factor) { if (factor == 1) { return IDENTITY; http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/main/java/org/apache/sshd/common/util/ObjectBuilder.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/ObjectBuilder.java b/sshd-core/src/main/java/org/apache/sshd/common/util/ObjectBuilder.java index fd3fce3..9072b03 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/util/ObjectBuilder.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/util/ObjectBuilder.java @@ -21,10 +21,11 @@ package org.apache.sshd.common.util; /** * A generic builder interface + * * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> */ public interface ObjectBuilder<T> { - T build(); + T build(); } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/main/java/org/apache/sshd/common/util/OsUtils.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/OsUtils.java b/sshd-core/src/main/java/org/apache/sshd/common/util/OsUtils.java index 529899c..0319fd9 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/util/OsUtils.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/util/OsUtils.java @@ -24,24 +24,30 @@ package org.apache.sshd.common.util; * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> */ public final class OsUtils { - private static final boolean win32; + + private static final boolean WIN32; + + private OsUtils() { + throw new UnsupportedOperationException("No instance allowed"); + } static { String os = System.getProperty("os.name").toLowerCase(); - win32 = os.contains("windows"); + WIN32 = os.contains("windows"); } - /** @return true if the host is a UNIX system (and not Windows). */ + /** + * @return true if the host is a UNIX system (and not Windows). + */ public static boolean isUNIX() { - return !win32; + return !WIN32; } - /** @return true if the host is Windows (and not UNIX). */ + /** + * @return true if the host is Windows (and not UNIX). + */ public static boolean isWin32() { - return win32; + return WIN32; } - private OsUtils () { - throw new UnsupportedOperationException("No instance allowed"); - } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/main/java/org/apache/sshd/common/util/Pair.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/Pair.java b/sshd-core/src/main/java/org/apache/sshd/common/util/Pair.java index 21e23d6..c580dc5 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/util/Pair.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/util/Pair.java @@ -22,9 +22,10 @@ import java.util.Objects; /** * Represents a pair of values + * * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> */ -public class Pair<U,V> { +public class Pair<U, V> { private final U first; private final V second; http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/main/java/org/apache/sshd/common/util/SecurityUtils.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/SecurityUtils.java b/sshd-core/src/main/java/org/apache/sshd/common/util/SecurityUtils.java index 38ccf45..d93460c 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/util/SecurityUtils.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/util/SecurityUtils.java @@ -34,7 +34,6 @@ import java.security.NoSuchProviderException; import java.security.SecureRandom; import java.security.Signature; import java.util.concurrent.Callable; - import javax.crypto.Cipher; import javax.crypto.KeyAgreement; import javax.crypto.Mac; @@ -64,12 +63,12 @@ import org.slf4j.LoggerFactory; * * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> */ -public class SecurityUtils { +public final class SecurityUtils { public static final String BOUNCY_CASTLE = "BC"; private static final Logger LOG = LoggerFactory.getLogger(SecurityUtils.class); - private static String securityProvider = null; + private static String securityProvider; private static Boolean registerBouncyCastle; private static boolean registrationDone; private static Boolean hasEcc; @@ -157,12 +156,12 @@ public class SecurityUtils { } /* -------------------------------------------------------------------- */ - + // TODO in JDK-8 make this an interface... private static class BouncyCastleInputStreamLoader { public static KeyPair loadKeyPair(String resourceKey, InputStream inputStream, FilePasswordProvider provider) throws IOException, GeneralSecurityException { - try(PEMParser r = new PEMParser(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { + try (PEMParser r = new PEMParser(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { Object o = r.readObject(); JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter(); @@ -170,14 +169,14 @@ public class SecurityUtils { if (o instanceof PEMEncryptedKeyPair) { ValidateUtils.checkNotNull(provider, "No password provider for resource=%s", resourceKey); - String password = ValidateUtils.checkNotNullAndNotEmpty(provider.getPassword(resourceKey), "No password provided for resource=%s", resourceKey); + String password = ValidateUtils.checkNotNullAndNotEmpty(provider.getPassword(resourceKey), "No password provided for resource=%s", resourceKey); JcePEMDecryptorProviderBuilder decryptorBuilder = new JcePEMDecryptorProviderBuilder(); PEMDecryptorProvider pemDecryptor = decryptorBuilder.build(password.toCharArray()); o = ((PEMEncryptedKeyPair) o).decryptKeyPair(pemDecryptor); } if (o instanceof PEMKeyPair) { - return pemConverter.getKeyPair((PEMKeyPair)o); + return pemConverter.getKeyPair((PEMKeyPair) o); } else if (o instanceof KeyPair) { return (KeyPair) o; } else { @@ -189,34 +188,34 @@ public class SecurityUtils { /** * @param resourceKey An identifier of the key being loaded - used as - * argument to the {@link FilePasswordProvider#getPassword(String)} - * invocation + * argument to the {@link FilePasswordProvider#getPassword(String)} + * invocation * @param inputStream The {@link InputStream} for the <U>private</U> key - * @param provider A {@link FilePasswordProvider} - may be {@code null} - * if the loaded key is <U>guaranteed</U> not to be encrypted + * @param provider A {@link FilePasswordProvider} - may be {@code null} + * if the loaded key is <U>guaranteed</U> not to be encrypted * @return The loaded {@link KeyPair} - * @throws IOException If failed to read/parse the input stream + * @throws IOException If failed to read/parse the input stream * @throws GeneralSecurityException If failed to generate the keys - specifically, - * {@link NoSuchProviderException} is thrown also if {@link #isBouncyCastleRegistered()} - * is {@code false} + * {@link NoSuchProviderException} is thrown also if {@link #isBouncyCastleRegistered()} + * is {@code false} */ public static KeyPair loadKeyPairIdentity(String resourceKey, InputStream inputStream, FilePasswordProvider provider) throws IOException, GeneralSecurityException { if (!isBouncyCastleRegistered()) { throw new NoSuchProviderException("BouncyCastle not registered"); } - + return BouncyCastleInputStreamLoader.loadKeyPair(resourceKey, inputStream, provider); } /* -------------------------------------------------------------------- */ // use a separate class in order to avoid direct dependency - private static class BouncyCastleFileKeyPairProvider extends AbstractFileKeyPairProvider { + private static final class BouncyCastleFileKeyPairProvider extends AbstractFileKeyPairProvider { private BouncyCastleFileKeyPairProvider() { ValidateUtils.checkTrue(isBouncyCastleRegistered(), "BouncyCastle not registered"); } - + @Override protected KeyPair doLoadKey(String resourceKey, InputStream inputStream, FilePasswordProvider provider) throws IOException, GeneralSecurityException { @@ -231,7 +230,7 @@ public class SecurityUtils { /* -------------------------------------------------------------------- */ - private static class BouncyCastleClassLoadableResourceKeyPairProvider extends AbstractClassLoadableResourceKeyPairProvider { + private static final class BouncyCastleClassLoadableResourceKeyPairProvider extends AbstractClassLoadableResourceKeyPairProvider { private BouncyCastleClassLoadableResourceKeyPairProvider() { ValidateUtils.checkTrue(isBouncyCastleRegistered(), "BouncyCastle not registered"); } @@ -250,7 +249,7 @@ public class SecurityUtils { /* -------------------------------------------------------------------- */ - private static class BouncyCastleGeneratorHostKeyProvider extends AbstractGeneratorHostKeyProvider { + private static final class BouncyCastleGeneratorHostKeyProvider extends AbstractGeneratorHostKeyProvider { private BouncyCastleGeneratorHostKeyProvider(Path path) { ValidateUtils.checkTrue(isBouncyCastleRegistered(), "BouncyCastle not registered"); setPath(path); @@ -264,25 +263,25 @@ public class SecurityUtils { @SuppressWarnings("deprecation") @Override protected void doWriteKeyPair(String resourceKey, KeyPair kp, OutputStream outputStream) throws IOException, GeneralSecurityException { - try(org.bouncycastle.openssl.PEMWriter w = - new org.bouncycastle.openssl.PEMWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8))) { + try (org.bouncycastle.openssl.PEMWriter w = + new org.bouncycastle.openssl.PEMWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8))) { w.writeObject(kp); w.flush(); } } } - + @SuppressWarnings("synthetic-access") public static AbstractGeneratorHostKeyProvider createGeneratorHostKeyProvider(Path path) { - return new BouncyCastleGeneratorHostKeyProvider(path ); + return new BouncyCastleGeneratorHostKeyProvider(path); } /* -------------------------------------------------------------------- */ - + /** * Named factory for the BouncyCastle <code>Random</code> */ - private static class BouncyCastleRandomFactory implements RandomFactory { + private static final class BouncyCastleRandomFactory implements RandomFactory { private static final BouncyCastleRandomFactory INSTANCE = new BouncyCastleRandomFactory(); private BouncyCastleRandomFactory() { @@ -313,7 +312,7 @@ public class SecurityUtils { * * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> */ - private static class BouncyCastleRandom extends AbstractRandom { + private static final class BouncyCastleRandom extends AbstractRandom { private final RandomGenerator random; @@ -337,27 +336,28 @@ public class SecurityUtils { public int random(int n) { if (n > 0) { if ((n & -n) == n) { - return (int)((n * (long) next(31)) >> 31); + return (int) ((n * (long) next(31)) >> 31); } - int bits, val; + int bits; + int val; do { bits = next(31); val = bits % n; - } while (bits - val + (n-1) < 0); + } while (bits - val + (n - 1) < 0); return val; } throw new IllegalArgumentException("Limit must be positive: " + n); } - final protected int next(int numBits) { - int bytes = (numBits+7)/8; + private int next(int numBits) { + int bytes = (numBits + 7) / 8; byte next[] = new byte[bytes]; int ret = 0; random.nextBytes(next); for (int i = 0; i < bytes; i++) { ret = (next[i] & 0xFF) | (ret << 8); } - return ret >>> (bytes*8 - numBits); + return ret >>> (bytes * 8 - numBits); } } @@ -400,7 +400,7 @@ public class SecurityUtils { public static synchronized MessageDigest getMessageDigest(String algorithm) throws GeneralSecurityException { register(); - + String providerName = getSecurityProvider(); if (GenericUtils.isEmpty(providerName)) { return MessageDigest.getInstance(algorithm); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/main/java/org/apache/sshd/common/util/SelectorUtils.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/SelectorUtils.java b/sshd-core/src/main/java/org/apache/sshd/common/util/SelectorUtils.java index 2ac0976..f38a75b 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/util/SelectorUtils.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/util/SelectorUtils.java @@ -59,7 +59,7 @@ public final class SelectorUtils { /** * <p>Tests whether or not a given path matches the start of a given * pattern up to the first "**".</p> - * + * <p/> * <p>This is not a general purpose test and should only be used if you * can live with false positives. For example, <code>pattern=**\a</code> * and <code>str=b</code> will yield <code>true</code>.</p> @@ -69,7 +69,7 @@ public final class SelectorUtils { * @param str The path to match, as a String. Must not be * {@code null}. * @return whether or not a given path matches the start of a given - * pattern up to the first "**". + * pattern up to the first "**". */ public static boolean matchPatternStart(String pattern, String str) { return matchPatternStart(pattern, str, true); @@ -78,7 +78,7 @@ public final class SelectorUtils { /** * <p>Tests whether or not a given path matches the start of a given * pattern up to the first "**".</p> - * + * <p/> * <p>This is not a general purpose test and should only be used if you * can live with false positives. For example, <code>pattern=**\a</code> * and <code>str=b</code> will yield <code>true</code>.</p> @@ -90,7 +90,7 @@ public final class SelectorUtils { * @param isCaseSensitive Whether or not matching should be performed * case sensitively. * @return whether or not a given path matches the start of a given - * pattern up to the first "**". + * pattern up to the first "**". */ public static boolean matchPatternStart(String pattern, String str, boolean isCaseSensitive) { @@ -118,8 +118,7 @@ public final class SelectorUtils { // File.separator. // When pattern starts with a File.separator, str has to start with a // File.separator. - if (str.startsWith(separator) != - pattern.startsWith(separator)) { + if (str.startsWith(separator) != pattern.startsWith(separator)) { return false; } @@ -145,6 +144,7 @@ public final class SelectorUtils { strIdxStart++; } + // CHECKSTYLE:OFF if (strIdxStart > strIdxEnd) { // String is exhausted return true; @@ -156,6 +156,7 @@ public final class SelectorUtils { // this will generate false positives but we can live with that. return true; } + // CHECKSTYLE:ON } /** @@ -166,7 +167,7 @@ public final class SelectorUtils { * @param str The path to match, as a String. Must not be * {@code null}. * @return <code>true</code> if the pattern matches against the string, - * or <code>false</code> otherwise. + * or <code>false</code> otherwise. */ public static boolean matchPath(String pattern, String str) { return matchPath(pattern, str, true); @@ -182,7 +183,7 @@ public final class SelectorUtils { * @param isCaseSensitive Whether or not matching should be performed * case sensitively. * @return <code>true</code> if the pattern matches against the string, - * or <code>false</code> otherwise. + * or <code>false</code> otherwise. */ public static boolean matchPath(String pattern, String str, boolean isCaseSensitive) { @@ -208,8 +209,7 @@ public final class SelectorUtils { // File.separator. // When pattern starts with a File.separator, str has to start with a // File.separator. - if (str.startsWith(File.separator) != - pattern.startsWith(File.separator)) { + if (str.startsWith(File.separator) != pattern.startsWith(File.separator)) { return false; } @@ -297,8 +297,8 @@ public final class SelectorUtils { } // Find the pattern between padIdxStart & padIdxTmp in str between // strIdxStart & strIdxEnd - int patLength = (patIdxTmp - patIdxStart - 1); - int strLength = (strIdxEnd - strIdxStart + 1); + int patLength = patIdxTmp - patIdxStart - 1; + int strLength = strIdxEnd - strIdxStart + 1; int foundIdx = -1; strLoop: for (int i = 0; i <= strLength - patLength; i++) { @@ -346,7 +346,7 @@ public final class SelectorUtils { * @param str The string which must be matched against the pattern. * Must not be {@code null}. * @return <code>true</code> if the string matches against the pattern, - * or <code>false</code> otherwise. + * or <code>false</code> otherwise. */ public static boolean match(String pattern, String str) { return match(pattern, str, true); @@ -365,7 +365,7 @@ public final class SelectorUtils { * @param isCaseSensitive Whether or not matching should be performed * case sensitively. * @return <code>true</code> if the string matches against the pattern, - * or <code>false</code> otherwise. + * or <code>false</code> otherwise. */ public static boolean match(String pattern, String str, boolean isCaseSensitive) { @@ -404,6 +404,7 @@ public final class SelectorUtils { } // Process characters before first star + // CHECKSTYLE:OFF while ((ch = patArr[patIdxStart]) != '*' && strIdxStart <= strIdxEnd) { if (ch != '?' && !equals(ch, strArr[strIdxStart], isCaseSensitive)) { return false; // Character mismatch @@ -411,6 +412,7 @@ public final class SelectorUtils { patIdxStart++; strIdxStart++; } + // CHECKSTYLE:ON if (strIdxStart > strIdxEnd) { // All characters in the string are used. Check if only '*'s are // left in the pattern. If so, we succeeded. Otherwise failure. @@ -423,6 +425,7 @@ public final class SelectorUtils { } // Process characters after last star + // CHECKSTYLE:OFF while ((ch = patArr[patIdxEnd]) != '*' && strIdxStart <= strIdxEnd) { if (ch != '?' && !equals(ch, strArr[strIdxEnd], isCaseSensitive)) { return false; // Character mismatch @@ -430,6 +433,7 @@ public final class SelectorUtils { patIdxEnd--; strIdxEnd--; } + // CHECKSTYLE:ON if (strIdxStart > strIdxEnd) { // All characters in the string are used. Check if only '*'s are // left in the pattern. If so, we succeeded. Otherwise failure. @@ -458,8 +462,8 @@ public final class SelectorUtils { } // Find the pattern between padIdxStart & padIdxTmp in str between // strIdxStart & strIdxEnd - int patLength = (patIdxTmp - patIdxStart - 1); - int strLength = (strIdxEnd - strIdxStart + 1); + int patLength = patIdxTmp - patIdxStart - 1; + int strLength = strIdxEnd - strIdxStart + 1; int foundIdx = -1; strLoop: for (int i = 0; i <= strLength - patLength; i++) { @@ -501,8 +505,8 @@ public final class SelectorUtils { } if (!isCaseSensitive) { // NOTE: Try both upper case and lower case as done by String.equalsIgnoreCase() - if (Character.toUpperCase(c1) == Character.toUpperCase(c2) || - Character.toLowerCase(c1) == Character.toLowerCase(c2)) { + if (Character.toUpperCase(c1) == Character.toUpperCase(c2) + || Character.toLowerCase(c1) == Character.toLowerCase(c2)) { return true; } } @@ -529,11 +533,12 @@ public final class SelectorUtils { return ret; } - + /** * Normalizes the path by removing '.', '..' and double separators (e.g. '//') - * @param path Original path - ignored if {@code null}/empty - * @param separator The separator used for the path components + * + * @param path Original path - ignored if {@code null}/empty + * @param separator The separator used for the path components * @return normalized path * @throws IOException when the path is invalid (e.g. '/first/../..') */ @@ -592,6 +597,7 @@ public final class SelectorUtils { * Converts a possibly '/' separated path to a local path. <B>Note:</B> * takes special care of Windows drive paths - e.g., {@code C:} * by converting them to "C:\" + * * @param path The original path - ignored if {@code null}/empty * @return The local path */ @@ -599,9 +605,9 @@ public final class SelectorUtils { if (GenericUtils.isEmpty(path) || (File.separatorChar == '/')) { return path; } - + // This code is reached if we are running on Windows - String localPath=path.replace('/', File.separatorChar); + String localPath = path.replace('/', File.separatorChar); if ((localPath.length() < 2) || (localPath.charAt(1) != ':')) { return localPath; // assume a relative path } @@ -626,14 +632,10 @@ public final class SelectorUtils { if ((GenericUtils.length(cs) < 2) || (cs.charAt(1) != ':')) { return false; } - - char drive=cs.charAt(0); - if (((drive >= 'a') && (drive <= 'z')) - || ((drive >= 'A') && (drive <= 'Z'))) { - return true; - } else { - return false; - } + + char drive = cs.charAt(0); + return ((drive >= 'a') && (drive <= 'z')) + || ((drive >= 'A') && (drive <= 'Z')); } /** http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/main/java/org/apache/sshd/common/util/Transformer.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/Transformer.java b/sshd-core/src/main/java/org/apache/sshd/common/util/Transformer.java index 19ba9c4..73e2233 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/util/Transformer.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/util/Transformer.java @@ -26,33 +26,51 @@ import java.util.Objects; */ public interface Transformer<I, O> { // TODO in JDK-8 replace this with Function + /** - * @param input Input value - * @return Transformed output value + * Invokes {@link Objects#toString(Object)} on the argument */ - O transform(I input); + Transformer<Object, String> TOSTRING = new Transformer<Object, String>() { + @Override + public String transform(Object input) { + return Objects.toString(input); + } + }; /** - * Invokes {@link Objects#toString(Object)} on the argument + * Returns {@link Enum#name()} or {@code null} if argument is {@code null} */ - Transformer<Object,String> TOSTRING=new Transformer<Object,String>() { - @Override - public String transform(Object input) { - return Objects.toString(input); + Transformer<Enum<?>, String> ENUM_NAME_EXTRACTOR = new Transformer<Enum<?>, String>() { + @Override + public String transform(Enum<?> input) { + if (input == null) { + return null; + } else { + return input.name(); } - }; + } + }; /** - * Returns {@link Enum#name()} or {@code null} if argument is {@code null} + * @param input Input value + * @return Transformed output value */ - Transformer<Enum<?>,String> ENUM_NAME_EXTRACTOR=new Transformer<Enum<?>,String>() { - @Override - public String transform(Enum<?> input) { - if (input == null) { - return null; - } else { - return input.name(); + O transform(I input); + + final class Utils { + + private Utils() { + throw new UnsupportedOperationException("No instance allowed"); + } + + public static <U extends V, V> Transformer<U, V> identity() { + return new Transformer<U, V>() { + @Override + public V transform(U input) { + return input; } - } - }; + }; + } + + } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/main/java/org/apache/sshd/common/util/ValidateUtils.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/ValidateUtils.java b/sshd-core/src/main/java/org/apache/sshd/common/util/ValidateUtils.java index 097c986..26b154b 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/util/ValidateUtils.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/util/ValidateUtils.java @@ -40,7 +40,7 @@ public final class ValidateUtils { return t; } - public static <T> T checkNotNull(T t, String message, Object ... args) { + public static <T> T checkNotNull(T t, String message, Object... args) { checkTrue(t != null, message, args); return t; } @@ -57,31 +57,31 @@ public final class ValidateUtils { return t; } - public static String checkNotNullAndNotEmpty(String t, String message, Object ... args) { + public static String checkNotNullAndNotEmpty(String t, String message, Object... args) { t = checkNotNull(t, message, args).trim(); checkTrue(GenericUtils.length(t) > 0, message, args); return t; } - public static <K,V,M extends Map<K,V>> M checkNotNullAndNotEmpty(M t, String message, Object ... args) { + public static <K, V, M extends Map<K, V>> M checkNotNullAndNotEmpty(M t, String message, Object... args) { t = checkNotNull(t, message, args); checkTrue(GenericUtils.size(t) > 0, message, args); return t; } - public static <T,C extends Collection<T>> C checkNotNullAndNotEmpty(C t, String message, Object ... args) { + public static <T, C extends Collection<T>> C checkNotNullAndNotEmpty(C t, String message, Object... args) { t = checkNotNull(t, message, args); checkTrue(GenericUtils.size(t) > 0, message, args); return t; } - public static byte[] checkNotNullAndNotEmpty(byte[] t, String message, Object ... args) { + public static byte[] checkNotNullAndNotEmpty(byte[] t, String message, Object... args) { t = checkNotNull(t, message, args); checkTrue(GenericUtils.length(t) > 0, message, args); return t; } - public static <T> T[] checkNotNullAndNotEmpty(T[] t, String message, Object ... args) { + public static <T> T[] checkNotNullAndNotEmpty(T[] t, String message, Object... args) { t = checkNotNull(t, message, args); checkTrue(GenericUtils.length(t) > 0, message, args); return t; @@ -99,13 +99,13 @@ public final class ValidateUtils { } } - public static void checkTrue(boolean flag, String message, Object ... args) { + public static void checkTrue(boolean flag, String message, Object... args) { if (!flag) { throwIllegalArgumentException(message, args); } } - - public static void throwIllegalArgumentException(String message, Object ... args) { + + public static void throwIllegalArgumentException(String message, Object... args) { throw new IllegalArgumentException(String.format(message, args)); } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/main/java/org/apache/sshd/common/util/buffer/Buffer.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/buffer/Buffer.java b/sshd-core/src/main/java/org/apache/sshd/common/util/buffer/Buffer.java index b68a4a3..9cf4d92 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/util/buffer/Buffer.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/util/buffer/Buffer.java @@ -61,12 +61,13 @@ import org.apache.sshd.common.util.SecurityUtils; /** * Provides an abstract message buffer for encoding SSH messages + * * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> */ public abstract class Buffer implements Readable { // TODO use Long.BYTES in JDK-8 - protected final byte[] workBuf = new byte[Long.SIZE / Byte.SIZE]; + protected final byte[] workBuf = new byte[Long.SIZE / Byte.SIZE]; protected Buffer() { super(); @@ -77,6 +78,7 @@ public abstract class Buffer implements Readable { ======================*/ public abstract int rpos(); + public abstract void rpos(int rpos); public abstract int wpos(); @@ -84,6 +86,7 @@ public abstract class Buffer implements Readable { public abstract void wpos(int wpos); public abstract int capacity(); + public abstract byte[] array(); public abstract void compact(); @@ -124,9 +127,8 @@ public abstract class Buffer implements Readable { // TODO use Short.BYTES for JDK-8 ensureAvailable(Short.SIZE / Byte.SIZE); getRawBytes(workBuf, 0, Short.SIZE / Byte.SIZE); - short v = (short) (((workBuf[1] << Byte.SIZE) & 0xFF00) - | ((workBuf[0] ) & 0xF)) - ; + short v = (short) ((workBuf[1] << Byte.SIZE) & 0xFF00); + v |= workBuf[0] & 0xF; return v; } @@ -146,14 +148,14 @@ public abstract class Buffer implements Readable { ensureAvailable(Long.SIZE / Byte.SIZE); getRawBytes(workBuf, 0, Long.SIZE / Byte.SIZE); @SuppressWarnings("cast") - long l = (((long) workBuf[0] << 56) & 0xff00000000000000L)| - (((long) workBuf[1] << 48) & 0x00ff000000000000L)| - (((long) workBuf[2] << 40) & 0x0000ff0000000000L)| - (((long) workBuf[3] << 32) & 0x000000ff00000000L)| - (((long) workBuf[4] << 24) & 0x00000000ff000000L)| - (((long) workBuf[5] << 16) & 0x0000000000ff0000L)| - (((long) workBuf[6] << 8) & 0x000000000000ff00L)| - (((long) workBuf[7] ) & 0x00000000000000ffL); + long l = ((long) workBuf[0] << 56) & 0xff00000000000000L; + l |= ((long) workBuf[1] << 48) & 0x00ff000000000000L; + l |= ((long) workBuf[2] << 40) & 0x0000ff0000000000L; + l |= ((long) workBuf[3] << 32) & 0x000000ff00000000L; + l |= ((long) workBuf[4] << 24) & 0x00000000ff000000L; + l |= ((long) workBuf[5] << 16) & 0x0000000000ff0000L; + l |= ((long) workBuf[6] << 8) & 0x000000000000ff00L; + l |= ((long) workBuf[7]) & 0x00000000000000ffL; return l; } @@ -167,9 +169,9 @@ public abstract class Buffer implements Readable { /** * @param usePrependedLength If {@code true} then there is a 32-bit - * value indicating the number of strings to read. Otherwise, the - * method will use a "greedy" reading of strings while more - * data available + * value indicating the number of strings to read. Otherwise, the + * method will use a "greedy" reading of strings while more + * data available * @return A {@link Collection} of the read strings * @see #getStringList(boolean, Charset) */ @@ -179,13 +181,13 @@ public abstract class Buffer implements Readable { /** * @param usePrependedLength If {@code true} then there is a 32-bit - * value indicating the number of strings to read. Otherwise, the - * method will use a "greedy" reading of strings while more - * data available - * @param charset The {@link Charset} to use for the string + * value indicating the number of strings to read. Otherwise, the + * method will use a "greedy" reading of strings while more + * data available + * @param charset The {@link Charset} to use for the string * @return A {@link Collection} of the read strings * @see {@link #getStringList(int, Charset)} - * @see {@link #getAvailableStrings()} + * @see {@link #getAvailableStrings()} */ public Collection<String> getStringList(boolean usePrependedLength, Charset charset) { if (usePrependedLength) { @@ -212,11 +214,11 @@ public abstract class Buffer implements Readable { */ public Collection<String> getAvailableStrings(Charset charset) { Collection<String> list = new LinkedList<String>(); - while(available() > 0) { + while (available() > 0) { String s = getString(charset); list.add(s); } - + return list; } @@ -230,7 +232,7 @@ public abstract class Buffer implements Readable { } /** - * @param count The <U>exact</V> number of strings to read - can be zero + * @param count The <U>exact</V> number of strings to read - can be zero * @param charset The {@link Charset} of the strings * @return A {@link List} with the specified number of strings */ @@ -238,16 +240,16 @@ public abstract class Buffer implements Readable { if (count == 0) { return Collections.emptyList(); } - + List<String> list = new ArrayList<String>(count); for (int index = 0; index < count; index++) { String s = getString(charset); list.add(s); } - + return list; } - + public abstract String getString(Charset charset); public BigInteger getMPInt() { @@ -300,7 +302,7 @@ public abstract class Buffer implements Readable { KeyFactory keyFactory = SecurityUtils.getKeyFactory("DSA"); return keyFactory.generatePublic(new DSAPublicKeySpec(y, p, q, g)); } - + ECCurves curve = ECCurves.fromKeyType(keyAlg); if (curve == null) { throw new NoSuchAlgorithmException("Unsupported raw public algorithm: " + keyAlg); @@ -328,11 +330,11 @@ public abstract class Buffer implements Readable { ECPoint w; try { w = ECDSAPublicKeyEntryDecoder.octetStringToEcPoint(octets); - } catch(RuntimeException e) { + } catch (RuntimeException e) { throw new InvalidKeySpecException("getRawECKey(" + expectedCurve + ")" - + " cannot (" + e.getClass().getSimpleName() + ")" - + " retrieve W value: " + e.getMessage(), - e); + + " cannot (" + e.getClass().getSimpleName() + ")" + + " retrieve W value: " + e.getMessage(), + e); } KeyFactory keyFactory = SecurityUtils.getKeyFactory("EC"); @@ -366,7 +368,7 @@ public abstract class Buffer implements Readable { pub = keyFactory.generatePublic(new DSAPublicKeySpec(y, p, q, g)); prv = keyFactory.generatePrivate(new DSAPrivateKeySpec(x, p, q, g)); } else { - ECCurves curve = ECCurves.fromKeyType(keyAlg); + ECCurves curve = ECCurves.fromKeyType(keyAlg); if (curve == null) { throw new NoSuchAlgorithmException("Unsupported key pair algorithm: " + keyAlg); } @@ -397,11 +399,11 @@ public abstract class Buffer implements Readable { ECPoint group; try { group = ECDSAPublicKeyEntryDecoder.octetStringToEcPoint(groupBytes); - } catch(RuntimeException e) { + } catch (RuntimeException e) { throw new InvalidKeySpecException("extractEC(" + expectedCurveName + ")" - + " failed (" + e.getClass().getSimpleName() + ")" - + " to decode EC group for curve: " + e.getMessage(), - e); + + " failed (" + e.getClass().getSimpleName() + ")" + + " to decode EC group for curve: " + e.getMessage(), + e); } KeyFactory keyFactory = SecurityUtils.getKeyFactory("EC"); @@ -435,18 +437,20 @@ public abstract class Buffer implements Readable { /** * Writes 16 bits + * * @param i */ public void putShort(int i) { // TODO use Short.BYTES for JDK-8 ensureCapacity(Short.SIZE / Byte.SIZE); - workBuf[0] = (byte) (i >> 8); - workBuf[1] = (byte) (i ); + workBuf[0] = (byte) (i >> 8); + workBuf[1] = (byte) i; putRawBytes(workBuf, 0, Short.SIZE / Byte.SIZE); } /** * Writes 32 bits + * * @param i The 32-bit value */ public void putInt(long i) { @@ -458,6 +462,7 @@ public abstract class Buffer implements Readable { /** * Writes 64 bits + * * @param i */ public void putLong(long i) { @@ -469,8 +474,8 @@ public abstract class Buffer implements Readable { workBuf[3] = (byte) (i >> 32); workBuf[4] = (byte) (i >> 24); workBuf[5] = (byte) (i >> 16); - workBuf[6] = (byte) (i >> 8); - workBuf[7] = (byte) (i ); + workBuf[6] = (byte) (i >> 8); + workBuf[7] = (byte) i; putRawBytes(workBuf, 0, Long.SIZE / Byte.SIZE); } @@ -489,10 +494,11 @@ public abstract class Buffer implements Readable { /** * Encodes the {@link Objects#toString(Object)} value of each member. - * @param objects The objects to be encoded in the buffer - OK if - * {@code null}/empty + * + * @param objects The objects to be encoded in the buffer - OK if + * {@code null}/empty * @param prependLength If {@code true} then the list is preceded by - * a 32-bit count of the number of members in the list + * a 32-bit count of the number of members in the list * @see #putStringList(Collection, Charset, boolean) */ public void putStringList(Collection<?> objects, boolean prependLength) { @@ -501,11 +507,12 @@ public abstract class Buffer implements Readable { /** * Encodes the {@link Objects#toString(Object)} value of each member - * @param objects The objects to be encoded in the buffer - OK if - * {@code null}/empty - * @param charset The {@link Charset} to use for encoding + * + * @param objects The objects to be encoded in the buffer - OK if + * {@code null}/empty + * @param charset The {@link Charset} to use for encoding * @param prependLength If {@code true} then the list is preceded by - * a 32-bit count of the number of members in the list + * a 32-bit count of the number of members in the list * @see #putString(String, Charset) */ public void putStringList(Collection<?> objects, Charset charset, boolean prependLength) { @@ -517,7 +524,7 @@ public abstract class Buffer implements Readable { if (numObjects <= 0) { return; } - + for (Object o : objects) { putString(Objects.toString(o), charset); } @@ -538,7 +545,7 @@ public abstract class Buffer implements Readable { public void putMPInt(byte[] foo) { if ((foo[0] & 0x80) != 0) { putInt(foo.length + 1 /* padding */); - putByte((byte)0); + putByte((byte) 0); } else { putInt(foo.length); } @@ -570,8 +577,8 @@ public abstract class Buffer implements Readable { putMPInt(rsaPub.getPublicExponent()); putMPInt(rsaPub.getModulus()); } else if (key instanceof DSAPublicKey) { - DSAPublicKey dsaPub = (DSAPublicKey) key; - DSAParams dsaParams = dsaPub.getParams(); + DSAPublicKey dsaPub = (DSAPublicKey) key; + DSAParams dsaParams = dsaPub.getParams(); putString(KeyPairProvider.SSH_DSS); putMPInt(dsaParams.getP()); @@ -595,11 +602,11 @@ public abstract class Buffer implements Readable { } public void putKeyPair(KeyPair kp) { - PublicKey pubKey = kp.getPublic(); - PrivateKey prvKey = kp.getPrivate(); + PublicKey pubKey = kp.getPublic(); + PrivateKey prvKey = kp.getPrivate(); if (prvKey instanceof RSAPrivateCrtKey) { - RSAPublicKey rsaPub = (RSAPublicKey) pubKey; - RSAPrivateCrtKey rsaPrv = (RSAPrivateCrtKey) prvKey; + RSAPublicKey rsaPub = (RSAPublicKey) pubKey; + RSAPrivateCrtKey rsaPrv = (RSAPrivateCrtKey) prvKey; putString(KeyPairProvider.SSH_RSA); putMPInt(rsaPub.getPublicExponent()); @@ -609,9 +616,9 @@ public abstract class Buffer implements Readable { putMPInt(rsaPrv.getPrimeQ()); putMPInt(rsaPrv.getPrimeP()); } else if (pubKey instanceof DSAPublicKey) { - DSAPublicKey dsaPub = (DSAPublicKey) pubKey; - DSAParams dsaParams = dsaPub.getParams(); - DSAPrivateKey dsaPrv = (DSAPrivateKey) prvKey; + DSAPublicKey dsaPub = (DSAPublicKey) pubKey; + DSAParams dsaParams = dsaPub.getParams(); + DSAPrivateKey dsaPrv = (DSAPrivateKey) prvKey; putString(KeyPairProvider.SSH_DSS); putMPInt(dsaParams.getP()); @@ -625,7 +632,7 @@ public abstract class Buffer implements Readable { ECParameterSpec ecParams = ecPub.getParams(); ECCurves curve = ECCurves.fromCurveParameters(ecParams); if (curve == null) { - throw new BufferException("Unsupported EC curve parameters"); + throw new BufferException("Unsupported EC curve parameters"); } putString(curve.getKeyType()); @@ -642,14 +649,15 @@ public abstract class Buffer implements Readable { } /** - * @param capacity The requires capacity + * @param capacity The requires capacity * @param growthFactor An {@link Int2IntFunction} that is invoked - * if the current capacity is insufficient. The argument is the minimum - * required new data length, the function result should be the - * effective new data length to be allocated - if less than minimum - * then an exception is thrown + * if the current capacity is insufficient. The argument is the minimum + * required new data length, the function result should be the + * effective new data length to be allocated - if less than minimum + * then an exception is thrown */ public abstract void ensureCapacity(int capacity, Int2IntFunction growthFactor); + protected abstract int size(); @Override
