You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mina.apache.org by gn...@apache.org on 2016/09/15 19:34:50 UTC
[13/16] mina-sshd git commit: [SSHD-698] Use lambda and method
references,
streams Deprecate Utils inner classes and use interface methods instead.
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/AbstractResourceKeyPairProvider.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/AbstractResourceKeyPairProvider.java b/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/AbstractResourceKeyPairProvider.java
index f028a3b..d007c07 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/AbstractResourceKeyPairProvider.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/AbstractResourceKeyPairProvider.java
@@ -100,9 +100,7 @@ public abstract class AbstractResourceKeyPairProvider<R> extends AbstractKeyPair
}
if (GenericUtils.size(toDelete) > 0) {
- for (String f : toDelete) {
- cacheMap.remove(f);
- }
+ toDelete.forEach(cacheMap::remove);
}
}
@@ -115,12 +113,7 @@ public abstract class AbstractResourceKeyPairProvider<R> extends AbstractKeyPair
if (GenericUtils.isEmpty(resources)) {
return Collections.emptyList();
} else {
- return new Iterable<KeyPair>() {
- @Override
- public Iterator<KeyPair> iterator() {
- return new KeyPairIterator(resources);
- }
- };
+ return () -> new KeyPairIterator(resources);
}
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/KeyIdentityProvider.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/KeyIdentityProvider.java b/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/KeyIdentityProvider.java
index cb1e08a..b696acf 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/KeyIdentityProvider.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/KeyIdentityProvider.java
@@ -20,12 +20,9 @@
package org.apache.sshd.common.keyprovider;
import java.security.KeyPair;
-import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
-import java.util.function.Supplier;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.util.GenericUtils;
@@ -53,6 +50,13 @@ public interface KeyIdentityProvider {
};
/**
+ * Invokes {@link KeyIdentityProvider#loadKeys()} and returns the result - ignores
+ * {@code null} providers (i.e., returns an empty iterable instance)
+ */
+ Transformer<KeyIdentityProvider, Iterable<KeyPair>> LOADER = p ->
+ (p == null) ? Collections.<KeyPair>emptyList() : p.loadKeys();
+
+ /**
* Load available keys.
*
* @return an {@link Iterable} instance of available keys - ignored if {@code null}
@@ -64,167 +68,169 @@ public interface KeyIdentityProvider {
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
// CHECKSTYLE:OFF
+ @Deprecated
final class Utils {
// CHECKSTYLE:ON
- /**
- * Invokes {@link KeyIdentityProvider#loadKeys()} and returns the result - ignores
- * {@code null} providers (i.e., returns an empty iterable instance)
- */
+
public static final Transformer<KeyIdentityProvider, Iterable<KeyPair>> LOADER =
- new Transformer<KeyIdentityProvider, Iterable<KeyPair>>() {
- @Override
- public Iterable<KeyPair> transform(KeyIdentityProvider p) {
- return (p == null) ? Collections.emptyList() : p.loadKeys();
- }
- };
+ KeyIdentityProvider.LOADER;
private Utils() {
throw new UnsupportedOperationException("No instance allowed");
}
- /**
- * Creates a "unified" {@link Iterator} of key pairs out of the registered
- * {@link KeyPair} identities and the extra available ones as a single iterator
- * of key pairs
- *
- * @param session The {@link ClientSession} - ignored if {@code null} (i.e., empty
- * iterator returned)
- * @return The wrapping iterator
- * @see ClientSession#getRegisteredIdentities()
- * @see ClientSession#getKeyPairProvider()
- */
public static Iterator<KeyPair> iteratorOf(ClientSession session) {
- return (session == null) ? Collections.emptyIterator() : iteratorOf(session.getRegisteredIdentities(), session.getKeyPairProvider());
+ return KeyIdentityProvider.iteratorOf(session);
}
- /**
- * Creates a "unified" {@link Iterator} of {@link KeyPair}s out of 2 possible
- * {@link KeyIdentityProvider}
- *
- * @param identities The registered keys identities
- * @param keys Extra available key pairs
- * @return The wrapping iterator
- * @see #resolveKeyIdentityProvider(KeyIdentityProvider, KeyIdentityProvider)
- */
public static Iterator<KeyPair> iteratorOf(KeyIdentityProvider identities, KeyIdentityProvider keys) {
- return iteratorOf(resolveKeyIdentityProvider(identities, keys));
+ return KeyIdentityProvider.iteratorOf(identities, keys);
}
- /**
- * Resolves a non-{@code null} iterator of the available keys
- *
- * @param provider The {@link KeyIdentityProvider} - ignored if {@code null}
- * @return A non-{@code null} iterator - which may be empty if no provider or no keys
- */
public static Iterator<KeyPair> iteratorOf(KeyIdentityProvider provider) {
- return GenericUtils.iteratorOf((provider == null) ? null : provider.loadKeys());
+ return KeyIdentityProvider.iteratorOf(provider);
}
- /**
- * <P>Creates a "unified" {@link KeyIdentityProvider} out of 2 possible ones
- * as follows:</P></BR>
- * <UL>
- * <LI>If both are {@code null} then return {@code null}.</LI>
- * <LI>If either one is {@code null} then use the non-{@code null} one.</LI>
- * <LI>If both are the same instance then use it.</U>
- * <LI>Otherwise, returns a wrapper that groups both providers.</LI>
- * </UL>
- * @param identities The registered key pair identities
- * @param keys The extra available key pairs
- * @return The resolved provider
- * @see #multiProvider(KeyIdentityProvider...)
- */
public static KeyIdentityProvider resolveKeyIdentityProvider(KeyIdentityProvider identities, KeyIdentityProvider keys) {
- if ((keys == null) || (identities == keys)) {
- return identities;
- } else if (identities == null) {
- return keys;
- } else {
- return multiProvider(identities, keys);
- }
+ return KeyIdentityProvider.resolveKeyIdentityProvider(identities, keys);
}
- /**
- * Wraps a group of {@link KeyIdentityProvider} into a single one
- *
- * @param providers The providers - ignored if {@code null}/empty (i.e., returns
- * {@link #EMPTY_KEYS_PROVIDER})
- * @return The wrapping provider
- * @see #multiProvider(Collection)
- */
public static KeyIdentityProvider multiProvider(KeyIdentityProvider ... providers) {
- return GenericUtils.isEmpty(providers) ? EMPTY_KEYS_PROVIDER : multiProvider(Arrays.asList(providers));
+ return KeyIdentityProvider.multiProvider(providers);
}
- /**
- * Wraps a group of {@link KeyIdentityProvider} into a single one
- *
- * @param providers The providers - ignored if {@code null}/empty (i.e., returns
- * {@link #EMPTY_KEYS_PROVIDER})
- * @return The wrapping provider
- */
public static KeyIdentityProvider multiProvider(Collection<? extends KeyIdentityProvider> providers) {
- return GenericUtils.isEmpty(providers) ? EMPTY_KEYS_PROVIDER : wrap(iterableOf(providers));
+ return KeyIdentityProvider.multiProvider(providers);
}
- /**
- * Wraps a group of {@link KeyIdentityProvider} into an {@link Iterable} of {@link KeyPair}s
- *
- * @param providers The group of providers - ignored if {@code null}/empty (i.e., returns an
- * empty iterable instance)
- * @return The wrapping iterable
- */
public static Iterable<KeyPair> iterableOf(Collection<? extends KeyIdentityProvider> providers) {
- if (GenericUtils.isEmpty(providers)) {
- return Collections.emptyList();
- }
-
- Collection<Supplier<Iterable<KeyPair>>> suppliers = new ArrayList<>(providers.size());
- for (final KeyIdentityProvider p : providers) {
- if (p == null) {
- continue;
- }
-
- suppliers.add(new Supplier<Iterable<KeyPair>>() {
- @Override
- public Iterable<KeyPair> get() {
- return p.loadKeys();
- }
- });
- }
-
- if (GenericUtils.isEmpty(suppliers)) {
- return Collections.emptyList();
- }
-
- return GenericUtils.multiIterableSuppliers(suppliers);
+ return KeyIdentityProvider.iterableOf(providers);
}
- /**
- * Wraps a group of {@link KeyPair}s into a {@link KeyIdentityProvider}
- *
- * @param pairs The key pairs - ignored if {@code null}/empty (i.e., returns
- * {@link #EMPTY_KEYS_PROVIDER}).
- * @return The provider wrapper
- */
public static KeyIdentityProvider wrap(KeyPair ... pairs) {
- return GenericUtils.isEmpty(pairs) ? EMPTY_KEYS_PROVIDER : wrap(Arrays.asList(pairs));
+ return KeyIdentityProvider.wrap(pairs);
}
- /**
- * Wraps a group of {@link KeyPair}s into a {@link KeyIdentityProvider}
- *
- * @param pairs The key pairs {@link Iterable} - ignored if {@code null} (i.e., returns
- * {@link #EMPTY_KEYS_PROVIDER}).
- * @return The provider wrapper
- */
public static KeyIdentityProvider wrap(final Iterable<KeyPair> pairs) {
- return (pairs == null) ? EMPTY_KEYS_PROVIDER : new KeyIdentityProvider() {
- @Override
- public Iterable<KeyPair> loadKeys() {
- return pairs;
- }
- };
+ return KeyIdentityProvider.wrap(pairs);
}
}
+
+ /**
+ * Creates a "unified" {@link Iterator} of key pairs out of the registered
+ * {@link KeyPair} identities and the extra available ones as a single iterator
+ * of key pairs
+ *
+ * @param session The {@link ClientSession} - ignored if {@code null} (i.e., empty
+ * iterator returned)
+ * @return The wrapping iterator
+ * @see ClientSession#getRegisteredIdentities()
+ * @see ClientSession#getKeyPairProvider()
+ */
+ static Iterator<KeyPair> iteratorOf(ClientSession session) {
+ return (session == null) ? Collections.<KeyPair>emptyIterator() : iteratorOf(session.getRegisteredIdentities(), session.getKeyPairProvider());
+ }
+
+ /**
+ * Creates a "unified" {@link Iterator} of {@link KeyPair}s out of 2 possible
+ * {@link KeyIdentityProvider}
+ *
+ * @param identities The registered keys identities
+ * @param keys Extra available key pairs
+ * @return The wrapping iterator
+ * @see #resolveKeyIdentityProvider(KeyIdentityProvider, KeyIdentityProvider)
+ */
+ static Iterator<KeyPair> iteratorOf(KeyIdentityProvider identities, KeyIdentityProvider keys) {
+ return iteratorOf(resolveKeyIdentityProvider(identities, keys));
+ }
+
+ /**
+ * Resolves a non-{@code null} iterator of the available keys
+ *
+ * @param provider The {@link KeyIdentityProvider} - ignored if {@code null}
+ * @return A non-{@code null} iterator - which may be empty if no provider or no keys
+ */
+ static Iterator<KeyPair> iteratorOf(KeyIdentityProvider provider) {
+ return GenericUtils.iteratorOf((provider == null) ? null : provider.loadKeys());
+ }
+
+ /**
+ * <P>Creates a "unified" {@link KeyIdentityProvider} out of 2 possible ones
+ * as follows:</P></BR>
+ * <UL>
+ * <LI>If both are {@code null} then return {@code null}.</LI>
+ * <LI>If either one is {@code null} then use the non-{@code null} one.</LI>
+ * <LI>If both are the same instance then use it.</U>
+ * <LI>Otherwise, returns a wrapper that groups both providers.</LI>
+ * </UL>
+ * @param identities The registered key pair identities
+ * @param keys The extra available key pairs
+ * @return The resolved provider
+ * @see #multiProvider(KeyIdentityProvider...)
+ */
+ static KeyIdentityProvider resolveKeyIdentityProvider(KeyIdentityProvider identities, KeyIdentityProvider keys) {
+ if ((keys == null) || (identities == keys)) {
+ return identities;
+ } else if (identities == null) {
+ return keys;
+ } else {
+ return multiProvider(identities, keys);
+ }
+ }
+
+ /**
+ * Wraps a group of {@link KeyIdentityProvider} into a single one
+ *
+ * @param providers The providers - ignored if {@code null}/empty (i.e., returns
+ * {@link #EMPTY_KEYS_PROVIDER})
+ * @return The wrapping provider
+ * @see #multiProvider(Collection)
+ */
+ static KeyIdentityProvider multiProvider(KeyIdentityProvider ... providers) {
+ return multiProvider(GenericUtils.asList(providers));
+ }
+
+ /**
+ * Wraps a group of {@link KeyIdentityProvider} into a single one
+ *
+ * @param providers The providers - ignored if {@code null}/empty (i.e., returns
+ * {@link #EMPTY_KEYS_PROVIDER})
+ * @return The wrapping provider
+ */
+ static KeyIdentityProvider multiProvider(Collection<? extends KeyIdentityProvider> providers) {
+ return GenericUtils.isEmpty(providers) ? EMPTY_KEYS_PROVIDER : wrap(iterableOf(providers));
+ }
+
+ /**
+ * Wraps a group of {@link KeyIdentityProvider} into an {@link Iterable} of {@link KeyPair}s
+ *
+ * @param providers The group of providers - ignored if {@code null}/empty (i.e., returns an
+ * empty iterable instance)
+ * @return The wrapping iterable
+ */
+ static Iterable<KeyPair> iterableOf(Collection<? extends KeyIdentityProvider> providers) {
+ return GenericUtils.multiIterableSuppliers(GenericUtils.wrapIterable(providers, p -> p::loadKeys));
+ }
+
+ /**
+ * Wraps a group of {@link KeyPair}s into a {@link KeyIdentityProvider}
+ *
+ * @param pairs The key pairs - ignored if {@code null}/empty (i.e., returns
+ * {@link #EMPTY_KEYS_PROVIDER}).
+ * @return The provider wrapper
+ */
+ static KeyIdentityProvider wrap(KeyPair ... pairs) {
+ return wrap(GenericUtils.asList(pairs));
+ }
+
+ /**
+ * Wraps a group of {@link KeyPair}s into a {@link KeyIdentityProvider}
+ *
+ * @param pairs The key pairs {@link Iterable} - ignored if {@code null} (i.e., returns
+ * {@link #EMPTY_KEYS_PROVIDER}).
+ * @return The provider wrapper
+ */
+ static KeyIdentityProvider wrap(final Iterable<KeyPair> pairs) {
+ return (pairs == null) ? EMPTY_KEYS_PROVIDER : () -> pairs;
+ }
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/KeyPairProvider.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/KeyPairProvider.java b/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/KeyPairProvider.java
index 1a59a8b..84d52ca 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/KeyPairProvider.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/KeyPairProvider.java
@@ -24,10 +24,12 @@ import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Objects;
+import java.util.stream.Collectors;
import org.apache.sshd.common.cipher.ECCurves;
import org.apache.sshd.common.config.keys.KeyUtils;
import org.apache.sshd.common.util.GenericUtils;
+import org.apache.sshd.common.util.ValidateUtils;
/**
* Provider for key pairs. This provider is used on the server side to provide
@@ -101,80 +103,100 @@ public interface KeyPairProvider extends KeyIdentityProvider {
* @param type the type of key to load
* @return a valid key pair or {@code null} if this type of key is not available
*/
- KeyPair loadKey(String type);
+ default KeyPair loadKey(String type) {
+ ValidateUtils.checkNotNullAndNotEmpty(type, "No key type to load");
+ return GenericUtils.stream(loadKeys())
+ .filter(key -> type.equals(KeyUtils.getKeyType(key)))
+ .findFirst()
+ .orElse(null);
+ }
/**
* @return The available {@link Iterable} key types in preferred order - never {@code null}
*/
- Iterable<String> getKeyTypes();
+ default Iterable<String> getKeyTypes() {
+ return GenericUtils.stream(loadKeys())
+ .map(KeyUtils::getKeyType)
+ .filter(GenericUtils::isNotEmpty)
+ .collect(Collectors.toSet());
+ }
/**
* A helper class for key-pair providers
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
// CHECKSTYLE:OFF
+ @Deprecated
final class Utils {
// CHECKSTYLE:ON
private Utils() {
throw new UnsupportedOperationException("No instance allowed");
}
- /**
- * Wrap the provided {@link KeyPair}s into a {@link KeyPairProvider}
- *
- * @param pairs The available pairs - ignored if {@code null}/empty (i.e.,
- * returns {@link #EMPTY_KEYPAIR_PROVIDER})
- * @return The provider wrapper
- * @see #wrap(Iterable)
- */
public static KeyPairProvider wrap(KeyPair ... pairs) {
- return GenericUtils.isEmpty(pairs) ? EMPTY_KEYPAIR_PROVIDER : wrap(Arrays.asList(pairs));
+ return KeyPairProvider.wrap(pairs);
}
- /**
- * Wrap the provided {@link KeyPair}s into a {@link KeyPairProvider}
- *
- * @param pairs The available pairs {@link Iterable} - ignored if {@code null} (i.e.,
- * returns {@link #EMPTY_KEYPAIR_PROVIDER})
- * @return The provider wrapper
- */
public static KeyPairProvider wrap(final Iterable<KeyPair> pairs) {
- return (pairs == null) ? EMPTY_KEYPAIR_PROVIDER : new KeyPairProvider() {
- @Override
- public Iterable<KeyPair> loadKeys() {
- return pairs;
- }
+ return KeyPairProvider.wrap(pairs);
+ }
+ }
- @Override
- public KeyPair loadKey(String type) {
- for (KeyPair kp : pairs) {
- String t = KeyUtils.getKeyType(kp);
- if (Objects.equals(type, t)) {
- return kp;
- }
- }
+ /**
+ * Wrap the provided {@link KeyPair}s into a {@link KeyPairProvider}
+ *
+ * @param pairs The available pairs - ignored if {@code null}/empty (i.e.,
+ * returns {@link #EMPTY_KEYPAIR_PROVIDER})
+ * @return The provider wrapper
+ * @see #wrap(Iterable)
+ */
+ static KeyPairProvider wrap(KeyPair ... pairs) {
+ return GenericUtils.isEmpty(pairs) ? EMPTY_KEYPAIR_PROVIDER : wrap(Arrays.asList(pairs));
+ }
+
+ /**
+ * Wrap the provided {@link KeyPair}s into a {@link KeyPairProvider}
+ *
+ * @param pairs The available pairs {@link Iterable} - ignored if {@code null} (i.e.,
+ * returns {@link #EMPTY_KEYPAIR_PROVIDER})
+ * @return The provider wrapper
+ */
+ static KeyPairProvider wrap(final Iterable<KeyPair> pairs) {
+ return (pairs == null) ? EMPTY_KEYPAIR_PROVIDER : new KeyPairProvider() {
+ @Override
+ public Iterable<KeyPair> loadKeys() {
+ return pairs;
+ }
- return null;
+ @Override
+ public KeyPair loadKey(String type) {
+ for (KeyPair kp : pairs) {
+ String t = KeyUtils.getKeyType(kp);
+ if (Objects.equals(type, t)) {
+ return kp;
+ }
}
- @Override
- public Iterable<String> getKeyTypes() {
- // use a LinkedHashSet so as to preserve the order but avoid duplicates
- Collection<String> types = new LinkedHashSet<>();
- for (KeyPair kp : pairs) {
- String t = KeyUtils.getKeyType(kp);
- if (GenericUtils.isEmpty(t)) {
- continue; // avoid unknown key types
- }
-
- if (!types.add(t)) {
- continue; // debug breakpoint
- }
+ return null;
+ }
+
+ @Override
+ public Iterable<String> getKeyTypes() {
+ // use a LinkedHashSet so as to preserve the order but avoid duplicates
+ Collection<String> types = new LinkedHashSet<>();
+ for (KeyPair kp : pairs) {
+ String t = KeyUtils.getKeyType(kp);
+ if (GenericUtils.isEmpty(t)) {
+ continue; // avoid unknown key types
}
- return types;
+ if (!types.add(t)) {
+ continue; // debug breakpoint
+ }
}
- };
- }
+
+ return types;
+ }
+ };
}
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/MappedKeyPairProvider.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/MappedKeyPairProvider.java b/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/MappedKeyPairProvider.java
index 60a2750..42a7102 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/MappedKeyPairProvider.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/MappedKeyPairProvider.java
@@ -44,12 +44,7 @@ public class MappedKeyPairProvider implements KeyPairProvider {
* associated {@link KeyPair}
*/
public static final Transformer<Map<String, KeyPair>, KeyPairProvider> MAP_TO_KEY_PAIR_PROVIDER =
- new Transformer<Map<String, KeyPair>, KeyPairProvider>() {
- @Override
- public KeyPairProvider transform(final Map<String, KeyPair> input) {
- return new MappedKeyPairProvider(input);
- }
- };
+ MappedKeyPairProvider::new;
private final Map<String, KeyPair> pairsMap;
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/mac/BuiltinMacs.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/mac/BuiltinMacs.java b/sshd-core/src/main/java/org/apache/sshd/common/mac/BuiltinMacs.java
index 3ad7c27..30b383e 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/mac/BuiltinMacs.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/mac/BuiltinMacs.java
@@ -186,7 +186,7 @@ public enum BuiltinMacs implements MacFactory {
* (case <U>insensitive</U>) the provided name - {@code null} if no match
*/
public static BuiltinMacs fromFactoryName(String name) {
- return NamedResource.Utils.findByName(name, String.CASE_INSENSITIVE_ORDER, VALUES);
+ return NamedResource.findByName(name, String.CASE_INSENSITIVE_ORDER, VALUES);
}
/**
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/scp/ScpHelper.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/scp/ScpHelper.java b/sshd-core/src/main/java/org/apache/sshd/common/scp/ScpHelper.java
index 8c0c17f..ad2867f 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/scp/ScpHelper.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/scp/ScpHelper.java
@@ -121,46 +121,43 @@ public class ScpHelper extends AbstractLoggingBean implements SessionHolder<Sess
}
public void receiveFileStream(final OutputStream local, final int bufferSize) throws IOException {
- receive(new ScpReceiveLineHandler() {
- @Override
- public void process(final String line, boolean isDir, ScpTimestamp timestamp) throws IOException {
- if (isDir) {
- throw new StreamCorruptedException("Cannot download a directory into a file stream: " + line);
- }
+ receive((line, isDir, timestamp) -> {
+ if (isDir) {
+ throw new StreamCorruptedException("Cannot download a directory into a file stream: " + line);
+ }
- final Path path = new MockPath(line);
- receiveStream(line, new ScpTargetStreamResolver() {
- @SuppressWarnings("synthetic-access")
- @Override
- public OutputStream resolveTargetStream(Session session, String name, long length,
- Set<PosixFilePermission> perms, OpenOption... options) throws IOException {
- if (log.isDebugEnabled()) {
- log.debug("resolveTargetStream({}) name={}, perms={}, len={} - started local stream download",
- ScpHelper.this, name, perms, length);
- }
- return local;
+ final Path path = new MockPath(line);
+ receiveStream(line, new ScpTargetStreamResolver() {
+ @SuppressWarnings("synthetic-access")
+ @Override
+ public OutputStream resolveTargetStream(Session session, String name, long length,
+ Set<PosixFilePermission> perms, OpenOption... options) throws IOException {
+ if (log.isDebugEnabled()) {
+ log.debug("resolveTargetStream({}) name={}, perms={}, len={} - started local stream download",
+ ScpHelper.this, name, perms, length);
}
+ return local;
+ }
- @Override
- public Path getEventListenerFilePath() {
- return path;
- }
+ @Override
+ public Path getEventListenerFilePath() {
+ return path;
+ }
- @Override
- @SuppressWarnings("synthetic-access")
- public void postProcessReceivedData(String name, boolean preserve, Set<PosixFilePermission> perms, ScpTimestamp time) throws IOException {
- if (log.isDebugEnabled()) {
- log.debug("postProcessReceivedData({}) name={}, perms={}, preserve={} time={}",
- ScpHelper.this, name, perms, preserve, time);
- }
+ @Override
+ @SuppressWarnings("synthetic-access")
+ public void postProcessReceivedData(String name, boolean preserve, Set<PosixFilePermission> perms, ScpTimestamp time) throws IOException {
+ if (log.isDebugEnabled()) {
+ log.debug("postProcessReceivedData({}) name={}, perms={}, preserve={} time={}",
+ ScpHelper.this, name, perms, preserve, time);
}
+ }
- @Override
- public String toString() {
- return line;
- }
- }, timestamp, false, bufferSize);
- }
+ @Override
+ public String toString() {
+ return line;
+ }
+ }, timestamp, false, bufferSize);
});
}
@@ -180,14 +177,11 @@ public class ScpHelper extends AbstractLoggingBean implements SessionHolder<Sess
}
}
- receive(new ScpReceiveLineHandler() {
- @Override
- public void process(String line, boolean isDir, ScpTimestamp time) throws IOException {
- if (recursive && isDir) {
- receiveDir(line, path, time, preserve, bufferSize);
- } else {
- receiveFile(line, path, time, preserve, bufferSize);
- }
+ receive((line, isDir, time) -> {
+ if (recursive && isDir) {
+ receiveDir(line, path, time, preserve, bufferSize);
+ } else {
+ receiveFile(line, path, time, preserve, bufferSize);
}
});
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/session/ConnectionServiceRequestHandler.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/ConnectionServiceRequestHandler.java b/sshd-core/src/main/java/org/apache/sshd/common/session/ConnectionServiceRequestHandler.java
index 3cf8481..a20181c 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/ConnectionServiceRequestHandler.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/ConnectionServiceRequestHandler.java
@@ -29,7 +29,7 @@ import org.apache.sshd.common.util.buffer.Buffer;
public interface ConnectionServiceRequestHandler extends RequestHandler<ConnectionService> {
// required because of generics issues
- Transformer<ConnectionServiceRequestHandler, RequestHandler<ConnectionService>> SVC2HNDLR = Transformer.Utils.identity();
+ Transformer<ConnectionServiceRequestHandler, RequestHandler<ConnectionService>> SVC2HNDLR = Transformer.identity();
@Override
Result process(ConnectionService service, String request, boolean wantReply, Buffer buffer) throws Exception;
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractConnectionService.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractConnectionService.java b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractConnectionService.java
index 0eab031..6878a84 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractConnectionService.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractConnectionService.java
@@ -31,7 +31,6 @@ import java.util.concurrent.atomic.AtomicReference;
import org.apache.sshd.agent.common.AgentForwardSupport;
import org.apache.sshd.agent.common.DefaultAgentForwardSupport;
import org.apache.sshd.client.channel.AbstractClientChannel;
-import org.apache.sshd.client.future.OpenFuture;
import org.apache.sshd.common.Closeable;
import org.apache.sshd.common.FactoryManager;
import org.apache.sshd.common.NamedFactory;
@@ -46,7 +45,6 @@ import org.apache.sshd.common.channel.Window;
import org.apache.sshd.common.forward.PortForwardingEventListener;
import org.apache.sshd.common.forward.TcpipForwarder;
import org.apache.sshd.common.forward.TcpipForwarderFactory;
-import org.apache.sshd.common.future.SshFutureListener;
import org.apache.sshd.common.io.AbstractIoWriteFuture;
import org.apache.sshd.common.io.IoWriteFuture;
import org.apache.sshd.common.session.ConnectionService;
@@ -84,7 +82,7 @@ public abstract class AbstractConnectionService<S extends AbstractSession>
/**
* Default growth factor function used to resize response buffers
*/
- public static final Int2IntFunction RESPONSE_BUFFER_GROWTH_FACTOR = Int2IntFunction.Utils.add(Byte.SIZE);
+ public static final Int2IntFunction RESPONSE_BUFFER_GROWTH_FACTOR = Int2IntFunction.add(Byte.SIZE);
/**
* Map of channels keyed by the identifier
@@ -540,7 +538,7 @@ public abstract class AbstractConnectionService<S extends AbstractSession>
final Session session = getSession();
FactoryManager manager = ValidateUtils.checkNotNull(session.getFactoryManager(), "No factory manager");
- final Channel channel = NamedFactory.Utils.create(manager.getChannelFactories(), type);
+ final Channel channel = NamedFactory.create(manager.getChannelFactories(), type);
if (channel == null) {
// TODO add language tag
sendChannelOpenFailure(buffer, sender, SshConstants.SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "Unsupported channel type: " + type, "");
@@ -548,45 +546,41 @@ public abstract class AbstractConnectionService<S extends AbstractSession>
}
final int channelId = registerChannel(channel);
- channel.open(sender, rwsize, rmpsize, buffer).addListener(new SshFutureListener<OpenFuture>() {
- @Override
- @SuppressWarnings("synthetic-access")
- public void operationComplete(OpenFuture future) {
- try {
- if (future.isOpened()) {
- Window window = channel.getLocalWindow();
- if (log.isDebugEnabled()) {
- log.debug("operationComplete({}) send SSH_MSG_CHANNEL_OPEN_CONFIRMATION recipient={}, sender={}, window-size={}, packet-size={}",
- channel, sender, channelId, window.getSize(), window.getPacketSize());
- }
- Buffer buf = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_OPEN_CONFIRMATION, Integer.SIZE);
- buf.putInt(sender); // remote (server side) identifier
- buf.putInt(channelId); // local (client side) identifier
- buf.putInt(window.getSize());
- buf.putInt(window.getPacketSize());
- session.writePacket(buf);
- } else {
- Throwable exception = future.getException();
- if (exception != null) {
- String message = exception.getMessage();
- int reasonCode = 0;
- if (exception instanceof OpenChannelException) {
- reasonCode = ((OpenChannelException) exception).getReasonCode();
- } else {
- message = exception.getClass().getSimpleName() + " while opening channel: " + message;
- }
-
- Buffer buf = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_OPEN_FAILURE, message.length() + Long.SIZE);
- sendChannelOpenFailure(buf, sender, reasonCode, message, "");
- }
- }
- } catch (IOException e) {
+ channel.open(sender, rwsize, rmpsize, buffer).addListener(future -> {
+ try {
+ if (future.isOpened()) {
+ Window window = channel.getLocalWindow();
if (log.isDebugEnabled()) {
- log.debug("operationComplete({}) {}: {}",
- AbstractConnectionService.this, e.getClass().getSimpleName(), e.getMessage());
+ log.debug("operationComplete({}) send SSH_MSG_CHANNEL_OPEN_CONFIRMATION recipient={}, sender={}, window-size={}, packet-size={}",
+ channel, sender, channelId, window.getSize(), window.getPacketSize());
}
- session.exceptionCaught(e);
+ Buffer buf = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_OPEN_CONFIRMATION, Integer.SIZE);
+ buf.putInt(sender); // remote (server side) identifier
+ buf.putInt(channelId); // local (client side) identifier
+ buf.putInt(window.getSize());
+ buf.putInt(window.getPacketSize());
+ session.writePacket(buf);
+ } else {
+ Throwable exception = future.getException();
+ if (exception != null) {
+ String message = exception.getMessage();
+ int reasonCode = 0;
+ if (exception instanceof OpenChannelException) {
+ reasonCode = ((OpenChannelException) exception).getReasonCode();
+ } else {
+ message = exception.getClass().getSimpleName() + " while opening channel: " + message;
+ }
+
+ Buffer buf = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_OPEN_FAILURE, message.length() + Long.SIZE);
+ sendChannelOpenFailure(buf, sender, reasonCode, message, "");
+ }
+ }
+ } catch (IOException e) {
+ if (log.isDebugEnabled()) {
+ log.debug("operationComplete({}) {}: {}",
+ AbstractConnectionService.this, e.getClass().getSimpleName(), e.getMessage());
}
+ session.exceptionCaught(e);
}
});
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractSession.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractSession.java b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractSession.java
index 3f879e4..290ce96 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractSession.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractSession.java
@@ -63,7 +63,6 @@ import org.apache.sshd.common.forward.PortForwardingEventListener;
import org.apache.sshd.common.future.DefaultKeyExchangeFuture;
import org.apache.sshd.common.future.DefaultSshFuture;
import org.apache.sshd.common.future.KeyExchangeFuture;
-import org.apache.sshd.common.future.SshFutureListener;
import org.apache.sshd.common.io.IoSession;
import org.apache.sshd.common.io.IoWriteFuture;
import org.apache.sshd.common.kex.AbstractKexFactoryManager;
@@ -719,7 +718,7 @@ public abstract class AbstractSession extends AbstractKexFactoryManager implemen
Map<KexProposalOption, String> result = negotiate();
String kexAlgorithm = result.get(KexProposalOption.ALGORITHMS);
- kex = ValidateUtils.checkNotNull(NamedFactory.Utils.create(getKeyExchangeFactories(), kexAlgorithm),
+ kex = ValidateUtils.checkNotNull(NamedFactory.create(getKeyExchangeFactories(), kexAlgorithm),
"Unknown negotiated KEX algorithm: %s",
kexAlgorithm);
kex.init(this, serverVersion.getBytes(StandardCharsets.UTF_8), clientVersion.getBytes(StandardCharsets.UTF_8), i_s, i_c);
@@ -944,23 +943,14 @@ public abstract class AbstractSession extends AbstractKexFactoryManager implemen
final IoWriteFuture writeFuture = writePacket(buffer);
final DefaultSshFuture<IoWriteFuture> future = (DefaultSshFuture<IoWriteFuture>) writeFuture;
ScheduledExecutorService executor = factoryManager.getScheduledExecutorService();
- final ScheduledFuture<?> sched = executor.schedule(new Runnable() {
- @SuppressWarnings("synthetic-access")
- @Override
- public void run() {
- Throwable t = new TimeoutException("Timeout writing packet: " + timeout + " " + unit);
- if (log.isDebugEnabled()) {
- log.debug("writePacket({}): {}", AbstractSession.this, t.getMessage());
- }
- future.setValue(t);
- }
- }, timeout, unit);
- future.addListener(new SshFutureListener<IoWriteFuture>() {
- @Override
- public void operationComplete(IoWriteFuture future) {
- sched.cancel(false);
- }
- });
+ final ScheduledFuture<?> sched = executor.schedule(() -> {
+ Throwable t = new TimeoutException("Timeout writing packet: " + timeout + " " + unit);
+ if (log.isDebugEnabled()) {
+ log.debug("writePacket({}): {}", AbstractSession.this, t.getMessage());
+ }
+ future.setValue(t);
+ }, timeout, unit);
+ future.addListener(future1 -> sched.cancel(false));
return writeFuture;
}
@@ -1485,21 +1475,21 @@ public abstract class AbstractSession extends AbstractKexFactoryManager implemen
protected Map<KexProposalOption, String> createProposal(String hostKeyTypes) {
Map<KexProposalOption, String> proposal = new EnumMap<>(KexProposalOption.class);
proposal.put(KexProposalOption.ALGORITHMS,
- NamedResource.Utils.getNames(
+ NamedResource.getNames(
ValidateUtils.checkNotNullAndNotEmpty(getKeyExchangeFactories(), "No KEX factories")));
proposal.put(KexProposalOption.SERVERKEYS, hostKeyTypes);
- String ciphers = NamedResource.Utils.getNames(
+ String ciphers = NamedResource.getNames(
ValidateUtils.checkNotNullAndNotEmpty(getCipherFactories(), "No cipher factories"));
proposal.put(KexProposalOption.S2CENC, ciphers);
proposal.put(KexProposalOption.C2SENC, ciphers);
- String macs = NamedResource.Utils.getNames(
+ String macs = NamedResource.getNames(
ValidateUtils.checkNotNullAndNotEmpty(getMacFactories(), "No MAC factories"));
proposal.put(KexProposalOption.S2CMAC, macs);
proposal.put(KexProposalOption.C2SMAC, macs);
- String compressions = NamedResource.Utils.getNames(
+ String compressions = NamedResource.getNames(
ValidateUtils.checkNotNullAndNotEmpty(getCompressionFactories(), "No compression factories"));
proposal.put(KexProposalOption.S2CCOMP, compressions);
proposal.put(KexProposalOption.C2SCOMP, compressions);
@@ -1672,12 +1662,12 @@ public abstract class AbstractSession extends AbstractKexFactoryManager implemen
byte[] mac_s2c = hash.digest();
String value = getNegotiatedKexParameter(KexProposalOption.S2CENC);
- Cipher s2ccipher = ValidateUtils.checkNotNull(NamedFactory.Utils.create(getCipherFactories(), value), "Unknown s2c cipher: %s", value);
+ Cipher s2ccipher = ValidateUtils.checkNotNull(NamedFactory.create(getCipherFactories(), value), "Unknown s2c cipher: %s", value);
e_s2c = resizeKey(e_s2c, s2ccipher.getBlockSize(), hash, k, h);
s2ccipher.init(isServer ? Cipher.Mode.Encrypt : Cipher.Mode.Decrypt, e_s2c, iv_s2c);
value = getNegotiatedKexParameter(KexProposalOption.S2CMAC);
- Mac s2cmac = NamedFactory.Utils.create(getMacFactories(), value);
+ Mac s2cmac = NamedFactory.create(getMacFactories(), value);
if (s2cmac == null) {
throw new SshException(SshConstants.SSH2_DISCONNECT_MAC_ERROR, "Unknown s2c MAC: " + value);
}
@@ -1685,18 +1675,18 @@ public abstract class AbstractSession extends AbstractKexFactoryManager implemen
s2cmac.init(mac_s2c);
value = getNegotiatedKexParameter(KexProposalOption.S2CCOMP);
- Compression s2ccomp = NamedFactory.Utils.create(getCompressionFactories(), value);
+ Compression s2ccomp = NamedFactory.create(getCompressionFactories(), value);
if (s2ccomp == null) {
throw new SshException(SshConstants.SSH2_DISCONNECT_COMPRESSION_ERROR, "Unknown s2c compression: " + value);
}
value = getNegotiatedKexParameter(KexProposalOption.C2SENC);
- Cipher c2scipher = ValidateUtils.checkNotNull(NamedFactory.Utils.create(getCipherFactories(), value), "Unknown c2s cipher: %s", value);
+ Cipher c2scipher = ValidateUtils.checkNotNull(NamedFactory.create(getCipherFactories(), value), "Unknown c2s cipher: %s", value);
e_c2s = resizeKey(e_c2s, c2scipher.getBlockSize(), hash, k, h);
c2scipher.init(isServer ? Cipher.Mode.Decrypt : Cipher.Mode.Encrypt, e_c2s, iv_c2s);
value = getNegotiatedKexParameter(KexProposalOption.C2SMAC);
- Mac c2smac = NamedFactory.Utils.create(getMacFactories(), value);
+ Mac c2smac = NamedFactory.create(getMacFactories(), value);
if (c2smac == null) {
throw new SshException(SshConstants.SSH2_DISCONNECT_MAC_ERROR, "Unknown c2s MAC: " + value);
}
@@ -1704,7 +1694,7 @@ public abstract class AbstractSession extends AbstractKexFactoryManager implemen
c2smac.init(mac_c2s);
value = getNegotiatedKexParameter(KexProposalOption.C2SCOMP);
- Compression c2scomp = NamedFactory.Utils.create(getCompressionFactories(), value);
+ Compression c2scomp = NamedFactory.create(getCompressionFactories(), value);
if (c2scomp == null) {
throw new SshException(SshConstants.SSH2_DISCONNECT_COMPRESSION_ERROR, "Unknown c2s compression: " + value);
}
@@ -1797,30 +1787,26 @@ public abstract class AbstractSession extends AbstractKexFactoryManager implemen
// Write the packet with a timeout to ensure a timely close of the session
// in case the consumer does not read packets anymore.
long disconnectTimeoutMs = PropertyResolverUtils.getLongProperty(this, FactoryManager.DISCONNECT_TIMEOUT, FactoryManager.DEFAULT_DISCONNECT_TIMEOUT);
- writePacket(buffer, disconnectTimeoutMs, TimeUnit.MILLISECONDS).addListener(new SshFutureListener<IoWriteFuture>() {
- @Override
- @SuppressWarnings("synthetic-access")
- public void operationComplete(IoWriteFuture future) {
- Throwable t = future.getException();
- if (log.isDebugEnabled()) {
- if (t == null) {
- log.debug("disconnect({}) operation successfully completed for reason={} [{}]",
- AbstractSession.this, SshConstants.getDisconnectReasonName(reason), msg);
- } else {
- log.debug("disconnect({}) operation failed ({}) for reason={} [{}]: {}",
- AbstractSession.this, t.getClass().getSimpleName(),
- SshConstants.getDisconnectReasonName(reason), msg, t.getMessage());
- }
+ writePacket(buffer, disconnectTimeoutMs, TimeUnit.MILLISECONDS).addListener(future -> {
+ Throwable t = future.getException();
+ if (log.isDebugEnabled()) {
+ if (t == null) {
+ log.debug("disconnect({}) operation successfully completed for reason={} [{}]",
+ AbstractSession.this, SshConstants.getDisconnectReasonName(reason), msg);
+ } else {
+ log.debug("disconnect({}) operation failed ({}) for reason={} [{}]: {}",
+ AbstractSession.this, t.getClass().getSimpleName(),
+ SshConstants.getDisconnectReasonName(reason), msg, t.getMessage());
}
+ }
- if (t != null) {
- if (log.isTraceEnabled()) {
- log.trace("disconnect(" + AbstractSession.this + ") reason=" + SshConstants.getDisconnectReasonName(reason) + " failure details", t);
- }
+ if (t != null) {
+ if (log.isTraceEnabled()) {
+ log.trace("disconnect(" + AbstractSession.this + ") reason=" + SshConstants.getDisconnectReasonName(reason) + " failure details", t);
}
-
- close(true);
}
+
+ close(true);
});
}
@@ -1988,7 +1974,7 @@ public abstract class AbstractSession extends AbstractKexFactoryManager implemen
@Override
public <T> T resolveAttribute(AttributeKey<T> key) {
- return AttributeStore.Utils.resolveAttribute(this, key);
+ return AttributeStore.resolveAttribute(this, key);
}
@Override
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionTimeoutListener.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionTimeoutListener.java b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionTimeoutListener.java
index 98025d7..da7818d 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionTimeoutListener.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionTimeoutListener.java
@@ -64,6 +64,7 @@ public class SessionTimeoutListener extends AbstractLoggingBean implements Sessi
sessionClosed(session);
}
+ @SuppressWarnings("SuspiciousMethodCalls")
@Override
public void sessionClosed(Session s) {
if (sessions.remove(s)) {
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/signature/BuiltinSignatures.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/signature/BuiltinSignatures.java b/sshd-core/src/main/java/org/apache/sshd/common/signature/BuiltinSignatures.java
index acd116e..a586bfe 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/signature/BuiltinSignatures.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/signature/BuiltinSignatures.java
@@ -214,7 +214,7 @@ public enum BuiltinSignatures implements SignatureFactory {
* (case <U>insensitive</U>) the provided name - {@code null} if no match
*/
public static BuiltinSignatures fromFactoryName(String name) {
- return NamedResource.Utils.findByName(name, String.CASE_INSENSITIVE_ORDER, VALUES);
+ return NamedResource.findByName(name, String.CASE_INSENSITIVE_ORDER, VALUES);
}
/**
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/signature/SignatureFactoriesManager.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/signature/SignatureFactoriesManager.java b/sshd-core/src/main/java/org/apache/sshd/common/signature/SignatureFactoriesManager.java
index 5bc3d54..2509a39 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/signature/SignatureFactoriesManager.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/signature/SignatureFactoriesManager.java
@@ -40,10 +40,10 @@ public interface SignatureFactoriesManager {
*/
List<NamedFactory<Signature>> getSignatureFactories();
default String getSignatureFactoriesNameList() {
- return NamedResource.Utils.getNames(getSignatureFactories());
+ return NamedResource.getNames(getSignatureFactories());
}
default List<String> getSignatureFactoriesNames() {
- return NamedResource.Utils.getNameList(getSignatureFactories());
+ return NamedResource.getNameList(getSignatureFactories());
}
void setSignatureFactories(List<NamedFactory<Signature>> factories);
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/subsystem/sftp/SftpConstants.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/subsystem/sftp/SftpConstants.java b/sshd-core/src/main/java/org/apache/sshd/common/subsystem/sftp/SftpConstants.java
index a9bb8c4..ac2764a 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/subsystem/sftp/SftpConstants.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/subsystem/sftp/SftpConstants.java
@@ -18,9 +18,7 @@
*/
package org.apache.sshd.common.subsystem.sftp;
-import java.lang.reflect.Field;
import java.util.Map;
-import java.util.function.Predicate;
import org.apache.sshd.common.util.GenericUtils;
import org.apache.sshd.common.util.logging.LoggingUtils;
@@ -279,16 +277,13 @@ public final class SftpConstants {
private static class LazyCommandNameHolder {
private static final Map<Integer, String> NAMES_MAP =
- LoggingUtils.generateMnemonicMap(SftpConstants.class, new Predicate<Field>() {
- @Override
- public boolean test(Field f) {
- String name = f.getName();
- return name.startsWith("SSH_FXP_")
- // exclude the rename modes which are not opcodes
- && (!name.startsWith("SSH_FXP_RENAME_"))
- // exclude the realpath modes wich are not opcodes
- && (!name.startsWith("SSH_FXP_REALPATH_"));
- }
+ LoggingUtils.generateMnemonicMap(SftpConstants.class, f -> {
+ String name = f.getName();
+ return name.startsWith("SSH_FXP_")
+ // exclude the rename modes which are not opcodes
+ && (!name.startsWith("SSH_FXP_RENAME_"))
+ // exclude the realpath modes wich are not opcodes
+ && (!name.startsWith("SSH_FXP_REALPATH_"));
});
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/subsystem/sftp/SftpUniversalOwnerAndGroup.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/subsystem/sftp/SftpUniversalOwnerAndGroup.java b/sshd-core/src/main/java/org/apache/sshd/common/subsystem/sftp/SftpUniversalOwnerAndGroup.java
index c8068f1..68ab055 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/subsystem/sftp/SftpUniversalOwnerAndGroup.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/subsystem/sftp/SftpUniversalOwnerAndGroup.java
@@ -62,6 +62,6 @@ public enum SftpUniversalOwnerAndGroup implements NamedResource {
}
public static SftpUniversalOwnerAndGroup fromName(String name) {
- return NamedResource.Utils.findByName(name, String.CASE_INSENSITIVE_ORDER, VALUES);
+ return NamedResource.findByName(name, String.CASE_INSENSITIVE_ORDER, VALUES);
}
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/util/EventListenerUtils.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/EventListenerUtils.java b/sshd-core/src/main/java/org/apache/sshd/common/util/EventListenerUtils.java
index 72b16b9..7bd7526 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/util/EventListenerUtils.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/util/EventListenerUtils.java
@@ -19,8 +19,6 @@
package org.apache.sshd.common.util;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;
import java.util.Collections;
@@ -40,55 +38,51 @@ public final class EventListenerUtils {
* there are no same references in a listener's set
*/
@SuppressWarnings("checkstyle:anoninnerlength")
- public static final Comparator<EventListener> LISTENER_INSTANCE_COMPARATOR =
- new Comparator<EventListener>() {
- @Override
- public int compare(EventListener l1, EventListener l2) {
- if (l1 == l2) {
- return 0;
- } else if (l1 == null) {
- return 1;
- } else if (l2 == null) {
- return -1;
- }
+ public static final Comparator<EventListener> LISTENER_INSTANCE_COMPARATOR = (l1, l2) -> {
+ if (l1 == l2) {
+ return 0;
+ } else if (l1 == null) {
+ return 1;
+ } else if (l2 == null) {
+ return -1;
+ }
- Class<?> c1 = l1.getClass();
- Class<?> c2 = l2.getClass();
- boolean checkHashCodes = true;
- if (Proxy.isProxyClass(c1)) {
- if (Proxy.isProxyClass(c2)) {
- checkHashCodes = false; // cannot call hashCode on a proxy
- } else {
- return 1;
- }
- } else if (Proxy.isProxyClass(c2)) {
- return -1;
- }
+ Class<?> c1 = l1.getClass();
+ Class<?> c2 = l2.getClass();
+ boolean checkHashCodes = true;
+ if (Proxy.isProxyClass(c1)) {
+ if (Proxy.isProxyClass(c2)) {
+ checkHashCodes = false; // cannot call hashCode on a proxy
+ } else {
+ return 1;
+ }
+ } else if (Proxy.isProxyClass(c2)) {
+ return -1;
+ }
- if (checkHashCodes) {
- int nRes = Integer.compare(l1.hashCode(), l2.hashCode());
- if (nRes != 0) {
- return nRes;
- }
- }
+ if (checkHashCodes) {
+ int nRes = Integer.compare(l1.hashCode(), l2.hashCode());
+ if (nRes != 0) {
+ return nRes;
+ }
+ }
- int nRes = Integer.compare(System.identityHashCode(l1), System.identityHashCode(l2));
- if (nRes != 0) {
- return nRes;
- }
+ int nRes = Integer.compare(System.identityHashCode(l1), System.identityHashCode(l2));
+ if (nRes != 0) {
+ return nRes;
+ }
- if (c1 != c2) {
- return c1.getName().compareTo(c2.getName());
- }
+ if (c1 != c2) {
+ return c1.getName().compareTo(c2.getName());
+ }
- String s1 = Objects.toString(l1.toString(), "");
- String s2 = Objects.toString(l2.toString(), "");
- nRes = s1.compareTo(s2);
- if (nRes != 0) {
- return nRes;
- }
- throw new UnsupportedOperationException("Ran out of options to compare instance of " + s1 + " vs. " + s2);
- }
+ String s1 = Objects.toString(l1.toString(), "");
+ String s2 = Objects.toString(l2.toString(), "");
+ nRes = s1.compareTo(s2);
+ if (nRes != 0) {
+ return nRes;
+ }
+ throw new UnsupportedOperationException("Ran out of options to compare instance of " + s1 + " vs. " + s2);
};
private EventListenerUtils() {
@@ -120,7 +114,7 @@ public final class EventListenerUtils {
* @see #LISTENER_INSTANCE_COMPARATOR
*/
public static <L extends EventListener> Set<L> synchronizedListenersSet() {
- return Collections.synchronizedSet(new TreeSet<L>(LISTENER_INSTANCE_COMPARATOR));
+ return Collections.synchronizedSet(new TreeSet<>(LISTENER_INSTANCE_COMPARATOR));
}
/**
@@ -197,25 +191,22 @@ public final class EventListenerUtils {
ValidateUtils.checkTrue(listenerType.isInterface(), "Target proxy is not an interface: %s", listenerType.getSimpleName());
ValidateUtils.checkNotNull(listeners, "No listeners container provided");
- Object wrapper = Proxy.newProxyInstance(loader, new Class<?>[]{listenerType}, new InvocationHandler() {
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- Throwable err = null;
- for (T l : listeners) {
- try {
- method.invoke(l, args);
- } catch (Throwable t) {
- Throwable e = GenericUtils.peelException(t);
- err = GenericUtils.accumulateException(err, e);
- }
- }
-
- if (err != null) {
- throw err;
+ Object wrapper = Proxy.newProxyInstance(loader, new Class<?>[]{listenerType}, (proxy, method, args) -> {
+ Throwable err = null;
+ for (T l : listeners) {
+ try {
+ method.invoke(l, args);
+ } catch (Throwable t) {
+ Throwable e = GenericUtils.peelException(t);
+ err = GenericUtils.accumulateException(err, e);
}
+ }
- return null; // we assume always void return value...
+ if (err != null) {
+ throw err;
}
+
+ return null; // we assume always void return value...
});
return listenerType.cast(wrapper);
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/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 ba58385..b8a04d1 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
@@ -27,7 +27,9 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
+import java.util.HashSet;
import java.util.Iterator;
+import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@@ -38,8 +40,15 @@ import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
+import java.util.function.BinaryOperator;
+import java.util.function.Consumer;
+import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
+import java.util.stream.Collector;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
import javax.management.MBeanException;
import javax.management.ReflectionException;
@@ -64,28 +73,18 @@ public final class GenericUtils {
/**
* 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);
- }
+ public static final Comparator<String> CASE_SENSITIVE_ORDER = (s1, s2) -> {
+ if (s1 == s2) {
+ return 0;
+ } else {
+ return s1.compareTo(s2);
}
};
public static final String QUOTES = "\"'";
@SuppressWarnings("rawtypes")
- private static final Factory CASE_INSENSITIVE_MAP_FACTORY = new Factory() {
- @Override
- @SuppressWarnings("unchecked")
- public Object create() {
- return new TreeMap(String.CASE_INSENSITIVE_ORDER);
- }
-
- };
+ private static final Factory CASE_INSENSITIVE_MAP_FACTORY = () -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
private GenericUtils() {
throw new UnsupportedOperationException("No instance");
@@ -121,6 +120,10 @@ public final class GenericUtils {
return length(cs) <= 0;
}
+ public static boolean isNotEmpty(CharSequence cs) {
+ return !isEmpty(cs);
+ }
+
// a List would be better, but we want to be compatible with String.split(...)
public static String[] split(String s, char ch) {
if (isEmpty(s)) {
@@ -217,6 +220,10 @@ public final class GenericUtils {
return (c == null) || c.isEmpty();
}
+ public static boolean isNotEmpty(Collection<?> c) {
+ return !isEmpty(c);
+ }
+
public static int size(Map<?, ?> m) {
return m == null ? 0 : m.size();
}
@@ -225,6 +232,10 @@ public final class GenericUtils {
return (m == null) || m.isEmpty();
}
+ public static boolean isNotEmpty(Map<?, ?> m) {
+ return !isEmpty(m);
+ }
+
@SafeVarargs
public static <T> int length(T... a) {
return a == null ? 0 : a.length;
@@ -240,10 +251,18 @@ public final class GenericUtils {
}
}
+ public static<T> boolean isNotEmpty(Iterable<? extends T> iter) {
+ return !isEmpty(iter);
+ }
+
public static <T> boolean isEmpty(Iterator<? extends T> iter) {
return iter == null || !iter.hasNext();
}
+ public static <T> boolean isNotEmpty(Iterator<? extends T> iter) {
+ return !isEmpty(iter);
+ }
+
@SafeVarargs
public static <T> boolean isEmpty(T... a) {
return length(a) <= 0;
@@ -275,6 +294,58 @@ public final class GenericUtils {
return result;
}
+ public static <T> void forEach(Iterable<T> values, Consumer<T> consumer) {
+ if (isNotEmpty(values)) {
+ values.forEach(consumer);
+ }
+ }
+
+ public static <T, U> List<U> map(Collection<T> values, Function<? super T, ? extends U> mapper) {
+ return stream(values).map(mapper).collect(Collectors.toList());
+ }
+
+ public static <T, U> SortedSet<U> mapSort(Collection<T> values,
+ Function<? super T, ? extends U> mapper,
+ Comparator<U> comparator) {
+ return stream(values).map(mapper).collect(toSortedSet(comparator));
+ }
+
+ public static <T, K, U> SortedMap<K, U> toSortedMap(
+ Iterable<T> values,
+ Function<? super T, ? extends K> keyMapper,
+ Function<? super T, ? extends U> valueMapper,
+ Comparator<K> comparator) {
+ return stream(values).collect(toSortedMap(keyMapper, valueMapper, comparator));
+ }
+
+ public static <T, K, U> Collector<T, ?, SortedMap<K, U>> toSortedMap(
+ Function<? super T, ? extends K> keyMapper,
+ Function<? super T, ? extends U> valueMapper,
+ Comparator<K> comparator) {
+ return Collectors.toMap(keyMapper, valueMapper, throwingMerger(), () -> new TreeMap<>(comparator));
+ }
+
+ private static <T> BinaryOperator<T> throwingMerger() {
+ return (u, v) -> {
+ throw new IllegalStateException(String.format("Duplicate key %s", u));
+ };
+ }
+
+ public static <T>
+ Collector<T, ?, SortedSet<T>> toSortedSet(Comparator<T> comparator) {
+ return Collectors.toCollection(() -> new TreeSet<>(comparator));
+ }
+
+ public static <T> Stream<T> stream(Iterable<T> values) {
+ if (isEmpty(values)) {
+ return Stream.empty();
+ } else if (values instanceof Collection) {
+ return ((Collection<T>) values).stream();
+ } else {
+ return StreamSupport.stream(values.spliterator(), false);
+ }
+ }
+
@SafeVarargs
public static <T> List<T> unmodifiableList(T ... values) {
return unmodifiableList(asList(values));
@@ -284,22 +355,31 @@ public final class GenericUtils {
if (isEmpty(values)) {
return Collections.emptyList();
} else {
- return Collections.unmodifiableList(new ArrayList<T>(values));
+ return Collections.unmodifiableList(new ArrayList<>(values));
}
}
+ public static <T> List<T> unmodifiableList(Stream<T> values) {
+ return unmodifiableList(values.collect(Collectors.toList()));
+ }
+
@SafeVarargs
public static <T> List<T> asList(T ... values) {
- int len = length(values);
- if (len <= 0) {
- return Collections.emptyList();
- } else {
- return Arrays.asList(values);
- }
+ return isEmpty(values) ? Collections.emptyList() : Arrays.asList(values);
+ }
+
+ @SafeVarargs
+ public static <T> Set<T> asSet(T ... values) {
+ return new HashSet<>(asList(values));
+ }
+
+ @SafeVarargs
+ public static <V extends Comparable<V>> SortedSet<V> asSortedSet(V ... values) {
+ return asSortedSet(Comparator.naturalOrder(), values);
}
public static <V extends Comparable<V>> SortedSet<V> asSortedSet(Collection<? extends V> values) {
- return asSortedSet(Comparator.<V>naturalOrder(), values);
+ return asSortedSet(Comparator.naturalOrder(), values);
}
/**
@@ -372,7 +452,7 @@ public final class GenericUtils {
* that 2 (or more) values are not mapped to the same key
*/
public static <K, V> Map<K, V> mapValues(
- Transformer<? super V, ? extends K> keyMapper, Factory<? extends Map<K, V>> mapCreator, Collection<? extends V> values) {
+ Transformer<? super V, ? extends K> keyMapper, Factory<? extends Map<K, V>> mapCreator, Collection<V> values) {
if (isEmpty(values)) {
return Collections.emptyMap();
}
@@ -411,18 +491,9 @@ public final class GenericUtils {
* @return A {@link List} of all the values that were accepted by the predicate
*/
public static <T> List<T> selectMatchingMembers(Predicate<? super T> acceptor, Collection<? extends T> values) {
- if (isEmpty(values)) {
- return Collections.emptyList();
- }
-
- List<T> matches = new ArrayList<>(values.size());
- for (T v : values) {
- if (acceptor.test(v)) {
- matches.add(v);
- }
- }
-
- return matches;
+ return GenericUtils.stream(values)
+ .filter(acceptor::test)
+ .collect(Collectors.toList());
}
/**
@@ -597,6 +668,24 @@ public final class GenericUtils {
return (iter == null) ? Collections.emptyIterator() : iter;
}
+ public static <U, V> Iterable<V> wrapIterable(Iterable<? extends U> iter, Function<U, V> mapper) {
+ return () -> wrapIterator(iteratorOf(iter), mapper);
+ }
+
+ public static <U, V> Iterator<V> wrapIterator(Iterator<? extends U> iter, Function<U, V> mapper) {
+ final Iterator<? extends U> iterator = iteratorOf(iter);
+ return new Iterator<V>() {
+ @Override
+ public boolean hasNext() {
+ return iterator.hasNext();
+ }
+ @Override
+ public V next() {
+ return mapper.apply(iterator.next());
+ }
+ };
+ }
+
/**
* Wraps a group of {@link Supplier}s of {@link Iterable} instances into a "unified"
* {@link Iterable} of their values, in the same order as the suppliers - i.e., once the values
@@ -608,50 +697,71 @@ public final class GenericUtils {
* @return The wrapping instance
*/
public static <T> Iterable<T> multiIterableSuppliers(final Iterable<? extends Supplier<? extends Iterable<? extends T>>> providers) {
- return (providers == null) ? Collections.emptyList() : new Iterable<T>() {
+ return (providers == null) ? Collections.emptyList() : () -> new Iterator<T>() {
+ private final Iterator<? extends Supplier<? extends Iterable<? extends T>>> iter = iteratorOf(providers);
+ private Iterator<? extends T> current = nextIterator();
+
@Override
- public Iterator<T> iterator() {
- return new Iterator<T>() {
- private final Iterator<? extends Supplier<? extends Iterable<? extends T>>> iter = iteratorOf(providers);
- private Iterator<? extends T> current = nextIterator();
-
- @Override
- public boolean hasNext() {
- return current != null;
- }
+ public boolean hasNext() {
+ return current != null;
+ }
- @Override
- public T next() {
- if (current == null) {
- throw new NoSuchElementException("No more elements");
- }
+ @Override
+ public T next() {
+ if (current == null) {
+ throw new NoSuchElementException("No more elements");
+ }
- T value = current.next();
- if (!current.hasNext()) {
- current = nextIterator();
- }
+ T value = current.next();
+ if (!current.hasNext()) {
+ current = nextIterator();
+ }
- return value;
- }
+ return value;
+ }
- @Override
- public void remove() {
- throw new UnsupportedOperationException("remove");
+ private Iterator<? extends T> nextIterator() {
+ while (iter.hasNext()) {
+ Supplier<? extends Iterable<? extends T>> supplier = iter.next();
+ Iterator<? extends T> values = iteratorOf((supplier == null) ? null : supplier.get());
+ if (values.hasNext()) {
+ return values;
}
+ }
- private Iterator<? extends T> nextIterator() {
- while (iter.hasNext()) {
- Supplier<? extends Iterable<? extends T>> supplier = iter.next();
- Iterator<? extends T> values = iteratorOf((supplier == null) ? null : supplier.get());
- if (values.hasNext()) {
- return values;
- }
- }
-
- return null;
- }
- };
+ return null;
}
};
}
+
+ public static <K, V> MapBuilder<K, V> mapBuilder() {
+ return new MapBuilder<>();
+ }
+
+ public static <K, V> MapBuilder<K, V> mapBuilder(Comparator<K> comparator) {
+ return new MapBuilder<>(comparator);
+ }
+
+ public static class MapBuilder<K, V> {
+ private Map<K, V> map;
+
+ public MapBuilder() {
+ this.map = new LinkedHashMap<>();
+ }
+
+ public MapBuilder(Comparator<K> comparator) {
+ this.map = new TreeMap<>(comparator);
+ }
+
+ public MapBuilder<K, V> put(K k, V v) {
+ map.put(k, v);
+ return this;
+ }
+ public Map<K, V> build() {
+ return map;
+ }
+ public Map<K, V> immutable() {
+ return Collections.unmodifiableMap(map);
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/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 cedb963..ea2962e 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
@@ -28,12 +28,7 @@ public interface Int2IntFunction {
/**
* An {@link Int2IntFunction} that returns same value as input
*/
- Int2IntFunction IDENTITY = new Int2IntFunction() {
- @Override
- public int apply(int value) {
- return value;
- }
- };
+ Int2IntFunction IDENTITY = value -> value;
/**
* @param value Argument
@@ -42,6 +37,7 @@ public interface Int2IntFunction {
int apply(int value);
// CHECKSTYLE:OFF
+ @Deprecated
final class Utils {
// CHECKSTYLE:ON
@@ -50,47 +46,48 @@ public interface Int2IntFunction {
}
public static Int2IntFunction sub(int delta) {
- return add(0 - delta);
+ return Int2IntFunction.sub(delta);
}
public static Int2IntFunction add(final int delta) {
- if (delta == 0) {
- return IDENTITY;
- } else {
- return new Int2IntFunction() {
- @Override
- public int apply(int value) {
- return value + delta;
- }
- };
- }
+ return Int2IntFunction.add(delta);
}
public static Int2IntFunction mul(final int factor) {
- if (factor == 1) {
- return IDENTITY;
- } else {
- return new Int2IntFunction() {
- @Override
- public int apply(int value) {
- return value * factor;
- }
- };
- }
+ return Int2IntFunction.mul(factor);
}
public static Int2IntFunction div(final int factor) {
- if (factor == 1) {
- return IDENTITY;
- } else {
- ValidateUtils.checkTrue(factor != 0, "Zero division factor");
- return new Int2IntFunction() {
- @Override
- public int apply(int value) {
- return value / factor;
- }
- };
- }
+ return Int2IntFunction.div(factor);
+ }
+ }
+
+ static Int2IntFunction sub(int delta) {
+ return add(0 - delta);
+ }
+
+ static Int2IntFunction add(final int delta) {
+ if (delta == 0) {
+ return IDENTITY;
+ } else {
+ return value -> value + delta;
+ }
+ }
+
+ static Int2IntFunction mul(final int factor) {
+ if (factor == 1) {
+ return IDENTITY;
+ } else {
+ return value -> value * factor;
+ }
+ }
+
+ static Int2IntFunction div(final int factor) {
+ if (factor == 1) {
+ return IDENTITY;
+ } else {
+ ValidateUtils.checkTrue(factor != 0, "Zero division factor");
+ return value -> value / factor;
}
}
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/util/NumberUtils.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/NumberUtils.java b/sshd-core/src/main/java/org/apache/sshd/common/util/NumberUtils.java
index 51c321b..b29d4fa 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/util/NumberUtils.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/util/NumberUtils.java
@@ -20,9 +20,9 @@
package org.apache.sshd.common.util;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import java.util.stream.IntStream;
/**
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
@@ -33,26 +33,18 @@ public final class NumberUtils {
* primitive numerical values
*/
public static final List<Class<?>> NUMERIC_PRIMITIVE_CLASSES =
- Collections.unmodifiableList(Arrays.<Class<?>>asList(
+ GenericUtils.unmodifiableList(
Byte.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE,
Float.TYPE, Double.TYPE
- ));
+ );
/**
* A {@link List} containing all the pure powers of 2 for a {@code long}
* value. The value at index <I>n</I> is 2 to the power of <I>n</I>
*/
public static final List<Long> POWERS_OF_TWO =
- Collections.unmodifiableList(new ArrayList<Long>(Long.SIZE) {
- private static final long serialVersionUID = 1L; // we're not serializing it
-
- {
- long value = 1L;
- for (int power = 0; power < Long.SIZE; power++, value <<= 1) {
- add(value);
- }
- }
- });
+ GenericUtils.unmodifiableList(IntStream.range(0, 64)
+ .mapToObj(i -> 1L << i));
private NumberUtils() {
throw new UnsupportedOperationException("No instance");
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/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 8a9bbd8..5cb56d5 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
@@ -20,7 +20,6 @@ package org.apache.sshd.common.util;
import java.util.Comparator;
import java.util.Map;
-import java.util.Map.Entry;
import java.util.Objects;
/**
@@ -31,16 +30,11 @@ import java.util.Objects;
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
public class Pair<F, S> implements Map.Entry<F, S> {
- @SuppressWarnings("rawtypes")
- private static final Comparator<Map.Entry<Comparable, ?>> BY_KEY_COMPARATOR =
- new Comparator<Map.Entry<Comparable, ?>>() {
- @SuppressWarnings("unchecked")
- @Override
- public int compare(Entry<Comparable, ?> o1, Entry<Comparable, ?> o2) {
- Comparable k1 = o1.getKey();
- Comparable k2 = o2.getKey();
- return k1.compareTo(k2);
- }
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ private static final Comparator<Map.Entry<Comparable, ?>> BY_KEY_COMPARATOR = (o1, o2) -> {
+ Comparable k1 = o1.getKey();
+ Comparable k2 = o2.getKey();
+ return k1.compareTo(k2);
};
private final F first;
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/sshd-core/src/main/java/org/apache/sshd/common/util/ReflectionUtils.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/ReflectionUtils.java b/sshd-core/src/main/java/org/apache/sshd/common/util/ReflectionUtils.java
index 961f32a..f8e1d6c 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/util/ReflectionUtils.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/util/ReflectionUtils.java
@@ -27,12 +27,7 @@ import java.util.function.Predicate;
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
public final class ReflectionUtils {
- public static final Transformer<Field, String> FIELD_NAME_EXTRACTOR = new Transformer<Field, String>() {
- @Override
- public String transform(Field f) {
- return (f == null) ? null : f.getName();
- }
- };
+ public static final Transformer<Field, String> FIELD_NAME_EXTRACTOR = f -> (f == null) ? null : f.getName();
private ReflectionUtils() {
throw new UnsupportedOperationException("No instance");
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/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 a02d553..cb8ed8e 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
@@ -371,8 +371,8 @@ public final class SelectorUtils {
char ch;
boolean containsStar = false;
- for (int i = 0; i < patArr.length; i++) {
- if (patArr[i] == '*') {
+ for (char aPatArr : patArr) {
+ if (aPatArr == '*') {
containsStar = true;
break;
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/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 d353f8d..2d025b8 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
@@ -33,24 +33,16 @@ public interface Transformer<I, O> extends Function<I, O> {
* Invokes {@link Objects#toString(Object, String)} on the argument
* with {@code null} as the value to return if argument is {@code null}
*/
- Transformer<Object, String> TOSTRING = new Transformer<Object, String>() {
- @Override
- public String transform(Object input) {
- return Objects.toString(input, null);
- }
- };
+ Transformer<Object, String> TOSTRING = input -> Objects.toString(input, null);
/**
* Returns {@link Enum#name()} or {@code null} if argument is {@code null}
*/
- 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();
- }
+ Transformer<Enum<?>, String> ENUM_NAME_EXTRACTOR = input -> {
+ if (input == null) {
+ return null;
+ } else {
+ return input.name();
}
};
@@ -65,24 +57,21 @@ public interface Transformer<I, O> extends Function<I, O> {
O transform(I input);
// CHECKSTYLE:OFF
+ @Deprecated
final class Utils {
// CHECKSTYLE:ON
- @SuppressWarnings("rawtypes")
- private static final Transformer IDENTITY = new Transformer() {
- @Override
- public Object transform(Object input) {
- return input;
- }
- };
-
private Utils() {
throw new UnsupportedOperationException("No instance allowed");
}
- @SuppressWarnings({ "unchecked" })
public static <U extends V, V> Transformer<U, V> identity() {
- return IDENTITY;
+ return Transformer.identity();
}
}
+
+ static <U extends V, V> Transformer<U, V> identity() {
+ return input -> input;
+ }
+
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/977b7b52/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 3679471..d725dea 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
@@ -80,6 +80,12 @@ public final class ValidateUtils {
return t;
}
+ public static <T, C extends Iterable<T>> C checkNotNullAndNotEmpty(C t, String message, Object... args) {
+ t = checkNotNull(t, message, args);
+ checkTrue(GenericUtils.isNotEmpty(t), message, args);
+ return t;
+ }
+
public static byte[] checkNotNullAndNotEmpty(byte[] a, String message) {
a = checkNotNull(a, message);
checkTrue(NumberUtils.length(a) > 0, message);