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:pt.sapo.pai.vip.VipServlet.java

private void processRequest(HttpServletRequest request, HttpServletResponse response,
        Supplier<HttpRequestBase> supplier) throws ServletException, IOException {
    try (OutputStream out = response.getOutputStream(); CloseableHttpClient http = builder.build()) {
        Optional.ofNullable(servers[rand.nextInt(2)]).map(server -> server.split(":"))
                .map(parts -> Tuple.of(parts[0], Integer.valueOf(parts[1]))).ifPresent(server -> {
                    try {
                        HttpRequestBase method = supplier.get();
                        method.setURI(new URI(request.getScheme(), null, server._1, server._2,
                                request.getRequestURI(), request.getQueryString(), null));
                        HttpResponse rsp = http.execute(method);
                        Collections.list(request.getHeaderNames())
                                .forEach(name -> Collections.list(request.getHeaders(name))
                                        .forEach(value -> method.setHeader(name, value)));
                        response.setStatus(rsp.getStatusLine().getStatusCode());
                        response.setContentType(rsp.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
                        IOUtils.copy(rsp.getEntity().getContent(), out);
                    } catch (IOException | URISyntaxException ex) {
                        log.error(null, ex);
                    }//ww  w . j a v a 2 s .c o  m
                });
    }
}

From source file:org.ebayopensource.turmeric.tools.AbstractCodegenTestCase.java

/**
 * Load {@link Properties} from classpath.
 * /*from   w w  w.  j  a  va 2  s.  c  om*/
 * @param resource
 *            the properties resource to load.
 * @return the loaded properties (or empty properties if resource not found)
 * @throws IOException
 *             if unable to read resource
 */
protected Properties loadProperties(String resource) throws IOException {
    Properties props = new Properties();
    Enumeration<URL> enurls = this.getClass().getClassLoader().getResources(resource);
    if (!enurls.hasMoreElements()) {
        return props;
    }
    List<URL> urls = Collections.list(enurls);
    Assert.assertThat("Encountered multiple hits for resource: " + resource, urls.size(), is(1));
    InputStream stream = null;
    try {
        stream = urls.get(0).openStream();
        props.load(stream);
    } finally {
        IOUtils.closeQuietly(stream);
    }
    return props;
}

From source file:org.neo4j.ha.upgrade.Utils.java

public static List<File> unzip(File zipFile, File targetDir) throws IOException {
    List<File> files = new ArrayList<File>();
    ZipFile zip = new ZipFile(zipFile);
    try {//from ww w . j  ava2s  . c o m
        zip = new ZipFile(zipFile);
        for (ZipEntry entry : Collections.list(zip.entries())) {
            File target = new File(targetDir, entry.getName());
            target.getParentFile().mkdirs();
            if (!entry.isDirectory()) {
                InputStream input = zip.getInputStream(entry);
                try {
                    copyInputStreamToFile(input, target);
                    files.add(target);
                } finally {
                    closeQuietly(input);
                }
            }
        }
        return files;
    } finally {
        zip.close();
    }
}

From source file:org.openmrs.module.kenyametadatatools.mflsync.MflSyncFromRemoteSpreadsheetTask.java

/**
 * @see BaseMflSyncTask#doImport()//from   ww w . j  a  v a 2 s  . c  o m
 */
@Override
public void doImport() throws Exception {

    File tmpZip = null;

    try {
        TaskEngine.log("Downloading MFL archive. This may take a few minutes ...");

        tmpZip = File.createTempFile("mfl", ".zip");

        OutputStream out = new BufferedOutputStream(new FileOutputStream(tmpZip));
        OpenmrsUtil.copyFile(spreadsheetUrl.openStream(), out);

        TaskEngine.log("Downloaded archive " + tmpZip.getName());
        TaskEngine.log("Looking for XLS files in archive ...");

        ZipFile zipFile = new ZipFile(tmpZip);
        for (ZipEntry entry : Collections.list(zipFile.entries())) {
            if (entry.getName().toLowerCase().endsWith(".xls")) {
                TaskEngine.log("Importing '" + entry.getName() + "' ...");
                importXls(zipFile.getInputStream(entry));
            }
        }
    } finally {
        if (tmpZip != null) {
            tmpZip.delete();
        }
    }
}

From source file:org.openrepose.powerfilter.intrafilterlogging.RequestLog.java

private Map<String, String> convertRequestHeadersToMap(HttpServletRequest httpServletRequest) {
    Map<String, String> headerMap = new LinkedHashMap<>();
    List<String> headerNames = Collections.list(httpServletRequest.getHeaderNames());

    for (String headerName : headerNames) {
        StringJoiner stringJoiner = new StringJoiner(",");
        Collections.list(httpServletRequest.getHeaders(headerName)).forEach(stringJoiner::add);
        headerMap.put(headerName, stringJoiner.toString());
    }// ww  w. j  av  a 2  s  . c o  m

    return headerMap;
}

From source file:org.ops4j.pax.web.resources.extender.internal.IndexedOsgiResourceLocator.java

@Override
public void register(final Bundle bundle) {
    Collection<URL> urls;
    try {// ww  w. j  a va 2  s  .com
        urls = Collections.list(bundle.findEntries(RESOURCE_ROOT, "*.*", true));
    } catch (IllegalStateException e) {
        logger.error("Error retrieving bundle-resources from bundle '{}'", bundle.getSymbolicName(), e);
        urls = Collections.emptyList();
    }

    urls.forEach(
            url -> index.addResourceToIndex(url.getPath(),
                    new ResourceInfo(url, LocalDateTime
                            .ofInstant(Instant.ofEpochMilli(bundle.getLastModified()), ZoneId.systemDefault()),
                            bundle.getBundleId()),
                    bundle));

    logger.info("Bundle '{}' scanned for resources in '{}': {} entries added to index.",
            new Object[] { bundle.getSymbolicName(), RESOURCE_ROOT, urls.size() });
}

From source file:jenkins.security.plugins.ldap.FromUserRecordLDAPGroupMembershipStrategy.java

@Override
public GrantedAuthority[] getGrantedAuthorities(LdapUserDetails ldapUser) {
    List<GrantedAuthority> result = new ArrayList<GrantedAuthority>();
    Attributes attributes = ldapUser.getAttributes();
    final String attributeName = getAttributeName();
    Attribute attribute = attributes == null ? null : attributes.get(attributeName);
    if (attribute != null) {
        try {/* w ww.ja  v a  2  s .  c  o  m*/
            for (Object value : Collections.list(attribute.getAll())) {
                String groupName = String.valueOf(value);
                try {
                    LdapName dn = new LdapName(groupName);
                    groupName = String.valueOf(dn.getRdn(dn.size() - 1).getValue());
                } catch (InvalidNameException e) {
                    LOGGER.log(Level.FINEST, "Expected a Group DN but found: {0}", groupName);
                }
                result.add(new GrantedAuthorityImpl(groupName));
            }
        } catch (NamingException e) {
            LogRecord lr = new LogRecord(Level.FINE,
                    "Failed to retrieve member of attribute ({0}) from LDAP user details");
            lr.setThrown(e);
            lr.setParameters(new Object[] { attributeName });
            LOGGER.log(lr);
        }

    }
    return result.toArray(new GrantedAuthority[result.size()]);
}

From source file:to.sven.androidrccar.host.communication.impl.SocketConnector.java

/**
 * Returns the first non-local IPv4 address of the device. 
 * @return IPv4 address as String or unknown, if no address is found.
 *///  w  w  w. j  a  v  a  2 s .com
private String getLocalIpAddress() {
    try {
        for (NetworkInterface iface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
            for (InetAddress address : Collections.list(iface.getInetAddresses())) {
                if (!address.isLoopbackAddress() && InetAddressUtils.isIPv4Address(address.getHostAddress())) {
                    return address.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return dc.getContext().getString(android.R.string.unknownName);
}

From source file:de.innovationgate.wgpublisher.expressions.tmlscript.IsolatedJARLoader.java

@Override
public Enumeration<URL> findResources(String s) throws IOException {

    List<URL> urls = new ArrayList<URL>();
    urls.addAll(Collections.list(super.findResources(s)));
    urls.addAll(Collections.list(_fallBackLoader.getResources(s)));
    return new IteratorEnumeration(urls.iterator());

}

From source file:com.temenos.interaction.core.web.RequestContextFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest servletRequest = (HttpServletRequest) request;

    String requestURI = servletRequest.getRequestURI();
    requestURI = StringUtils.removeStart(requestURI,
            servletRequest.getContextPath() + servletRequest.getServletPath());
    String baseURL = StringUtils.removeEnd(servletRequest.getRequestURL().toString(), requestURI);

    Map<String, List<String>> headersMap = new HashMap<>();
    Enumeration<String> headerNames = servletRequest.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            List<String> valuesList = Collections.list(servletRequest.getHeaders(headerName));
            headersMap.put(headerName, valuesList);
        }//from w w w  . j  a va2s  .co  m
    }

    RequestContext ctx;
    Principal userPrincipal = servletRequest.getUserPrincipal();
    if (userPrincipal != null) {
        ctx = new RequestContext(baseURL, servletRequest.getRequestURI(),
                servletRequest.getHeader(RequestContext.HATEOAS_OPTIONS_HEADER), userPrincipal, headersMap);
    } else {
        ctx = new RequestContext(baseURL, servletRequest.getRequestURI(),
                servletRequest.getHeader(RequestContext.HATEOAS_OPTIONS_HEADER), headersMap);
    }

    RequestContext.setRequestContext(ctx);

    try {
        chain.doFilter(request, response);
    } finally {
        RequestContext.clearRequestContext();
    }
}