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:javadepchecker.Main.java

/**
 * Check for orphaned class files not owned by any package in dependencies
 *
 * @param pkg Gentoo package name/*from  w  ww . j  a v a  2  s. co  m*/
 * @param deps collection of dependencies for the package
 * @return boolean if the dependency is found or not
 * @throws IOException
 */
private static boolean depsFound(Collection<String> pkgs, Collection<String> deps) throws IOException {
    boolean found = true;
    Collection<String> jars = new ArrayList<>();
    String[] bootClassPathJars = System.getProperty("sun.boot.class.path").split(":");
    // Do we need "java-config -r" here?
    for (String jar : bootClassPathJars) {
        File jarFile = new File(jar);
        if (jarFile.exists()) {
            jars.add(jar);
        }
    }
    pkgs.forEach((String pkg) -> {
        jars.addAll(getPackageJars(pkg));
    });

    if (jars.isEmpty()) {
        return false;
    }
    ArrayList<String> jarClasses = new ArrayList<>();
    jars.forEach((String jarName) -> {
        try {
            JarFile jar = new JarFile(jarName);
            Collections.list(jar.entries()).forEach((JarEntry entry) -> {
                jarClasses.add(entry.getName());
            });
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    for (String dep : deps) {
        if (!jarClasses.contains(dep)) {
            if (found) {
                System.out.println("Class files not found via DEPEND in package.env");
            }
            System.out.println("\t" + dep);
            found = false;
        }
    }
    return found;
}

From source file:com.hg.development.apps.messagenotifier_v1.Utils.Utility.java

/**
 *
 * @return adresse IP v4 actuelle du tlphone.
 * @throws SocketException/*  www  .j  a  v  a 2  s  .com*/
 */
private String getLocalIpAddress() throws SocketException {
    String ipv4 = null;
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());

        if (interfaces.size() > 0) {
            for (NetworkInterface ni : interfaces) {
                List<InetAddress> ialist = Collections.list(ni.getInetAddresses());

                if (ialist.size() > 0) {
                    for (InetAddress address : ialist) {
                        if (!address.isLoopbackAddress()
                                && InetAddressUtils.isIPv4Address(ipv4 = address.getHostAddress()))
                            ;
                    }
                }

            }
        }

    } catch (SocketException ex) {
        throw ex;
    } finally {
        return ipv4;
    }
}

From source file:com.buaa.cfs.net.DNS.java

/**
 * Returns all the IPs associated with the provided interface, if any, in textual form.
 *
 * @param strInterface        The name of the network interface or sub-interface to query (eg eth0 or eth0:0) or the
 *                            string "default"
 * @param returnSubinterfaces Whether to return IPs associated with subinterfaces of the given interface
 *
 * @return A string vector of all the IPs associated with the provided interface. The local host IP is returned if
 * the interface name "default" is specified or there is an I/O error looking for the given interface.
 *
 * @throws UnknownHostException If the given interface is invalid
 *///from  www  . ja  v a  2  s  . com
public static String[] getIPs(String strInterface, boolean returnSubinterfaces) throws UnknownHostException {
    if ("default".equals(strInterface)) {
        return new String[] { cachedHostAddress };
    }
    NetworkInterface netIf;
    try {
        netIf = NetworkInterface.getByName(strInterface);
        if (netIf == null) {
            netIf = getSubinterface(strInterface);
        }
    } catch (SocketException e) {
        LOG.warn("I/O error finding interface " + strInterface + ": " + e.getMessage());
        return new String[] { cachedHostAddress };
    }
    if (netIf == null) {
        throw new UnknownHostException("No such interface " + strInterface);
    }

    // NB: Using a LinkedHashSet to preserve the order for callers
    // that depend on a particular element being 1st in the array.
    // For example, getDefaultIP always returns the first element.
    LinkedHashSet<InetAddress> allAddrs = new LinkedHashSet<InetAddress>();
    allAddrs.addAll(Collections.list(netIf.getInetAddresses()));
    if (!returnSubinterfaces) {
        allAddrs.removeAll(getSubinterfaceInetAddrs(netIf));
    }

    String ips[] = new String[allAddrs.size()];
    int i = 0;
    for (InetAddress addr : allAddrs) {
        ips[i++] = addr.getHostAddress();
    }
    return ips;
}

From source file:org.kei.android.phone.netcap.OutputFragment.java

@Override
public void onClick(final View v) {
    if (v.equals(refreshBT)) {
        adapter.clear();/*from   www  .ja v a  2 s .c o m*/
        try {
            final List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            if (interfaces != null && interfaces.size() != 0)
                adapter.add(getResources().getText(R.string.any).toString());
            for (final NetworkInterface ni : interfaces)
                if (ni.isUp())
                    adapter.add(ni.getName());
        } catch (final Throwable e) {
            logException(e);
        }
    } else if (v.equals(browseOutputCaptureTV)) {
        final Map<String, String> extra = new HashMap<String, String>();
        extra.put(FileChooser.FILECHOOSER_TYPE_KEY, "" + FileChooser.FILECHOOSER_TYPE_DIRECTORY_ONLY);
        extra.put(FileChooser.FILECHOOSER_TITLE_KEY, "Save");
        extra.put(FileChooser.FILECHOOSER_MESSAGE_KEY, "Use this folder:? ");
        extra.put(FileChooser.FILECHOOSER_DEFAULT_DIR, browseOutputCaptureTV.getText().toString());
        extra.put(FileChooser.FILECHOOSER_SHOW_KEY, "" + FileChooser.FILECHOOSER_SHOW_DIRECTORY_ONLY);
        extra.put(FileChooser.FILECHOOSER_USER_MESSAGE, getClass().getSimpleName());
        Tools.switchToForResult(owner, FileChooserActivity.class, extra,
                FileChooserActivity.FILECHOOSER_SELECTION_TYPE_DIRECTORY);

    } else if (v.equals(captureBT)) {
        if (!captureBT.isChecked()) {
            captureBT.setChecked(true);
            delete();
        } else {
            String sdest = browseOutputCaptureTV.getText().toString();
            if (sdest.isEmpty()) {
                Tools.showAlertDialog(owner, "Error", "Empty destination folder!");
                captureBT.setChecked(false);
                return;
            }

            File legacy = new File(sdest.replaceFirst("emulated/([0-9]+)/", "emulated/legacy/"));
            File fdest = new File(sdest);
            Log.i(getClass().getSimpleName(), "Test directory '" + legacy + "'");
            if (legacy.isDirectory())
                fdest = legacy;
            if (!fdest.isDirectory()) {
                Tools.showAlertDialog(owner, "Error", "The destination folder is not a valid directory!");
                captureBT.setChecked(false);
                return;
            } else if (!fdest.canWrite()) {
                Tools.showAlertDialog(owner, "Error", "Unable to write into the destination folder!");
                captureBT.setChecked(false);
                return;
            }

            if (!RootTools.isAccessGiven()) {
                Resources r = getResources();
                Tools.toast(owner, R.drawable.ic_launcher, r.getString(R.string.root_toast_error));
                showResult.setText(" " + r.getString(R.string.root_error));
                captureBT.setChecked(false);
                return;
            }

            final PackageManager m = owner.getPackageManager();
            String s = owner.getPackageName();
            try {
                final PackageInfo p = m.getPackageInfo(s, 0);
                s = p.applicationInfo.dataDir;
            } catch (final PackageManager.NameNotFoundException e) {
            }
            s = s + "/netcap";
            copyFile(Build.SUPPORTED_ABIS[0] + "/netcap", s, owner);
            final File netcap = new File(s);
            if (!netcap.exists()) {
                Tools.showAlertDialog(owner, "Error",
                        "'netcap' for '" + Build.SUPPORTED_ABIS[0] + "' was not found!");
                return;
            }
            pname = netcap.getAbsolutePath();
            netcap.setExecutable(true);

            ifaces = "";
            String ni = (String) devicesSp.getSelectedItem();
            if (ni.equals(getResources().getText(R.string.any).toString())) {
                for (int i = 0; i < adapter.getCount(); i++) {
                    ni = adapter.getItem(i);
                    if (ni.equals(getResources().getText(R.string.any).toString()))
                        continue;
                    ifaces += ni;
                    if (i < adapter.getCount() - 1)
                        ifaces += ",";
                }
            } else
                ifaces = ni;

            final File outputFile = new File(fdest,
                    new SimpleDateFormat("yyyyMMdd_hhmmssa'_netcap.pcap'", Locale.US).format(new Date()));
            buffer.clear();
            new Thread(new Runnable() {
                public void run() {
                    try {
                        String cmd = netcap.getAbsolutePath() + " -i " + ifaces + " -f "
                                + outputFile.getAbsolutePath() + " -d";
                        if (promiscuousCB.isChecked())
                            cmd += " -p";
                        cmd += " 2>&1";
                        command = new Command(0, cmd) {
                            @Override
                            public void commandOutput(int id, String line) {
                                super.commandOutput(id, line);
                                if (line.startsWith(NETCAP_READY))
                                    pid = line.substring(NETCAP_READY.length());
                                buffer.add(line);
                                owner.runOnUiThread(new Runnable() {
                                    @SuppressWarnings("unchecked")
                                    @Override
                                    public void run() {
                                        final String[] lines = (String[]) buffer.toArray(new String[] {});
                                        final StringBuilder sb = new StringBuilder();
                                        for (final String s : lines)
                                            sb.append(" ").append(s).append("\n");
                                        showResult.setText(sb.toString());
                                    }
                                });
                            }

                            public void commandCompleted(int id, int exitcode) {
                                super.commandCompleted(id, exitcode);
                                owner.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        captureBT.setChecked(false);
                                    }
                                });
                            }

                            public void commandTerminated(int id, String reason) {
                                super.commandTerminated(id, reason);
                            }
                        };
                        RootTools.getShell(true).add(command);
                    } catch (final Exception e) {
                        logException(e);
                    }
                }
            }).start();
        }
    }
}

From source file:eu.planets_project.tb.gui.backing.ListExp.java

public Collection<Experiment> getAllExpAwaitingAuth() {
    // Get the experiments-to-approve list:
    TestbedManager testbedMan = (TestbedManager) JSFUtil.getManagedObject("TestbedManager");
    Collection<Experiment> myExps = testbedMan.getAllExperimentsAwaitingApproval();
    currExps = Collections.list(Collections.enumeration(myExps));
    sort(getSort(), isAscending());/*from w w  w .j av a  2s  .  com*/
    return currExps;
}

From source file:org.pentaho.hadoop.PropertiesConfigurationPropertiesTest.java

@Test
public void testKeys() {
    HashSet<String> names = new HashSet<>(Arrays.asList("a", "b", "c"));
    mockKeys(names);/*from   w w  w.  j a  v  a 2  s  . c  om*/
    assertEquals(names, new HashSet<>(Collections.list(propertiesConfigurationProperties.keys())));
}

From source file:org.apache.hadoop.hdfs.server.datanode.TestDataNodeMetricsLogger.java

private void addAppender(Log log, Appender appender) {
    org.apache.log4j.Logger logger = ((Log4JLogger) log).getLogger();
    @SuppressWarnings("unchecked")
    List<Appender> appenders = Collections.list(logger.getAllAppenders());
    ((AsyncAppender) appenders.get(0)).addAppender(appender);
}

From source file:org.springframework.boot.actuate.trace.WebRequestTraceFilter.java

private Map<String, Object> getRequestHeaders(HttpServletRequest request) {
    Map<String, Object> headers = new LinkedHashMap<String, Object>();
    Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        List<String> values = Collections.list(request.getHeaders(name));
        Object value = values;//from ww w  . j a v a2s  .com
        if (values.size() == 1) {
            value = values.get(0);
        } else if (values.isEmpty()) {
            value = "";
        }
        headers.put(name, value);
    }
    return headers;
}

From source file:net.dataforte.commons.resources.ClassUtils.java

/**
 * Returns all classes within the specified package. Supports filesystem, JARs and JBoss VFS
 * /*  w w  w .  j  a v a 2  s.  co m*/
 * @param folder
 * @return
 * @throws IOException
 */
public static Class<?>[] getClassesForPackage(String pckgname) 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 {
        ClassLoader cld = Thread.currentThread().getContextClassLoader();
        if (cld == null) {
            throw new ClassNotFoundException("Can't get class loader.");
        }
        // Ask for all resources for the path
        Enumeration<URL> resources = cld.getResources(pckgname.replace('.', '/'));
        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(pckgname.replace('.', '/')) && e.getName().endsWith(".class")
                            && !e.getName().contains("$")) {
                        String className = e.getName().replace("/", ".").substring(0, e.getName().length() - 6);
                        classes.add(Class.forName(className, true, cld));
                    }
                }
            } else if (res.getProtocol().equalsIgnoreCase("vfszip")) { // JBoss 5+
                try {
                    Object content = res.getContent();
                    Method getChildren = content.getClass().getMethod("getChildren");
                    List<?> files = (List<?>) getChildren.invoke(res.getContent());
                    Method getPathName = null;
                    for (Object o : files) {
                        if (getPathName == null) {
                            getPathName = o.getClass().getMethod("getPathName");
                        }
                        String pathName = (String) getPathName.invoke(o);
                        if (pathName.endsWith(".class")) {
                            String className = pathName.replace("/", ".").substring(0, pathName.length() - 6);
                            classes.add(Class.forName(className, true, cld));
                        }
                    }
                } catch (Exception e) {
                    throw new IOException("Error while scanning " + res.toString(), e);
                }
            } else {
                directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8")));
            }
        }
    } catch (NullPointerException x) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Null pointer exception)", x);
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Unsupported encoding)", encex);
    } catch (IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying to get all resources for " + pckgname, ioex);
    }

    // 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
            String[] files = directory.list();
            for (String file : files) {
                // we are only interested in .class files
                if (file.endsWith(".class")) {
                    // removes the .class extension
                    classes.add(Class.forName(pckgname + '.' + file.substring(0, file.length() - 6)));
                }
            }
        } else {
            throw new ClassNotFoundException(
                    pckgname + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    Class<?>[] classesA = new Class[classes.size()];
    classes.toArray(classesA);
    return classesA;
}

From source file:com.rincliu.library.util.RLNetUtil.java

/**
 * Get IP address from first non-localhost interface
 * //from w  w w.java2  s  .co  m
 * @param ipv4 true=return ipv4, false=return ipv6
 * @return address or empty string
 */
public static String getIPAddress(boolean useIPv4) {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            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 (Exception e) {
        e.printStackTrace();
    }
    return "";
}