org.apache.sshd.common.util.GenericUtils Java Examples

The following examples show how to use org.apache.sshd.common.util.GenericUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PortForwardingTest.java    From termd with Apache License 2.0 6 votes vote down vote up
private void waitForForwardingRequest(String expected, long timeout) throws InterruptedException {
    for (long remaining = timeout; remaining > 0L;) {
        long waitStart = System.currentTimeMillis();
        String actual = requestsQ.poll(remaining, TimeUnit.MILLISECONDS);
        long waitEnd = System.currentTimeMillis();
        if (GenericUtils.isEmpty(actual)) {
            throw new IllegalStateException("Failed to retrieve request=" + expected);
        }

        if (expected.equals(actual)) {
            return;
        }

        long waitDuration = waitEnd - waitStart;
        remaining -= waitDuration;
    }

    throw new IllegalStateException("Timeout while waiting to retrieve request=" + expected);
}
 
Example #2
Source File: FixedSftpSubsystem.java    From sftp-fs with Apache License 2.0 6 votes vote down vote up
@Override
public Command create() {
    SftpSubsystem subsystem = new FixedSftpSubsystem(getExecutorService(), isShutdownOnExit(), getUnsupportedAttributePolicy(),
            getFileSystemAccessor(), getErrorStatusDataHandler());
    Collection<? extends SftpEventListener> listeners = getRegisteredListeners();
    if (GenericUtils.size(listeners) > 0) {
        for (SftpEventListener l : listeners) {
            subsystem.addSftpEventListener(l);
        }
    }
    subsystem.addSftpEventListener(new AbstractSftpEventListenerAdapter() {
        @Override
        public void open(ServerSession session, String remoteHandle, Handle localHandle) {
            if (localHandle instanceof DirectoryHandle) {
                DirectoryHandle directoryHandle = (DirectoryHandle) localHandle;
                directoryHandle.markDotSent();
                directoryHandle.markDotDotSent();
            }
        }
    });

    return subsystem;
}
 
Example #3
Source File: BaseTestSupport.java    From termd with Apache License 2.0 6 votes vote down vote up
public static String shuffleCase(CharSequence cs) {
    if (GenericUtils.isEmpty(cs)) {
        return "";
    }

    StringBuilder sb = new StringBuilder(cs.length());
    for (int index = 0; index < cs.length(); index++) {
        char ch = cs.charAt(index);
        double v = Math.random();
        if (Double.compare(v, 0.3d) < 0) {
            ch = Character.toUpperCase(ch);
        } else if ((Double.compare(v, 0.3d) >= 0) && (Double.compare(v, 0.6d) < 0)) {
            ch = Character.toLowerCase(ch);
        }
        sb.append(ch);
    }

    return sb.toString();
}
 
Example #4
Source File: PortForwardingTest.java    From termd with Apache License 2.0 6 votes vote down vote up
private void waitForForwardingRequest(String expected, long timeout) throws InterruptedException {
    for (long remaining = timeout; remaining > 0L;) {
        long waitStart = System.currentTimeMillis();
        String actual = requestsQ.poll(remaining, TimeUnit.MILLISECONDS);
        long waitEnd = System.currentTimeMillis();
        if (GenericUtils.isEmpty(actual)) {
            throw new IllegalStateException("Failed to retrieve request=" + expected);
        }

        if (expected.equals(actual)) {
            return;
        }

        long waitDuration = waitEnd - waitStart;
        remaining -= waitDuration;
    }

    throw new IllegalStateException("Timeout while waiting to retrieve request=" + expected);
}
 
Example #5
Source File: Utils.java    From termd with Apache License 2.0 6 votes vote down vote up
/**
 * @param externalForm The {@link URL#toExternalForm()} string - ignored if
 *                     {@code null}/empty
 * @return The URL(s) source path where {@link #JAR_URL_PREFIX} and
 * any sub-resource are stripped
 */
public static String getURLSource(String externalForm) {
    String url = externalForm;
    if (GenericUtils.isEmpty(url)) {
        return url;
    }

    url = stripJarURLPrefix(externalForm);
    if (GenericUtils.isEmpty(url)) {
        return url;
    }

    int sepPos = url.indexOf(RESOURCE_SUBPATH_SEPARATOR);
    if (sepPos < 0) {
        return adjustURLPathValue(url);
    } else {
        return adjustURLPathValue(url.substring(0, sepPos));
    }
}
 
Example #6
Source File: Utils.java    From termd with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a {@link URI} that may refer to an internal resource to
 * a {@link File} representing is &quot;source&quot; container (e.g.,
 * if it is a resource in a JAR, then the result is the JAR's path)
 *
 * @param uri The {@link URI} - ignored if {@code null}
 * @return The matching {@link File}
 * @throws MalformedURLException If source URI does not refer to a
 *                               file location
 * @see #getURLSource(URI)
 */
public static File toFileSource(URI uri) throws MalformedURLException {
    String src = getURLSource(uri);
    if (GenericUtils.isEmpty(src)) {
        return null;
    }

    if (!src.startsWith(FILE_URL_PREFIX)) {
        throw new MalformedURLException("toFileSource(" + src + ") not a '" + FILE_URL_SCHEME + "' scheme");
    }

    try {
        return new File(new URI(src));
    } catch (URISyntaxException e) {
        throw new MalformedURLException("toFileSource(" + src + ")"
                + " cannot (" + e.getClass().getSimpleName() + ")"
                + " convert to URI: " + e.getMessage());
    }
}
 
Example #7
Source File: Utils.java    From termd with Apache License 2.0 6 votes vote down vote up
/**
 * Removes the specified file - if it is a directory, then its children
 * are deleted recursively and then the directory itself. <B>Note:</B>
 * no attempt is made to make sure that {@link File#delete()} was successful
 *
 * @param file The {@link File} to be deleted - ignored if {@code null}
 *             or does not exist anymore
 * @return The <tt>file</tt> argument
 */
public static File deleteRecursive(File file) {
    if ((file == null) || (!file.exists())) {
        return file;
    }

    if (file.isDirectory()) {
        File[] children = file.listFiles();
        if (!GenericUtils.isEmpty(children)) {
            for (File child : children) {
                deleteRecursive(child);
            }
        }
    }

    // seems that if a file is not writable it cannot be deleted
    if (!file.canWrite()) {
        file.setWritable(true, false);
    }

    if (!file.delete()) {
        System.err.append("Failed to delete ").println(file.getAbsolutePath());
    }

    return file;
}
 
Example #8
Source File: Utils.java    From termd with Apache License 2.0 6 votes vote down vote up
/**
 * Removes the specified file - if it is a directory, then its children
 * are deleted recursively and then the directory itself. <B>Note:</B>
 * no attempt is made to make sure that {@link File#delete()} was successful
 *
 * @param file The {@link File} to be deleted - ignored if {@code null}
 *             or does not exist anymore
 * @return The <tt>file</tt> argument
 */
public static File deleteRecursive(File file) {
    if ((file == null) || (!file.exists())) {
        return file;
    }

    if (file.isDirectory()) {
        File[] children = file.listFiles();
        if (!GenericUtils.isEmpty(children)) {
            for (File child : children) {
                deleteRecursive(child);
            }
        }
    }

    // seems that if a file is not writable it cannot be deleted
    if (!file.canWrite()) {
        file.setWritable(true, false);
    }

    if (!file.delete()) {
        System.err.append("Failed to delete ").println(file.getAbsolutePath());
    }

    return file;
}
 
Example #9
Source File: Utils.java    From termd with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a {@link URI} that may refer to an internal resource to
 * a {@link File} representing is &quot;source&quot; container (e.g.,
 * if it is a resource in a JAR, then the result is the JAR's path)
 *
 * @param uri The {@link URI} - ignored if {@code null}
 * @return The matching {@link File}
 * @throws MalformedURLException If source URI does not refer to a
 *                               file location
 * @see #getURLSource(URI)
 */
public static File toFileSource(URI uri) throws MalformedURLException {
    String src = getURLSource(uri);
    if (GenericUtils.isEmpty(src)) {
        return null;
    }

    if (!src.startsWith(FILE_URL_PREFIX)) {
        throw new MalformedURLException("toFileSource(" + src + ") not a '" + FILE_URL_SCHEME + "' scheme");
    }

    try {
        return new File(new URI(src));
    } catch (URISyntaxException e) {
        throw new MalformedURLException("toFileSource(" + src + ")"
                + " cannot (" + e.getClass().getSimpleName() + ")"
                + " convert to URI: " + e.getMessage());
    }
}
 
Example #10
Source File: Utils.java    From termd with Apache License 2.0 6 votes vote down vote up
/**
 * @param externalForm The {@link URL#toExternalForm()} string - ignored if
 *                     {@code null}/empty
 * @return The URL(s) source path where {@link #JAR_URL_PREFIX} and
 * any sub-resource are stripped
 */
public static String getURLSource(String externalForm) {
    String url = externalForm;
    if (GenericUtils.isEmpty(url)) {
        return url;
    }

    url = stripJarURLPrefix(externalForm);
    if (GenericUtils.isEmpty(url)) {
        return url;
    }

    int sepPos = url.indexOf(RESOURCE_SUBPATH_SEPARATOR);
    if (sepPos < 0) {
        return adjustURLPathValue(url);
    } else {
        return adjustURLPathValue(url.substring(0, sepPos));
    }
}
 
Example #11
Source File: BaseTestSupport.java    From termd with Apache License 2.0 6 votes vote down vote up
public static String shuffleCase(CharSequence cs) {
    if (GenericUtils.isEmpty(cs)) {
        return "";
    }

    StringBuilder sb = new StringBuilder(cs.length());
    for (int index = 0; index < cs.length(); index++) {
        char ch = cs.charAt(index);
        double v = Math.random();
        if (Double.compare(v, 0.3d) < 0) {
            ch = Character.toUpperCase(ch);
        } else if ((Double.compare(v, 0.3d) >= 0) && (Double.compare(v, 0.6d) < 0)) {
            ch = Character.toLowerCase(ch);
        }
        sb.append(ch);
    }

    return sb.toString();
}
 
Example #12
Source File: Utils.java    From termd with Apache License 2.0 5 votes vote down vote up
public static File resolve(File root, String... children) {
    if (GenericUtils.isEmpty(children)) {
        return root;
    } else {
        return resolve(root, Arrays.asList(children));
    }
}
 
Example #13
Source File: Utils.java    From termd with Apache License 2.0 5 votes vote down vote up
public static Path resolve(Path root, Collection<String> children) {
    Path path = root;
    if (!GenericUtils.isEmpty(children)) {
        for (String child : children) {
            path = path.resolve(child);
        }
    }

    return path;
}
 
Example #14
Source File: Utils.java    From termd with Apache License 2.0 5 votes vote down vote up
public static Path resolve(Path root, String... children) {
    if (GenericUtils.isEmpty(children)) {
        return root;
    } else {
        return resolve(root, Arrays.asList(children));
    }
}
 
Example #15
Source File: BaseTestSupport.java    From termd with Apache License 2.0 5 votes vote down vote up
public static <K, V> void assertMapEquals(String message, Map<? extends K, ? extends V> expected, Map<? super K, ? extends V> actual) {
    int numItems = GenericUtils.size(expected);
    assertEquals(message + "[size]", numItems, GenericUtils.size(actual));

    if (numItems > 0) {
        for (Map.Entry<? extends K, ? extends V> ee : expected.entrySet()) {
            K key = ee.getKey();
            V expValue = ee.getValue();
            V actValue = actual.get(key);
            assertEquals(message + "[" + key + "]", expValue, actValue);
        }
    }
}
 
Example #16
Source File: BaseTestSupport.java    From termd with Apache License 2.0 5 votes vote down vote up
public static <E> void assertListEquals(String message, List<? extends E> expected, List<? extends E> actual) {
    int expSize = GenericUtils.size(expected);
    int actSize = GenericUtils.size(actual);
    assertEquals(message + "[size]", expSize, actSize);

    for (int index = 0; index < expSize; index++) {
        E expValue = expected.get(index);
        E actValue = actual.get(index);
        assertEquals(message + "[" + index + "]", expValue, actValue);
    }
}
 
Example #17
Source File: BaseTestSupport.java    From termd with Apache License 2.0 5 votes vote down vote up
public static List<Object[]> parameterize(Collection<?> params) {
    if (GenericUtils.isEmpty(params)) {
        return Collections.emptyList();
    }

    List<Object[]> result = new ArrayList<Object[]>(params.size());
    for (Object p : params) {
        result.add(new Object[]{p});
    }

    return result;
}
 
Example #18
Source File: BaseTestSupport.java    From termd with Apache License 2.0 5 votes vote down vote up
public static String repeat(CharSequence csq, int nTimes) {
    if (GenericUtils.isEmpty(csq) || (nTimes <= 0)) {
        return "";
    }

    StringBuilder sb = new StringBuilder(nTimes * csq.length());
    for (int index = 0; index < nTimes; index++) {
        sb.append(csq);
    }

    return sb.toString();
}
 
Example #19
Source File: Utils.java    From termd with Apache License 2.0 5 votes vote down vote up
public static String stripJarURLPrefix(String externalForm) {
    String url = externalForm;
    if (GenericUtils.isEmpty(url)) {
        return url;
    }

    if (url.startsWith(JAR_URL_PREFIX)) {
        return url.substring(JAR_URL_PREFIX.length());
    }

    return url;
}
 
Example #20
Source File: Utils.java    From termd with Apache License 2.0 5 votes vote down vote up
/**
 * @param name The fully qualified class name - ignored if {@code null}/empty
 * @return The relative path of the class file byte-code resource
 */
public static String getClassBytesResourceName(String name) {
    if (GenericUtils.isEmpty(name)) {
        return name;
    } else {
        return new StringBuilder(name.length() + CLASS_FILE_SUFFIX.length())
                .append(name.replace('.', '/'))
                .append(CLASS_FILE_SUFFIX)
                .toString();
    }
}
 
Example #21
Source File: AsyncUserAuthService.java    From termd with Apache License 2.0 5 votes vote down vote up
protected void handleAuthenticationFailure(int cmd, Buffer buffer) throws Exception {
  String username = (currentAuth == null) ? null : currentAuth.getUsername();
  ServerSession session = getServerSession();
  if (log.isDebugEnabled()) {
    log.debug("handleAuthenticationFailure({}@{}) {}",
        username, session, SshConstants.getCommandMessageName(cmd));
  }

  StringBuilder sb = new StringBuilder((authMethods.size() + 1) * Byte.SIZE);
  for (List<String> l : authMethods) {
    if (GenericUtils.size(l) > 0) {
      String m = l.get(0);
      if (!UserAuthNoneFactory.NAME.equals(m)) {
        if (sb.length() > 0) {
          sb.append(",");
        }
        sb.append(m);
      }
    }
  }

  String remaining = sb.toString();
  if (log.isDebugEnabled()) {
    log.debug("handleAuthenticationFailure({}@{}) remaining methods: {}", username, session, remaining);
  }

  buffer = session.createBuffer(SshConstants.SSH_MSG_USERAUTH_FAILURE, remaining.length() + Byte.SIZE);
  buffer.putString(remaining);
  buffer.putBoolean(false);   // no partial success ...
  session.writePacket(buffer);

  if (currentAuth != null) {
    try {
      currentAuth.destroy();
    } finally {
      currentAuth = null;
    }
  }
}
 
Example #22
Source File: AsyncUserAuthService.java    From aesh-readline with Apache License 2.0 5 votes vote down vote up
public AsyncUserAuthService(Session s) throws SshException {
    ValidateUtils.checkTrue(s instanceof ServerSession, "Server side service used on client side");
    if (s.isAuthenticated()) {
        throw new SshException("Session already authenticated");
    }

    this.session = (ServerSession) s;
    maxAuthRequests = session.getIntProperty(ServerFactoryManager.MAX_AUTH_REQUESTS, DEFAULT_MAX_AUTH_REQUESTS);

    ServerFactoryManager manager = getFactoryManager();
    userAuthFactories = new ArrayList<>(manager.getUserAuthFactories());
    // Get authentication methods
    authMethods = new ArrayList<>();

    String mths = FactoryManagerUtils.getString(manager, ServerFactoryManager.AUTH_METHODS);
    if (GenericUtils.isEmpty(mths)) {
        for (NamedFactory<UserAuth> uaf : manager.getUserAuthFactories()) {
            authMethods.add(new ArrayList<>(Collections.singletonList(uaf.getName())));
        }
    }
    else {
        for (String mthl : mths.split("\\s")) {
            authMethods.add(new ArrayList<>(Arrays.asList(mthl.split(","))));
        }
    }
    // Verify all required methods are supported
    for (List<String> l : authMethods) {
        for (String m : l) {
            NamedFactory<UserAuth> factory = NamedResource.Utils.findByName(m, String.CASE_INSENSITIVE_ORDER, userAuthFactories);
            if (factory == null) {
                throw new SshException("Configured method is not supported: " + m);
            }
        }
    }

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Authorized authentication methods: "+ NamedResource.Utils.getNames(userAuthFactories));
    }
}
 
Example #23
Source File: PortForwardingTest.java    From termd with Apache License 2.0 5 votes vote down vote up
private Set<Thread> findThreads(ThreadGroup group, String name) {
    int numThreads = group.activeCount();
    Thread[] threads = new Thread[numThreads * 2];
    numThreads = group.enumerate(threads, false);
    Set<Thread> ret = new HashSet<Thread>();

    // Enumerate each thread in `group'
    for (int i = 0; i < numThreads; ++i) {
        Thread t = threads[i];
        // Get thread
        // log.debug("Thread name: " + threads[i].getName());
        if (checkThreadForPortForward(t, name)) {
            ret.add(t);
        }
    }
    // didn't find the thread to check the
    int numGroups = group.activeGroupCount();
    ThreadGroup[] groups = new ThreadGroup[numGroups * 2];
    numGroups = group.enumerate(groups, false);
    for (int i = 0; i < numGroups; ++i) {
        ThreadGroup g = groups[i];
        Collection<Thread> c = findThreads(g, name);
        if (GenericUtils.isEmpty(c)) {
            continue;   // debug breakpoint
        }
        ret.addAll(c);
    }
    return ret;
}
 
Example #24
Source File: FixedSftpSubsystem.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Override
public Command create() {
    SftpSubsystem subsystem = new FixedSftpSubsystem(getExecutorService(), isShutdownOnExit(), getUnsupportedAttributePolicy(),
            getFileSystemAccessor(), getErrorStatusDataHandler());
    Collection<? extends SftpEventListener> listeners = getRegisteredListeners();
    if (GenericUtils.size(listeners) > 0) {
        for (SftpEventListener l : listeners) {
            subsystem.addSftpEventListener(l);
        }
    }

    return subsystem;
}
 
Example #25
Source File: PortForwardingTest.java    From termd with Apache License 2.0 5 votes vote down vote up
private Set<Thread> findThreads(ThreadGroup group, String name) {
    int numThreads = group.activeCount();
    Thread[] threads = new Thread[numThreads * 2];
    numThreads = group.enumerate(threads, false);
    Set<Thread> ret = new HashSet<Thread>();

    // Enumerate each thread in `group'
    for (int i = 0; i < numThreads; ++i) {
        Thread t = threads[i];
        // Get thread
        // log.debug("Thread name: " + threads[i].getName());
        if (checkThreadForPortForward(t, name)) {
            ret.add(t);
        }
    }
    // didn't find the thread to check the
    int numGroups = group.activeGroupCount();
    ThreadGroup[] groups = new ThreadGroup[numGroups * 2];
    numGroups = group.enumerate(groups, false);
    for (int i = 0; i < numGroups; ++i) {
        ThreadGroup g = groups[i];
        Collection<Thread> c = findThreads(g, name);
        if (GenericUtils.isEmpty(c)) {
            continue;   // debug breakpoint
        }
        ret.addAll(c);
    }
    return ret;
}
 
Example #26
Source File: AsyncUserAuthService.java    From termd with Apache License 2.0 5 votes vote down vote up
protected void handleAuthenticationFailure(int cmd, Buffer buffer) throws Exception {
  String username = (currentAuth == null) ? null : currentAuth.getUsername();
  ServerSession session = getServerSession();
  if (log.isDebugEnabled()) {
    log.debug("handleAuthenticationFailure({}@{}) {}",
        username, session, SshConstants.getCommandMessageName(cmd));
  }

  StringBuilder sb = new StringBuilder((authMethods.size() + 1) * Byte.SIZE);
  for (List<String> l : authMethods) {
    if (GenericUtils.size(l) > 0) {
      String m = l.get(0);
      if (!UserAuthNoneFactory.NAME.equals(m)) {
        if (sb.length() > 0) {
          sb.append(",");
        }
        sb.append(m);
      }
    }
  }

  String remaining = sb.toString();
  if (log.isDebugEnabled()) {
    log.debug("handleAuthenticationFailure({}@{}) remaining methods: {}", username, session, remaining);
  }

  buffer = session.createBuffer(SshConstants.SSH_MSG_USERAUTH_FAILURE, remaining.length() + Byte.SIZE);
  buffer.putString(remaining);
  buffer.putBoolean(false);   // no partial success ...
  session.writePacket(buffer);

  if (currentAuth != null) {
    try {
      currentAuth.destroy();
    } finally {
      currentAuth = null;
    }
  }
}
 
Example #27
Source File: BaseTestSupport.java    From termd with Apache License 2.0 5 votes vote down vote up
public static String repeat(CharSequence csq, int nTimes) {
    if (GenericUtils.isEmpty(csq) || (nTimes <= 0)) {
        return "";
    }

    StringBuilder sb = new StringBuilder(nTimes * csq.length());
    for (int index = 0; index < nTimes; index++) {
        sb.append(csq);
    }

    return sb.toString();
}
 
Example #28
Source File: Utils.java    From termd with Apache License 2.0 5 votes vote down vote up
/**
 * @param name The fully qualified class name - ignored if {@code null}/empty
 * @return The relative path of the class file byte-code resource
 */
public static String getClassBytesResourceName(String name) {
    if (GenericUtils.isEmpty(name)) {
        return name;
    } else {
        return new StringBuilder(name.length() + CLASS_FILE_SUFFIX.length())
                .append(name.replace('.', '/'))
                .append(CLASS_FILE_SUFFIX)
                .toString();
    }
}
 
Example #29
Source File: Utils.java    From termd with Apache License 2.0 5 votes vote down vote up
public static String stripJarURLPrefix(String externalForm) {
    String url = externalForm;
    if (GenericUtils.isEmpty(url)) {
        return url;
    }

    if (url.startsWith(JAR_URL_PREFIX)) {
        return url.substring(JAR_URL_PREFIX.length());
    }

    return url;
}
 
Example #30
Source File: Utils.java    From termd with Apache License 2.0 5 votes vote down vote up
public static File resolve(File root, String... children) {
    if (GenericUtils.isEmpty(children)) {
        return root;
    } else {
        return resolve(root, Arrays.asList(children));
    }
}