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

The following are Jave code examples for showing how to use list() of the java.util.Collections class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ModuleFrame   File: DeviceUtil.java   View Source Code Vote up 6 votes
/**
 * 获取设备MAC地址
 *
 * @return MAC地址
 */
@RequiresPermission(Manifest.permission.INTERNET)
private static String getMacAddressByNetworkInterface() {
    try {
        List<NetworkInterface> nis = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface ni : nis) {
            if (!ni.getName().equalsIgnoreCase("wlan0")) continue;
            byte[] macBytes = ni.getHardwareAddress();
            if (macBytes != null && macBytes.length > 0) {
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02x:", b));
                }
                return res1.deleteCharAt(res1.length() - 1).toString();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "02:00:00:00:00:00";
}
 
Example 2
Project: DeviceInfo   File: Methods.java   View Source Code Vote up 6 votes
/**
 * 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 3
Project: incubator-servicecomb-java-chassis   File: HeaderProcessorCreator.java   View Source Code Vote up 6 votes
@Override
public Object getValue(HttpServletRequest request) throws Exception {
  Object value = null;
  if (targetType.isContainerType()) {
    Enumeration<String> headerValues = request.getHeaders(paramPath);
    if (headerValues == null) {
      return null;
    }

    value = Collections.list(headerValues);
  } else {
    value = request.getHeader(paramPath);
  }

  return convertValue(value, targetType);
}
 
Example 4
Project: elasticsearch_my   File: NetworkUtils.java   View Source Code Vote up 6 votes
/** Returns all site-local scope (private) addresses for interfaces that are up. */
static InetAddress[] getSiteLocalAddresses() throws SocketException {
    List<InetAddress> list = new ArrayList<>();
    for (NetworkInterface intf : getInterfaces()) {
        if (intf.isUp()) {
            for (InetAddress address : Collections.list(intf.getInetAddresses())) {
                if (address.isSiteLocalAddress()) {
                    list.add(address);
                }
            }
        }
    }
    if (list.isEmpty()) {
        throw new IllegalArgumentException("No up-and-running site-local (private) addresses found, got " + getInterfaces());
    }
    return list.toArray(new InetAddress[list.size()]);
}
 
Example 5
Project: incubator-netbeans   File: AntBridge.java   View Source Code Vote up 6 votes
@Override
public Enumeration<URL> findResources(String name) throws IOException {
    try {
        Enumeration<URL> us = super.findResources(name);
        if (LOG.isLoggable(Level.FINER)) {
            // Make a copy so it can be logged:
            List<URL> resources = Collections.list(us);
            us = Collections.enumeration(resources);
            LOG.finer("APURLCL.fRs: " + name + " -> " + resources + " [" + this + "]");
        }
        return us;
    } catch (IOException e) {
        LOG.log(Level.FINE, null, e);
        throw e;
    }
}
 
Example 6
Project: openjdk-jdk10   File: Util.java   View Source Code Vote up 6 votes
/**
 * 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 7
Project: KTools   File: NetworkUtils.java   View Source Code Vote up 6 votes
/**
 * 获取设备MAC地址
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
 *
 * @return MAC地址
 */
private static String getMacAddressByNetworkInterface() {
    try {
        List<NetworkInterface> nis = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface ni : nis) {
            if (!ni.getName().equalsIgnoreCase("wlan0")) continue;
            byte[] macBytes = ni.getHardwareAddress();
            if (macBytes != null && macBytes.length > 0) {
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02x:", b));
                }
                return res1.deleteCharAt(res1.length() - 1).toString();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "02:00:00:00:00:00";
}
 
Example 8
Project: openjdk-jdk10   File: PackerImpl.java   View Source Code Vote up 5 votes
List<InFile> scanJar(JarFile jf) throws IOException {
    // Collect jar entries, preserving order.
    List<InFile> inFiles = new ArrayList<>();
    try {
        for (JarEntry je : Collections.list(jf.entries())) {
            InFile inFile = new InFile(jf, je);
            assert(je.isDirectory() == inFile.name.endsWith("/"));
            inFiles.add(inFile);
        }
    } catch (IllegalStateException ise) {
        throw new IOException(ise.getLocalizedMessage(), ise);
    }
    return inFiles;
}
 
Example 9
Project: MockableJarGenerator   File: MockableJarGeneratorTest.java   View Source Code Vote up 5 votes
public void testJarRewriting() throws Exception {
    MockableJarGenerator generator = new MockableJarGenerator(true);
    
    File inputJar = new File(TestUtils.getRoot("testing"), "non-mockable.jar");
    File outputJar = new File(Files.createTempDir(), "mockable.jar");

    generator.createMockableJar(inputJar, outputJar);

    assertTrue(outputJar.exists());
    
    Set<String> expectedEntries = ImmutableSet.of(
            "META-INF/",
            "META-INF/MANIFEST.MF",
            "NonFinalClass.class",
            "FinalClass.class");
    
    Set<String> actualEntries = Sets.newHashSet();
    JarFile jarFile = new JarFile(outputJar);
    for (JarEntry entry : Collections.list(jarFile.entries())) {
        actualEntries.add(entry.getName());
    }
    
    assertEquals(expectedEntries, actualEntries);
    // TODO: Verify bytecode?
    
    jarFile.close();
}
 
Example 10
Project: Nird2   File: InvitationListener.java   View Source Code Vote up 5 votes
private void findNestedClassIds(Object o, Collection<String> ids) {
	o = getDataElementValue(o);
	if (o instanceof Enumeration<?>) {
		for (Object o1 : Collections.list((Enumeration<?>) o))
			findNestedClassIds(o1, ids);
	} else if (o instanceof UUID) {
		ids.add(o.toString());
	}
}
 
Example 11
Project: xm-commons   File: TimelineEventProducer.java   View Source Code Vote up 5 votes
private static Object getHeaderValue(HttpServletRequest request, String name) {
    List<String> value = Collections.list(request.getHeaders(name));
    if (value.size() == 1) {
        return value.get(0);
    }
    if (value.isEmpty()) {
        return "";
    }
    return value;
}
 
Example 12
Project: openjdk-jdk10   File: Utils.java   View Source Code Vote up 5 votes
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 13
Project: Cognizant-Intelligent-Test-Scripter   File: ReleaseNode.java   View Source Code Vote up 5 votes
public TestSetNode getTestSetBy(TestSet testSet) {
    for (TestSetNode testSetNode : Collections.list(children())) {
        if (testSetNode.getTestSet().equals(testSet)) {
            return testSetNode;
        }
    }
    return null;
}
 
Example 14
Project: ultra-debugger   File: IpUtils.java   View Source Code Vote up 5 votes
@Nullable
private static String getIpAddress(boolean useIPv4) {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface networkInterface : interfaces) {
            List<InetAddress> addresses = Collections.list(networkInterface.getInetAddresses());
            for (InetAddress address : addresses) {
                if (!address.isLoopbackAddress()) {
                    String resultAddress = address.getHostAddress().toUpperCase();
                    boolean isIPv4 = isIPv4Address(resultAddress);
                    if (useIPv4) {
                        if (isIPv4) {
                            return resultAddress;
                        }
                    } else {
                        if (!isIPv4) {
                            int delimiter = resultAddress.indexOf('%');
                            return delimiter < 0 ? resultAddress : resultAddress.substring(0, delimiter);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 15
Project: neoscada   File: SymbolContext.java   View Source Code Vote up 5 votes
public Map<String, String> getPropertiesAsMap ()
{
    final Map<String, String> r = new HashMap<String, String> ();
    for ( final Object key : Collections.list ( this.controller.getProperties ().propertyNames () ) )
    {
        r.put ( (String)key, this.controller.getProperties ().getProperty ( (String)key ) );
    }
    return r;
}
 
Example 16
Project: Android-Bridge-App   File: Utils.java   View Source Code Vote up 5 votes
/**
 * Get IP address from first non-localhost interface
 *
 * @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();
                    //boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    boolean isIPv4 = sAddr.indexOf(':') < 0;

                    if (useIPv4) {
                        if (isIPv4) return sAddr;
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
                            return delim < 0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
    } // for now eat exceptions
    return "";
}
 
Example 17
Project: shabdiz   File: NetworkUtil.java   View Source Code Vote up 5 votes
/**
 * Returns the first non-loopback IPv4 address (Inet4Address) that can be found for an interface on the local host.
 * This method should be used in place of InetAddress.getLocalHost(), which may return an Inet6Address object
 * corresponding to the IPv6 address of a local interface. The bind operation is not supported by this
 * address family.
 *
 * @return the first IPv4 address found
 * @throws UnknownHostException if no IPv4 address can be found
 */
public static InetAddress getLocalIPv4Address() throws UnknownHostException {

    final InetAddress default_local_address = InetAddress.getLocalHost();

    // Return the default local address if it's an IPv4 address and isn't the loopback address. This will work in most cases.
    if (default_local_address instanceof Inet4Address && !default_local_address.isLoopbackAddress()) {
        return default_local_address;
    }

    // Otherwise, look for an IPv4 address among the other interfaces.
    InetAddress loopback_address = null;

    try {
        final Enumeration<NetworkInterface> interfaces_enumeration = NetworkInterface.getNetworkInterfaces();

        if (interfaces_enumeration != null) {
            for (final NetworkInterface network_interface : Collections.list(interfaces_enumeration)) {
                for (final InetAddress address : Collections.list(network_interface.getInetAddresses())) {
                    if (address instanceof Inet4Address) {
                        // Found an IPv4 address. Return it if it's not loopback, otherwise remember it.
                        if (!address.isLoopbackAddress()) {
                            return address;
                        }
                        loopback_address = address;
                    }
                }
            }
        }

        // Haven't found any non-loopback IPv4 address, so return loopback if available.
        if (loopback_address != null) {
            return loopback_address;
        }
    } catch (final SocketException e) {
        LOGGER.trace("ignoring error", e);
    }

    throw new UnknownHostException("local host has no interface with an IPv4 address");
}
 
Example 18
Project: incubator-netbeans   File: ETableColumnModel.java   View Source Code Vote up 5 votes
/** Get all columns, including hidden ones. */
List<TableColumn> getAllColumns() {
    List<TableColumn> columns = Collections.list(getColumns());
    int n = hiddenColumns.size();
    for (int i = 0; i < n; i++) {
        int index = hiddenColumnsPosition.get(i);
        index = Math.min(index, columns.size());
        columns.add(index, hiddenColumns.get(i));
    }
    return columns;
}
 
Example 19
Project: openjdk-jdk10   File: TrustAnchors.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {
    if (initSecmod() == false) {
        return;
    }

    // our secmod.db file says nssckbi.*so*, so NSS does not find the
    // *DLL* on Windows nor the *DYLIB* on Mac OSX.
    String osName = System.getProperty("os.name").toLowerCase();
    if (osName.startsWith("win") || osName.startsWith("mac")) {
        System.out.println("Test currently does not work on " + osName +
            ", skipping");
        return;
    }

    String configName = BASE + SEP + "nsstrust.cfg";
    Provider p = getSunPKCS11(configName);

    System.out.println(p);
    Security.addProvider(p);

    if (args.length > 1 && "sm".equals(args[0])) {
        System.setProperty("java.security.policy",
                BASE + File.separator + args[1]);
        System.setSecurityManager(new SecurityManager());
    }

    KeyStore ks = KeyStore.getInstance("PKCS11", p);
    ks.load(null, null);
    Collection<String> aliases = new TreeSet<>(Collections.list(ks.aliases()));
    System.out.println("entries: " + aliases.size());
    System.out.println(aliases);

    for (String alias : aliases) {
        if (ks.isCertificateEntry(alias) == false) {
            throw new Exception("not trusted: " + alias);
        }
        X509Certificate cert = (X509Certificate)ks.getCertificate(alias);
        // verify self-signed certs
        if (cert.getSubjectX500Principal().equals(cert.getIssuerX500Principal())) {
        System.out.print(".");
            cert.verify(cert.getPublicKey());
        } else {
            System.out.print("-");
        }
    }

    System.out.println();
    System.out.println("OK");
}
 
Example 20
Project: jdk8u-jdk   File: ResourceCheckTest.java   View Source Code Vote up 4 votes
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);
    }
}