Example usage for java.util Collections list

List of usage examples for java.util Collections list

Introduction

In this page you can find the example usage for java.util Collections list.

Prototype

public static <T> ArrayList<T> list(Enumeration<T> e) 

Source Link

Document

Returns an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration.

Usage

From source file:Main.java

public static String getJarSignature(String packagePath) throws IOException {
    Pattern signatureFilePattern = Pattern.compile("META-INF/[A-Z]+\\.SF");

    ZipFile packageZip = null;//from   w  ww  . ja  va2s.  c o  m
    try {
        packageZip = new ZipFile(packagePath);
        // For each file in the zip.
        for (ZipEntry entry : Collections.list(packageZip.entries())) {
            // Ignore non-signature files.
            if (!signatureFilePattern.matcher(entry.getName()).matches()) {
                continue;
            }

            BufferedReader sigContents = null;
            try {
                sigContents = new BufferedReader(new InputStreamReader(packageZip.getInputStream(entry)));
                // For each line in the signature file.
                while (true) {
                    String line = sigContents.readLine();
                    if (line == null || line.equals("")) {
                        throw new IllegalArgumentException(
                                "Failed to find manifest digest in " + entry.getName());
                    }
                    String prefix = "SHA1-Digest-Manifest: ";
                    if (line.startsWith(prefix)) {
                        return line.substring(prefix.length());
                    }
                }
            } finally {
                if (sigContents != null) {
                    sigContents.close();
                }
            }
        }
    } finally {
        if (packageZip != null) {
            packageZip.close();
        }
    }

    throw new IllegalArgumentException("Failed to find signature file.");
}

From source file:Main.java

/**
 * Convenience method for retrieving the UIDefault for a single property
 * of a particular class.//from w ww.ja v a2  s . c  om
 * 
 * @param clazz the class of interest
 * @param property the property to query
 * @return the UIDefault property, or null if not found
 */
public static Object getUIDefaultOfClass(Class<?> clazz, String property) {
    Object retVal = null;
    UIDefaults defaults = getUIDefaultsOfClass(clazz);
    List<Object> listKeys = Collections.list(defaults.keys());
    for (Object key : listKeys) {
        if (key.equals(property)) {
            return defaults.get(key);
        }
        if (key.toString().equalsIgnoreCase(property)) {
            retVal = defaults.get(key);
        }
    }
    return retVal;
}

From source file:com.ihelpoo.app.common.DeviceUtil.java

/**
 * Returns MAC address of the given interface name.
 *
 * @param interfaceName eth0, wlan0 or NULL=use first interface
 * @return mac address or empty string/* w ww  .j ava  2s.c o m*/
 */
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static String getMACAddress(String interfaceName) {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            if (interfaceName != null) {
                if (!intf.getName().equalsIgnoreCase(interfaceName))
                    continue;
            }
            byte[] mac = intf.getHardwareAddress();
            if (mac == null)
                return "";
            StringBuilder buf = new StringBuilder();
            for (int idx = 0; idx < mac.length; idx++)
                buf.append(String.format("%02X:", mac[idx]));
            if (buf.length() > 0)
                buf.deleteCharAt(buf.length() - 1);
            return buf.toString();
        }
    } catch (Exception ex) {
    } // for now eat exceptions
    return "";
    /*try {
    // this is so Linux hack
    return loadFileAsString("/sys/class/net/" +interfaceName + "/address").toUpperCase().trim();
    } catch (IOException ex) {
    return null;
    }*/
}

From source file:de.uni_bonn.bit.IPAddressHelper.java

/**
 * Returns a list of IP addresses that can be used to communicate with a peer on a
 * different machine. The IP addresses are in CIDR notation (e.g. 192.168.2.1/24).
 * @return//  w ww  .ja v  a 2  s. c o  m
 */
public static List<String> getAllUsableIPAddresses() {
    List<String> output = new ArrayList<String>();
    try {
        for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces())) {
            for (InterfaceAddress address : ni.getInterfaceAddresses()) {
                if (!address.getAddress().isMulticastAddress() && !address.getAddress().isLinkLocalAddress()
                        && !address.getAddress().isLoopbackAddress()) {
                    output.add(address.getAddress().getHostAddress() + "/" + address.getNetworkPrefixLength());
                }
            }
        }
    } catch (SocketException e) {

    }
    return output;
}

From source file:Main.java

public static String getLocalIpAddress() {
    try {//from  w ww  .  j  a v a2 s .c o  m
        String ipv4;
        List<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface ni : nilist) {
            List<InetAddress> ialist = Collections.list(ni.getInetAddresses());
            for (InetAddress address : ialist) {
                if (!address.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(ipv4 = address.getHostAddress())) {
                    return ipv4;
                }
            }
        }
    } catch (SocketException ex) {
    }

    return null;
}

From source file:Main.java

/**
 * Copy the given Enumeration into a String array.
 * The Enumeration must contain String elements only.
 * @param enumeration the Enumeration to copy
 * @return the String array ({@code null} if the passed-in
 * Enumeration was {@code null})// w w  w.  j  a  v  a2s .  c o m
 */
public static String[] toStringArray(Enumeration<String> enumeration) {
    if (enumeration == null) {
        return null;
    }
    List<String> list = Collections.list(enumeration);
    return list.toArray(new String[list.size()]);
}

From source file:nfinity.FindPeer.java

public String ScanNetwork() {
    try {/*  ww  w.  j  av  a 2s  . co m*/
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets)) {
            Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
            for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                if (!inetAddress.getClass().toString().equals("class java.net.Inet6Address")) {
                    if (!inetAddress.isLoopbackAddress()) {
                        try {
                            SubnetUtils utils = new SubnetUtils(inetAddress.getHostAddress() + "/"
                                    + netint.getInterfaceAddresses().get(1).getNetworkPrefixLength());
                            String[] allIps = utils.getInfo().getAllAddresses();
                            return ConnectIP(allIps, inetAddress);
                        } catch (IllegalArgumentException ex) {
                            int prefix = NetworkInterface.getByInetAddress(inetAddress).getInterfaceAddresses()
                                    .get(0).getNetworkPrefixLength();
                            if (!inetAddress.isLoopbackAddress()) {
                                System.out
                                        .println("IP: " + inetAddress.getHostAddress() + " Prefix: " + prefix);
                                SubnetUtils utils = new SubnetUtils(
                                        inetAddress.getHostAddress() + "/" + prefix);
                                String[] allIps = utils.getInfo().getAllAddresses();
                                return ConnectIP(allIps, inetAddress);
                            }
                        }
                    }
                }
            }
        }
    } catch (SocketException ex) {
        System.out.println("Connection failed " + ex.getMessage());
    }
    return "Peer not found";
}

From source file:eu.codebits.plasmas.util.NetworkInterfaces.java

/**
 * @param interfaceName eth0, wlan0 or NULL=use first interface 
 * @param useIPv4//from w ww .  j  av a 2  s.c o m
 * @return address or empty string
 */
@SuppressLint("DefaultLocale")
public static String getIPAddress(String interfaceName, boolean useIPv4) {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            if (interfaceName != null) {
                if (!intf.getName().equalsIgnoreCase(interfaceName))
                    continue;
            }
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    String sAddr = addr.getHostAddress().toUpperCase();
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    if (useIPv4) {
                        if (isIPv4)
                            return sAddr;
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                            return delim < 0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (SocketException ex) {
    }
    return "";
}

From source file:Main.java

public static List<Class<?>> getClassesForPackage(final String iPackageName, final ClassLoader iClassLoader)
        throws ClassNotFoundException {
    // This will hold a list of directories matching the pckgname.
    // There may be more than one if a package is split over multiple jars/paths
    List<Class<?>> classes = new ArrayList<Class<?>>();
    ArrayList<File> directories = new ArrayList<File>();
    try {//  www .  ja v a 2s . co m
        // Ask for all resources for the path
        final String packageUrl = iPackageName.replace('.', '/');
        Enumeration<URL> resources = iClassLoader.getResources(packageUrl);
        if (!resources.hasMoreElements()) {
            resources = iClassLoader.getResources(packageUrl + CLASS_EXTENSION);
            if (resources.hasMoreElements()) {
                throw new IllegalArgumentException(
                        iPackageName + " does not appear to be a valid package but a class");
            }
        } else {
            while (resources.hasMoreElements()) {
                URL res = resources.nextElement();
                if (res.getProtocol().equalsIgnoreCase("jar")) {
                    JarURLConnection conn = (JarURLConnection) res.openConnection();
                    JarFile jar = conn.getJarFile();
                    for (JarEntry e : Collections.list(jar.entries())) {

                        if (e.getName().startsWith(iPackageName.replace('.', '/'))
                                && e.getName().endsWith(CLASS_EXTENSION) && !e.getName().contains("$")) {
                            String className = e.getName().replace("/", ".").substring(0,
                                    e.getName().length() - 6);
                            classes.add(Class.forName(className));
                        }
                    }
                } else
                    directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8")));
            }
        }
    } catch (NullPointerException x) {
        throw new ClassNotFoundException(
                iPackageName + " does not appear to be " + "a valid package (Null pointer exception)");
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(
                iPackageName + " does not appear to be " + "a valid package (Unsupported encoding)");
    } catch (IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying " + "to get all resources for " + iPackageName);
    }

    // For every directory identified capture all the .class files
    for (File directory : directories) {
        if (directory.exists()) {
            // Get the list of the files contained in the package
            File[] files = directory.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    classes.addAll(findClasses(file, iPackageName));
                } else {
                    String className;
                    if (file.getName().endsWith(CLASS_EXTENSION)) {
                        className = file.getName().substring(0,
                                file.getName().length() - CLASS_EXTENSION.length());
                        classes.add(Class.forName(iPackageName + '.' + className));
                    }
                }
            }
        } else {
            throw new ClassNotFoundException(
                    iPackageName + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    return classes;
}

From source file:psiprobe.tools.logging.log4j.Log4JLoggerAccessor.java

/**
 * Gets the appenders./*from   w  w w  .  ja va  2 s  .  co  m*/
 *
 * @return the appenders
 */
public List<Log4JAppenderAccessor> getAppenders() {
    List<Log4JAppenderAccessor> appenders = new ArrayList<>();
    try {
        for (Object unwrappedAppender : Collections
                .list((Enumeration<Object>) MethodUtils.invokeMethod(getTarget(), "getAllAppenders", null))) {
            Log4JAppenderAccessor appender = wrapAppender(unwrappedAppender);
            if (appender != null) {
                appenders.add(appender);
            }
        }
    } catch (Exception e) {
        logger.error("{}#getAllAppenders() failed", getTarget().getClass().getName(), e);
    }
    return appenders;
}