Java Code Examples for java.util.Collections#list()

The following examples show how to use java.util.Collections#list() . These examples are extracted from open source projects. 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
/**
 * Returns a list of all the addresses on the system.
 * @param  inclLoopback
 *         if {@code true}, include the loopback addresses
 * @param  ipv4Only
 *         it {@code true}, only IPv4 addresses will be included
 */
static List<InetAddress> getAddresses(boolean inclLoopback,
                                      boolean ipv4Only)
    throws SocketException {
    ArrayList<InetAddress> list = new ArrayList<InetAddress>();
    Enumeration<NetworkInterface> nets =
             NetworkInterface.getNetworkInterfaces();
    for (NetworkInterface netInf : Collections.list(nets)) {
        Enumeration<InetAddress> addrs = netInf.getInetAddresses();
        for (InetAddress addr : Collections.list(addrs)) {
            if (!list.contains(addr) &&
                    (inclLoopback ? true : !addr.isLoopbackAddress()) &&
                    (ipv4Only ? (addr instanceof Inet4Address) : true)) {
                list.add(addr);
            }
        }
    }

    return list;
}
 
Example 2
protected void discoverNetworkInterfaces() throws InitializationException {
    try {

        Enumeration<NetworkInterface> interfaceEnumeration = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface iface : Collections.list(interfaceEnumeration)) {
            //displayInterfaceInformation(iface);

            log.finer("Analyzing network interface: " + iface.getDisplayName());
            if (isUsableNetworkInterface(iface)) {
                log.fine("Discovered usable network interface: " + iface.getDisplayName());
                synchronized (networkInterfaces) {
                    networkInterfaces.add(iface);
                }
            } else {
                log.finer("Ignoring non-usable network interface: " + iface.getDisplayName());
            }
        }

    } catch (Exception ex) {
        throw new InitializationException("Could not not analyze local network interfaces: " + ex, ex);
    }
}
 
Example 3
Source Project: DeviceInfo   File: Methods.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns MAC address of the given interface name.
 *
 * @param interfaceName eth0, wlan0 or NULL=use first interface
 * @return mac address or empty string
 */
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 (byte aMac : mac) buf.append(String.format("%02X:", aMac));
            if (buf.length() > 0) buf.deleteCharAt(buf.length() - 1);
            return buf.toString();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return "";
}
 
Example 4
Source Project: jdk8u60   File: Util.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a list of all the addresses on the system.
 * @param  inclLoopback
 *         if {@code true}, include the loopback addresses
 * @param  ipv4Only
 *         it {@code true}, only IPv4 addresses will be included
 */
static List<InetAddress> getAddresses(boolean inclLoopback,
                                      boolean ipv4Only)
    throws SocketException {
    ArrayList<InetAddress> list = new ArrayList<InetAddress>();
    Enumeration<NetworkInterface> nets =
             NetworkInterface.getNetworkInterfaces();
    for (NetworkInterface netInf : Collections.list(nets)) {
        Enumeration<InetAddress> addrs = netInf.getInetAddresses();
        for (InetAddress addr : Collections.list(addrs)) {
            if (!list.contains(addr) &&
                    (inclLoopback ? true : !addr.isLoopbackAddress()) &&
                    (ipv4Only ? (addr instanceof Inet4Address) : true)) {
                list.add(addr);
            }
        }
    }

    return list;
}
 
Example 5
Source Project: jdk8u_jdk   File: Equals.java    License: GNU General Public License v2.0 6 votes vote down vote up
static void displayInterfaceInformation(NetworkInterface netint,
                                       PrintStream out) throws SocketException {
   out.printf("Display name: %s%n", netint.getDisplayName());
   out.printf("Name: %s%n", netint.getName());
   Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();

   for (InetAddress inetAddress : Collections.list(inetAddresses))
       out.printf("InetAddress: %s%n", inetAddress);

   out.printf("Up? %s%n", netint.isUp());
   out.printf("Loopback? %s%n", netint.isLoopback());
   out.printf("PointToPoint? %s%n", netint.isPointToPoint());
   out.printf("Supports multicast? %s%n", netint.supportsMulticast());
   out.printf("Virtual? %s%n", netint.isVirtual());
   out.printf("Hardware address: %s%n",
               Arrays.toString(netint.getHardwareAddress()));
   out.printf("MTU: %s%n", netint.getMTU());
   out.printf("Index: %s%n", netint.getIndex());
   out.printf("%n");
}
 
Example 6
Source Project: pandroid   File: NetworkUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get IP address from first non-localhost interface
 *
 * @param useIPv4 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();
                    if (useIPv4) {
                        if (addr instanceof Inet4Address)
                            return sAddr;
                    } else {
                        if (addr instanceof Inet6Address) {
                            int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                            return delim < 0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
    } // for now eat exceptions
    return "";
}
 
Example 7
/**
 * Similar to {@link #testRootConflict()} but now the revs 1 and 2 are identical for both trees,
 * they only diverge at the 3rd revision.
 * Assert that all 4 revisions are present after the createWithHistory and that a conflict
 * exists for the two latest generation docs.
 *
 * @throws Exception
 */
@Test
public void testLeafConflict() throws Exception {
    List<DocumentRevision> parallelTree = createRevisions(3);

    List<DocumentRevision> sharedHistory = Collections.list(Collections.enumeration
            (parallelTree.subList(0, 2))); //note sublist second index is *exclusive*
    sharedHistory.add(REV3.revision);

    advancedDatabase.createWithHistory(REV3.revision, REV3.generation, toHistory
            (sharedHistory));

    // Assert both trees are good
    assertRevisionAndHistoryPresent(Collections.singleton(REV3.revision));
    assertRevisionContent(Collections.singleton(REV3.revision), false); // Not a stub

    assertRevisionAndHistoryPresent(parallelTree);
    assertRevisionContent(parallelTree, false, false, false); // None are stubs

    assertNoUnexpectedRevs(Collections.singleton(REV3.revision), parallelTree);

    assertConflictBetween(REV3.revision.getRevision(), parallelTree.get(2).getRevision());
}
 
Example 8
Source Project: hottub   File: Utils.java    License: GNU General Public License v2.0 5 votes vote down vote up
static ArrayList<String> getZipFileEntryNames(ZipFile z) {
    ArrayList<String> out = new ArrayList<String>();
    for (ZipEntry ze : Collections.list(z.entries())) {
        out.add(ze.getName());
    }
    return out;
}
 
Example 9
/**
 * Updated based on the discussion in
 * http://stackoverflow.com/questions/6064510/how-to-get-ip-address-of-the-device-from-code
 * Get IP addresses from the non-localhost interfaces
 * @param useIPv4  true -> returns ipv4, false -> returns ipv6
 * @return  addresses or empty list
 */
private static List<String> getIPAddresses(boolean useIPv4) {
    List<String> ipAddresses = new ArrayList<>();
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            if (intf.getName().startsWith("dummy")) {
                continue;
            }
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    String sAddr = addr.getHostAddress();
                    boolean isIPv4 = sAddr.indexOf(':') < 0;
                    if (useIPv4) {
                        if (isIPv4) {
                            ipAddresses.add(sAddr);
                        }
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
                            ipAddresses.add(delim < 0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase());
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
        // for now, just catch all...
        Log.w(TAG, "Exception:" + ex.getMessage());
    }
    return ipAddresses;
}
 
Example 10
private static boolean hasIPv6() throws Exception {
    List<NetworkInterface> nics = Collections.list(NetworkInterface
            .getNetworkInterfaces());
    for (NetworkInterface nic : nics) {
        List<InetAddress> addrs = Collections.list(nic.getInetAddresses());
        for (InetAddress addr : addrs) {
            if (addr instanceof Inet6Address)
                return true;
        }
    }

    return false;
}
 
Example 11
public static void extractJar(JarFile jf, File where) throws Exception {
    for (JarEntry file : Collections.list(jf.entries())) {
        File out = new File(where, file.getName());
        if (file.isDirectory()) {
            out.mkdirs();
            continue;
        }
        File parent = out.getParentFile();
        if (parent != null && !parent.exists()) {
            parent.mkdirs();
        }
        InputStream is = null;
        OutputStream os = null;
        try {
            is = jf.getInputStream(file);
            os = new FileOutputStream(out);
            while (is.available() > 0) {
                os.write(is.read());
            }
        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        }
    }
}
 
Example 12
Source Project: openpojo   File: JarFileReader.java    License: Apache License 2.0 5 votes vote down vote up
private Set<String> getAllEntries() {
  Set<String> entries = new HashSet<String>();

  ArrayList<JarEntry> jarEntries = Collections.list(jarFile.entries());
  for (JarEntry entry : jarEntries)
    entries.add(entry.getName());

  return entries;
}
 
Example 13
Source Project: jdk8u60   File: Utils.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void copyJarFile(JarFile in, JarOutputStream out) throws IOException {
    byte[] buffer = new byte[1 << 14];
    for (JarEntry je : Collections.list(in.entries())) {
        out.putNextEntry(je);
        InputStream ein = in.getInputStream(je);
        for (int nr; 0 < (nr = ein.read(buffer)); ) {
            out.write(buffer, 0, nr);
        }
    }
    in.close();
    markJarFile(out);  // add PACK200 comment
}
 
Example 14
public static void main(String[] args) throws IOException, ZeroVectorException {
  PSITypeLister typeLister = new PSITypeLister(args);

  int numCountries = 0;
  for (ObjectVector vector : Collections.list(typeLister.semanticVectors.getAllVectors())) {
    numCountries += typeLister.printBestRelations(vector.getObject().toString());

  }
  System.out.println("Number of countries: " + numCountries);
  //notUsDollar(typeLister, FlagConfig.getFlagConfig(args));
}
 
Example 15
public static void main(String... args) {
    List<String> errors = new ArrayList<>();
    // Ensure that all Message fields have a corresponding key/value
    // in the resource bundle and that mnemonics can be looked
    // up where applicable.
    ResourceBundle rb = ResourceBundle.getBundle(RESOURCE_BUNDLE);
    for (Field field : Messages.class.getFields()) {
        if (isResourceKeyField(field)) {
            String resourceKey = field.getName();
            String message = readField(field);
            if (message.startsWith(MISSING_RESOURCE_KEY_PREFIX)) {
                errors.add("Can't find message (and perhaps mnemonic) for "
                        + Messages.class.getSimpleName() + "."
                        + resourceKey + " in resource bundle.");
            } else {
                String resourceMessage = rb.getString(resourceKey);
                if (hasMnemonicIdentifier(resourceMessage)) {
                    int mi = Resources.getMnemonicInt(message);
                    if (mi == 0) {
                        errors.add("Could not look up mnemonic for message '"
                                + message + "'.");
                    }
                }
            }
        }
    }

    // Ensure that there is Message class field for every resource key.
    for (String key : Collections.list(rb.getKeys())) {
        try {
            Messages.class.getField(key);
        } catch (NoSuchFieldException nfe) {
            errors.add("Can't find static field ("
                    + Messages.class.getSimpleName() + "." + key
                    + ") matching '" + key
                    + "' in resource bundle. Unused message?");
        }
    }

    if (errors.size() > 0) {
        throwError(errors);
    }
}
 
Example 16
Source Project: pampas   File: CompositeServerContext.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public List<String> getAllServiceName() {
    return Collections.list(instanceMap.keys());
}
 
Example 17
Source Project: development   File: SecurityIT.java    License: Apache License 2.0 4 votes vote down vote up
@Test(expected = SQLException.class)
public void testGetGroupNamesUserStringUserKey() throws Exception {
    String userKey = "CLIENTCERT";
    ADMRealmImpl realmImpl = new TestADMRealmImpl(userKey);
    Collections.list(realmImpl.getGroupNames(null));
}
 
Example 18
private void clearUiColumns() {
  List<TableColumn> columns = Collections.list(getTable().getColumnModel().getColumns());
  for (TableColumn column : columns) {
    getTable().removeColumn(column);
  }
}
 
Example 19
public static void main(String... args) {
    List<String> errors = new ArrayList<>();
    // Ensure that all Message fields have a corresponding key/value
    // in the resource bundle and that mnemonics can be looked
    // up where applicable.
    ResourceBundle rb = ResourceBundle.getBundle(RESOURCE_BUNDLE);
    for (Field field : Messages.class.getFields()) {
        if (isResourceKeyField(field)) {
            String resourceKey = field.getName();
            String message = readField(field);
            if (message.startsWith(MISSING_RESOURCE_KEY_PREFIX)) {
                errors.add("Can't find message (and perhaps mnemonic) for "
                        + Messages.class.getSimpleName() + "."
                        + resourceKey + " in resource bundle.");
            } else {
                String resourceMessage = rb.getString(resourceKey);
                if (hasMnemonicIdentifier(resourceMessage)) {
                    int mi = Resources.getMnemonicInt(message);
                    if (mi == 0) {
                        errors.add("Could not look up mnemonic for message '"
                                + message + "'.");
                    }
                }
            }
        }
    }

    // Ensure that there is Message class field for every resource key.
    for (String key : Collections.list(rb.getKeys())) {
        try {
            Messages.class.getField(key);
        } catch (NoSuchFieldException nfe) {
            errors.add("Can't find static field ("
                    + Messages.class.getSimpleName() + "." + key
                    + ") matching '" + key
                    + "' in resource bundle. Unused message?");
        }
    }

    if (errors.size() > 0) {
        throwError(errors);
    }
}
 
Example 20
@SuppressWarnings("unchecked")
public static List<Logger> getLoggers() {
	return Collections.list(LogManager.getCurrentLoggers());
}