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:eu.musesproject.client.contextmonitoring.sensors.DeviceProtectionSensor.java

public String getIPAddress(boolean useIPv4) {
    try {//from   w  w w . j a  v  a 2s .com
        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('%');
                            return delim < 0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
    } // for now eat exceptions
    return "";
}

From source file:org.apache.qpid.server.management.plugin.HttpManagementUtil.java

public static Subject tryToAuthenticate(HttpServletRequest request,
        HttpManagementConfiguration managementConfig) {
    Subject subject = null;//w w  w.j  a  v  a  2  s.c  o  m
    SocketAddress localAddress = getSocketAddress(request);
    final AuthenticationProvider authenticationProvider = managementConfig
            .getAuthenticationProvider(localAddress);
    SubjectCreator subjectCreator = authenticationProvider.getSubjectCreator(request.isSecure());
    String remoteUser = request.getRemoteUser();

    if (remoteUser != null || authenticationProvider instanceof AnonymousAuthenticationManager) {
        subject = authenticateUser(subjectCreator, remoteUser, null);
    } else if (authenticationProvider instanceof ExternalAuthenticationManager && Collections
            .list(request.getAttributeNames()).contains("javax.servlet.request.X509Certificate")) {
        Principal principal = null;
        X509Certificate[] certificates = (X509Certificate[]) request
                .getAttribute("javax.servlet.request.X509Certificate");
        if (certificates != null && certificates.length != 0) {
            principal = certificates[0].getSubjectX500Principal();

            if (!Boolean.valueOf(String.valueOf(authenticationProvider
                    .getAttribute(ExternalAuthenticationManager.ATTRIBUTE_USE_FULL_DN)))) {
                String username;
                String dn = ((X500Principal) principal).getName(X500Principal.RFC2253);

                username = SSLUtil.getIdFromSubjectDN(dn);
                principal = new UsernamePrincipal(username);
            }

            subject = subjectCreator.createSubjectWithGroups(new AuthenticatedPrincipal(principal));
        }
    } else {
        String header = request.getHeader("Authorization");
        if (header != null) {
            String[] tokens = header.split("\\s");
            if (tokens.length >= 2 && "BASIC".equalsIgnoreCase(tokens[0])) {
                boolean isBasicAuthSupported = false;
                if (request.isSecure()) {
                    isBasicAuthSupported = managementConfig.isHttpsBasicAuthenticationEnabled();
                } else {
                    isBasicAuthSupported = managementConfig.isHttpBasicAuthenticationEnabled();
                }
                if (isBasicAuthSupported) {
                    String base64UsernameAndPassword = tokens[1];
                    String[] credentials = (new String(
                            Base64.decodeBase64(base64UsernameAndPassword.getBytes()))).split(":", 2);
                    if (credentials.length == 2) {
                        subject = authenticateUser(subjectCreator, credentials[0], credentials[1]);
                    }
                }
            }
        }
    }
    return subject;
}

From source file:org.niord.proxy.web.ETagServletFilter.java

/**
 * Inspired by javax.ws.rs.core.Request.evaluatePreconditions().
 * Evaluate request preconditions based on the passed in value.
 *
 * @param etag an ETag for the current state of the resource
 * @return if the preconditions are met.
 *///from  w  w w.  ja  v a2  s  . c  om
private boolean evaluatePreconditions(EntityTag etag, HttpServletRequest request,
        HttpServletResponse response) {
    if (etag == null) {
        return false;
    }

    response.setHeader(HEADER_ETAG, etag.toString());

    boolean match = Collections.list(request.getHeaders(HEADER_IF_NONE_MATCH)).stream().map(this::trimEtagValue) // Strip any "-gzip" suffix added by Apache modules
            .anyMatch(val -> val.equals(etag.toString()));

    if (match) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return true;
    }

    // No matching etag headers
    return false;
}

From source file:org.apache.openejb.cdi.OptimizedLoaderService.java

private boolean isFiltered(final Collection<Extension> extensions, final Extension next) {
    final ClassLoader containerLoader = ParentClassLoaderFinder.Helper.get();
    final Class<? extends Extension> extClass = next.getClass();
    if (extClass.getClassLoader() != containerLoader) {
        return false;
    }/*from w ww.  j  a va 2 s .c  o m*/

    final String name = extClass.getName();
    switch (name) {
    case "org.apache.bval.cdi.BValExtension":
        for (final Extension e : extensions) {
            final String en = e.getClass().getName();

            // org.hibernate.validator.internal.cdi.ValidationExtension but allowing few evolutions of packages
            if (en.startsWith("org.hibernate.validator.") && en.endsWith("ValidationExtension")) {
                log.info("Skipping BVal CDI integration cause hibernate was found in the application");
                return true;
            }
        }
        break;
    case "org.apache.batchee.container.cdi.BatchCDIInjectionExtension": // see org.apache.openejb.batchee.BatchEEServiceManager
        return "true".equals(SystemInstance.get().getProperty("tomee.batchee.cdi.use-extension", "false"));
    case "org.apache.commons.jcs.jcache.cdi.MakeJCacheCDIInterceptorFriendly":
        final String spi = "META-INF/services/javax.cache.spi.CachingProvider";
        try {
            final Enumeration<URL> appResources = Thread.currentThread().getContextClassLoader()
                    .getResources(spi);
            if (appResources != null && appResources.hasMoreElements()) {
                final Collection<URL> containerResources = Collections.list(containerLoader.getResources(spi));
                do {
                    if (!containerResources.contains(appResources.nextElement())) {
                        log.info(
                                "Skipping JCS CDI integration cause another provide was found in the application");
                        return true;
                    }
                } while (appResources.hasMoreElements());
            }
        } catch (final Exception e) {
            // no-op
        }
        break;
    default:
    }
    return false;
}

From source file:com.xtructure.xutil.AbstractRunTests.java

/**
 * Processes the given jar resource.//from   w ww  . ja  v  a  2s .  c om
 * 
 * @param packageName
 *            the name of the package currently being processed
 * 
 * @param resourceUrl
 *            the URL of the jar resource to process
 */
private final void processJarResource(final String packageName, final URL resourceUrl) {
    try {
        for (final JarEntry jarEntry : Collections
                .list(((JarURLConnection) resourceUrl.openConnection()).getJarFile().entries())) {
            final String className = stripSuffix(makeClassName(jarEntry.getName()));
            if (isTestClassName(packageName, className)) {
                addClass(className);
            }
        }
    } catch (IOException ioEx) {
        throw new RuntimeException("couldn't get entries from jar '" + resourceUrl + "': " + ioEx.getMessage(),
                ioEx);
    }
}

From source file:org.paxle.data.impl.Activator.java

/**
 * We may have multiple datalayer-fragment-bundles installed. We try to find all available
 * config files here//from  w  ww. java  2 s.  c  om
 */
@SuppressWarnings("unchecked")
private HashMap<String, URL> getAvailableConfigFiles(BundleContext context) {
    HashMap<String, URL> availableConfigs = new HashMap<String, URL>();

    this.logger.info("Trying to find db config files ...");
    Enumeration<URL> configFileEnum = context.getBundle().findEntries("/resources/hibernate/", "*.cfg.xml",
            true);
    if (configFileEnum != null) {
        ArrayList<URL> configFileURLs = Collections.list(configFileEnum);
        this.logger.info(String.format("%d config-file(s) found.", Integer.valueOf(configFileURLs.size())));

        for (URL configFileURL : configFileURLs) {
            String file = configFileURL.getFile();
            int idx = file.lastIndexOf("/");
            if (idx != -1)
                file = file.substring(idx + 1);
            idx = file.indexOf(".");
            if (idx != -1)
                file = file.substring(0, idx);

            availableConfigs.put(file, configFileURL);
        }
    }

    return availableConfigs;
}

From source file:org.openhab.binding.ekozefir.internal.EkozefirBinding.java

/**
 * @{inheritDoc}/*from www.  java2 s .co m*/
 */
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    Objects.requireNonNull(config);
    for (String configKey : Collections.list(config.keys())) {
        parseConfig(clearAndCheckConfig(configKey, (String) config.get(configKey)));
    }
    setProperlyConfigured(true);
}

From source file:org.ireland.jnetty.loader.WebAppClassLoader.java

private List<URL> toList(Enumeration<URL> e) {
    if (e == null)
        return new ArrayList<URL>();
    return Collections.list(e);
}

From source file:hudson.logging.LogRecorder.java

@Restricted(NoExternalUse.class)
public AutoCompletionCandidates doAutoCompleteLoggerName(@QueryParameter String value) {
    if (value == null) {
        return new AutoCompletionCandidates();
    }/*from www  .jav a2s.  c  o m*/

    // get names of all actual loggers known to Jenkins
    Set<String> candidateNames = new LinkedHashSet<>(
            getAutoCompletionCandidates(Collections.list(LogManager.getLogManager().getLoggerNames())));

    for (String part : value.split("[ ]+")) {
        HashSet<String> partCandidates = new HashSet<>();
        String lowercaseValue = part.toLowerCase(Locale.ENGLISH);
        for (String loggerName : candidateNames) {
            if (loggerName.toLowerCase(Locale.ENGLISH).contains(lowercaseValue)) {
                partCandidates.add(loggerName);
            }
        }
        candidateNames.retainAll(partCandidates);
    }
    AutoCompletionCandidates candidates = new AutoCompletionCandidates();
    candidates.add(candidateNames.toArray(MemoryReductionUtil.EMPTY_STRING_ARRAY));
    return candidates;
}

From source file:edu.ksu.cis.indus.tools.slicer.criteria.specification.SliceCriterionSpec.java

/**
 * Retrieves the criteria represented by this spec relative to the given scene.
 *
 * @param scene relative to which the criteria will be generated.
 *
 * @return the collection of slice criterion.
 *
 * @throws MissingResourceException when the any of the types used in the criterion specification cannot be found.
 * @throws IllegalStateException when the method in the spec does not have a body or the specified statment/expr does not
 *          exists.//  ww  w .  j a va  2s. c  om
 */
public Collection<ISliceCriterion> getCriteria(final Scene scene) {
    trim();

    final SootClass _sc = scene.getSootClass(className);

    if (_sc == null) {
        final String _msg = className + " is not available in the System.";
        LOGGER.error(_msg);
        throw new MissingResourceException("Given class not available in the System.", className, null);
    }

    final List<Type> _parameterTypes = new ArrayList<Type>();

    for (final Iterator<String> _i = parameterTypeNames.iterator(); _i.hasNext();) {
        final String _name = _i.next();
        _parameterTypes.add(Util.getTypeFor(_name, scene));
    }

    final SootMethod _sm = _sc.getMethod(methodName, _parameterTypes, Util.getTypeFor(returnTypeName, scene));
    _sc.setApplicationClass();

    final Body _body = _sm.retrieveActiveBody();

    if (_body == null) {
        final String _msg = returnTypeName + " " + methodName + "(" + parameterTypeNames
                + ") does not have a body.";
        LOGGER.error(_msg);
        throw new IllegalStateException(_msg);
    }

    final List<Stmt> _stmts = Collections.list(Collections.<Stmt>enumeration(_body.getUnits()));

    if (_stmts.size() < stmtIndex + 1) {
        final String _msg = returnTypeName + " " + methodName + "(" + parameterTypeNames + ") has only "
                + _stmts.size() + " statements. [" + stmtIndex + "]";
        LOGGER.error(_msg);
        throw new IllegalStateException(_msg);
    }

    final Collection<ISliceCriterion> _result;

    if (stmtIndex == -1) {
        _result = CRITERIA_FACTORY.getCriteria(_sm);
    } else {
        final Stmt _stmt = _stmts.get(stmtIndex);

        if (exprIndex == -1) {
            _result = CRITERIA_FACTORY.getCriteria(_sm, _stmt, considerEntireStmt, considerExecution);
        } else {
            _result = CRITERIA_FACTORY.getCriteria(_sm, _stmt,
                    (ValueBox) _stmt.getUseAndDefBoxes().get(exprIndex), considerExecution);
        }
    }

    return _result;
}