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:org.opt4j.config.ModuleAutoFinder.java

/**
 * Retrieves all Classes from a {@link ZipFile} (Jar archive).
 * /*from ww w.java  2s . c  om*/
 * @param zipFile
 *            the Jar archive
 * @return the list of all classes
 */
protected List<Class<?>> getAllClasses(ZipFile zipFile) {
    invokeOut(zipFile.toString());
    List<Class<?>> classes = new ArrayList<Class<?>>();

    List<? extends ZipEntry> entries = Collections.list(zipFile.entries());
    for (int i = 0; i < entries.size(); i++) {

        ZipEntry entry = entries.get(i);

        String s = entry.getName();

        if (s.endsWith(".class")) {

            s = s.replace("/", ".");
            s = s.substring(0, s.length() - 6);

            try {
                Class<?> clazz = classLoader.loadClass(s);
                classes.add(clazz);
                invokeOut("Check: " + clazz.getName());
            } catch (ClassNotFoundException e) {
            } catch (NoClassDefFoundError e) {
            } catch (UnsupportedClassVersionError e) {
                System.err.println(s + " not supported: bad version number");
                invokeErr(s + " not supported");
            }

        }
    }

    return classes;
}

From source file:org.rhq.plugins.database.ComponentTest.java

/**
 * Initializes all plugins defined in the system; using auto-discovery where possible.
 * This is run once per test class./*  w w  w .j a va  2s.  c  o m*/
 */
@BeforeClass
protected void before() throws Exception {
    if (processScan) {
        processInfo = getProcessInfos();
        if (processInfo == null)
            processInfo = Collections.emptyList();
        log.debug("Process Info " + processInfo);
        for (ProcessInfo i : processInfo) {
            log.debug(i.getBaseName() + " " + Arrays.toString(i.getCommandLine()));
        }
    }
    Enumeration<URL> e = getClass().getClassLoader().getResources("META-INF/rhq-plugin.xml");
    List<URL> l = Collections.list(e);
    Collections.sort(l, new Comparator<URL>() {
        @Override
        public int compare(URL u1, URL u2) {
            return u2.toString().compareTo(u1.toString());
        }
    });
    for (URL url : l) {
        log.debug("parse " + url);
        InputStream is = url.openStream();
        PluginDescriptor pd = AgentPluginDescriptorUtil.parsePluginDescriptor(is);
        processPluginDescriptor(pd);
        log.debug("pmm names " + pmm.getPluginNames());
        buildDesc(pd.getServers());
        buildDesc(pd.getServices());
        is.close();
    }
}

From source file:com.zz.globalsession.GlobalHttpSession.java

@Override
public String[] getValueNames() {
    Enumeration<String> names = (Enumeration<String>) getAttributeNames();
    return Collections.list(names).toArray(new String[] {});
}

From source file:org.basdroid.common.NetworkUtils.java

/**
 * Returns MAC address of the given interface name.
 * @param interfaceName eth0, wlan0 or NULL=use first interface
 * @return  mac address or empty string//from ww w  .  j av  a 2s .c  o m
 */
public static String getMACAddress(String interfaceName) {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            if (interfaceName != null) {
                Log.d(TAG, "intf.getName() = " + intf.getName());
                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 "";
}

From source file:org.gluu.oxtrust.ldap.cache.service.CacheRefreshTimer.java

private boolean isStartCacheRefresh(CacheRefreshConfiguration cacheRefreshConfiguration,
        GluuAppliance currentAppliance) {
    if (!GluuBoolean.ENABLED.equals(currentAppliance.getVdsCacheRefreshEnabled())) {
        return false;
    }/* w ww.  j  a v a 2s  .  c om*/

    long poolingInterval = StringHelper.toInteger(currentAppliance.getVdsCacheRefreshPollingInterval()) * 60
            * 1000;
    if (poolingInterval < 0) {
        return false;
    }

    String cacheRefreshServerIpAddress = currentAppliance.getCacheRefreshServerIpAddress();
    if (StringHelper.isEmpty(cacheRefreshServerIpAddress)) {
        log.debug("There is no master Cache Refresh server");
        return false;
    }

    // Compare server IP address with cacheRefreshServerIp
    boolean cacheRefreshServer = false;
    try {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface networkInterface : Collections.list(nets)) {
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                if (StringHelper.equals(cacheRefreshServerIpAddress, inetAddress.getHostAddress())) {
                    cacheRefreshServer = true;
                    break;
                }
            }

            if (cacheRefreshServer) {
                break;
            }
        }
    } catch (SocketException ex) {
        log.error("Failed to enumerate server IP addresses", ex);
    }

    if (!cacheRefreshServer) {
        log.debug("This server isn't master Cache Refresh server");
        return false;
    }

    // Check if cache refresh specific configuration was loaded
    if (cacheRefreshConfiguration == null) {
        log.info(
                "Failed to start cache refresh. Can't loading configuration from oxTrustCacheRefresh.properties");
        return false;
    }

    long timeDiffrence = System.currentTimeMillis() - this.lastFinishedTime;

    return timeDiffrence >= poolingInterval;
}

From source file:psiprobe.tools.ApplicationUtils.java

/**
 * Gets the application session.//from ww  w  .j a v  a  2  s .  c o  m
 *
 * @param session the session
 * @param calcSize the calc size
 * @param addAttributes the add attributes
 * @return the application session
 */
public static ApplicationSession getApplicationSession(Session session, boolean calcSize,
        boolean addAttributes) {

    ApplicationSession sbean = null;
    if (session != null && session.isValid()) {
        sbean = new ApplicationSession();

        sbean.setId(session.getId());
        sbean.setCreationTime(new Date(session.getCreationTime()));
        sbean.setLastAccessTime(new Date(session.getLastAccessedTime()));
        sbean.setMaxIdleTime(session.getMaxInactiveInterval() * 1000);
        sbean.setManagerType(session.getManager().getClass().getName());
        // sbean.setInfo(session.getInfo());
        // TODO:fixmee

        boolean sessionSerializable = true;
        int attributeCount = 0;
        long size = 0;

        HttpSession httpSession = session.getSession();
        Set<Object> processedObjects = new HashSet<>(1000);

        // Exclude references back to the session itself
        processedObjects.add(httpSession);
        try {
            for (String name : Collections.list(httpSession.getAttributeNames())) {
                Object obj = httpSession.getAttribute(name);
                sessionSerializable = sessionSerializable && obj instanceof Serializable;

                long objSize = 0;
                if (calcSize) {
                    try {
                        objSize += Instruments.sizeOf(name, processedObjects);
                        objSize += Instruments.sizeOf(obj, processedObjects);
                    } catch (Exception ex) {
                        logger.error("Cannot estimate size of attribute '{}'", name, ex);
                    }
                }

                if (addAttributes) {
                    Attribute saBean = new Attribute();
                    saBean.setName(name);
                    saBean.setType(ClassUtils.getQualifiedName(obj.getClass()));
                    saBean.setValue(obj);
                    saBean.setSize(objSize);
                    saBean.setSerializable(obj instanceof Serializable);
                    sbean.addAttribute(saBean);
                }
                attributeCount++;
                size += objSize;
            }
            String lastAccessedIp = (String) httpSession.getAttribute(ApplicationSession.LAST_ACCESSED_BY_IP);
            if (lastAccessedIp != null) {
                sbean.setLastAccessedIp(lastAccessedIp);
            }
            try {
                sbean.setLastAccessedIpLocale(
                        InetAddressLocator.getLocale(InetAddress.getByName(lastAccessedIp).getAddress()));
            } catch (Exception e) {
                logger.error("Cannot determine Locale of {}", lastAccessedIp);
                logger.trace("", e);
            }

        } catch (IllegalStateException e) {
            logger.info("Session appears to be invalidated, ignore");
            logger.trace("", e);
        }

        sbean.setObjectCount(attributeCount);
        sbean.setSize(size);
        sbean.setSerializable(sessionSerializable);
    }

    return sbean;
}

From source file:ninja.servlet.NinjaServletContext.java

@Override
public Map<String, List<String>> getHeaders() {
    Map<String, List<String>> headers = new HashMap<>();
    Enumeration<String> names = httpServletRequest.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        headers.put(name, Collections.list(httpServletRequest.getHeaders(name)));
    }/*  w  ww  .j av  a 2  s  .co m*/
    return headers;
}

From source file:com.opensymphony.xwork2.util.finder.UrlSet.java

private List<URL> getUrls(ClassLoaderInterface classLoader, Set<String> protocols) throws IOException {

    if (protocols == null) {
        return getUrls(classLoader);
    }/*  ww  w.ja  v a  2  s . co m*/

    List<URL> list = new ArrayList<URL>();

    //find jars
    ArrayList<URL> urls = Collections.list(classLoader.getResources("META-INF"));

    for (URL url : urls) {
        if (protocols.contains(url.getProtocol())) {
            String externalForm = url.toExternalForm();
            //build a URL pointing to the jar, instead of the META-INF dir
            url = new URL(StringUtils.substringBefore(externalForm, "META-INF"));
            list.add(url);
        } else if (LOG.isDebugEnabled())
            LOG.debug("Ignoring URL [#0] because it is not a valid protocol", url.toExternalForm());

    }
    return list;
}

From source file:alpine.auth.LdapConnectionWrapper.java

/**
 * Performs a search for the specified username. Internally, this method queries on
 * the attribute defined by {@link Config.AlpineKey#LDAP_ATTRIBUTE_NAME}.
 * @param ctx the DirContext to use//  w w  w  .j  a  v a  2s.  co  m
 * @param username the username to query on
 * @return a list of SearchResult objects. If the username is found, the list should typically only contain one result.
 * @throws NamingException if an exception is thrown
 * @since 1.4.0
 */
public List<SearchResult> searchForUsername(DirContext ctx, String username) throws NamingException {
    final String[] attributeFilter = {};
    final SearchControls sc = new SearchControls();
    sc.setReturningAttributes(attributeFilter);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final String searchFor = LdapConnectionWrapper.ATTRIBUTE_NAME + "="
            + LdapStringSanitizer.sanitize(formatPrincipal(username));
    return Collections.list(ctx.search(LdapConnectionWrapper.BASE_DN, searchFor, sc));
}

From source file:com.cyanogenmod.account.util.CMAccountUtils.java

public static String getUniqueDeviceId(Context context) {
    SharedPreferences prefs = context.getSharedPreferences(CMAccount.SETTINGS_PREFERENCES,
            Context.MODE_PRIVATE);
    String udid = prefs.getString(KEY_UDID, null);
    if (udid != null)
        return udid;
    String wifiInterface = SystemProperties.get("wifi.interface");
    if (wifiInterface != null) {
        try {/*w  ww .j a  v a  2 s.  c  o m*/
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface networkInterface : interfaces) {
                if (wifiInterface.equals(networkInterface.getDisplayName())) {
                    byte[] mac = networkInterface.getHardwareAddress();
                    if (mac != null) {
                        StringBuilder buf = new StringBuilder();
                        for (int i = 0; i < mac.length; i++)
                            buf.append(String.format("%02X:", mac[i]));
                        if (buf.length() > 0)
                            buf.deleteCharAt(buf.length() - 1);
                        if (CMAccount.DEBUG)
                            Log.d(TAG, "using wifi mac for id : " + buf.toString());
                        return digest(prefs, context.getPackageName() + buf.toString());
                    }
                }

            }
        } catch (SocketException e) {
            Log.e(TAG, "Unable to get wifi mac address", e);
        }
    }
    //If we fail, just use android id.
    return digest(prefs, context.getPackageName()
            + Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID));
}