Java Code Examples for org.apache.sshd.common.util.GenericUtils#isEmpty()

The following examples show how to use org.apache.sshd.common.util.GenericUtils#isEmpty() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
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 17
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 18
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 19
Source File: AsyncUserAuthService.java    From termd with Apache License 2.0 4 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");
  }

  serverSession = (ServerSession) s;
  maxAuthRequests = PropertyResolverUtils.getIntProperty(s, ServerAuthenticationManager.MAX_AUTH_REQUESTS, ServerAuthenticationManager.DEFAULT_MAX_AUTH_REQUESTS);

  List<NamedFactory<UserAuth>> factories = ValidateUtils.checkNotNullAndNotEmpty(
      serverSession.getUserAuthFactories(), "No user auth factories for %s", s);
  userAuthFactories = new ArrayList<>(factories);
  // Get authentication methods
  authMethods = new ArrayList<>();

  String mths = PropertyResolverUtils.getString(s, ServerFactoryManager.AUTH_METHODS);
  if (GenericUtils.isEmpty(mths)) {
    for (NamedFactory<UserAuth> uaf : factories) {
      authMethods.add(new ArrayList<>(Collections.singletonList(uaf.getName())));
    }
  } else {
    if (log.isDebugEnabled()) {
      log.debug("ServerUserAuthService({}) using configured methods={}", s, mths);
    }
    for (String mthl : mths.split("\\s")) {
      authMethods.add(new ArrayList<>(Arrays.asList(GenericUtils.split(mthl, ','))));
    }
  }
  // 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 (log.isDebugEnabled()) {
    log.debug("ServerUserAuthService({}) authorized authentication methods: {}",
        s, NamedResource.Utils.getNames(userAuthFactories));
  }
}
 
Example 20
Source File: AsyncUserAuthService.java    From termd with Apache License 2.0 4 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");
  }

  serverSession = (ServerSession) s;
  maxAuthRequests = PropertyResolverUtils.getIntProperty(s, ServerAuthenticationManager.MAX_AUTH_REQUESTS, ServerAuthenticationManager.DEFAULT_MAX_AUTH_REQUESTS);

  List<NamedFactory<UserAuth>> factories = ValidateUtils.checkNotNullAndNotEmpty(
      serverSession.getUserAuthFactories(), "No user auth factories for %s", s);
  userAuthFactories = new ArrayList<NamedFactory<UserAuth>>(factories);
  // Get authentication methods
  authMethods = new ArrayList<List<String>>();

  String mths = PropertyResolverUtils.getString(s, ServerFactoryManager.AUTH_METHODS);
  if (GenericUtils.isEmpty(mths)) {
    for (NamedFactory<UserAuth> uaf : factories) {
      authMethods.add(new ArrayList<String>(Collections.singletonList(uaf.getName())));
    }
  } else {
    if (log.isDebugEnabled()) {
      log.debug("ServerUserAuthService({}) using configured methods={}", s, mths);
    }
    for (String mthl : mths.split("\\s")) {
      authMethods.add(new ArrayList<String>(Arrays.asList(GenericUtils.split(mthl, ','))));
    }
  }
  // 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 (log.isDebugEnabled()) {
    log.debug("ServerUserAuthService({}) authorized authentication methods: {}",
        s, NamedResource.Utils.getNames(userAuthFactories));
  }
}