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:com.adobe.acs.commons.http.headers.impl.AbstractDispatcherCacheHeaderFilter.java

@SuppressWarnings("unchecked")
protected boolean accepts(final HttpServletRequest request) {

    Enumeration<String> agentsEnum = request.getHeaders(SERVER_AGENT_NAME);
    List<String> serverAgents = agentsEnum != null ? Collections.list(agentsEnum)
            : Collections.<String>emptyList();

    // Only inject when:
    // - GET request
    // - No Params
    // - From Dispatcher
    if (StringUtils.equalsIgnoreCase("get", request.getMethod()) && request.getParameterMap().isEmpty()
            && serverAgents.contains(DISPATCHER_AGENT_HEADER_VALUE)) {

        return true;
    }/*from w w w .j a  va 2s  . c om*/
    return false;
}

From source file:org.dataconservancy.dcs.access.http.QueryServlet.java

@SuppressWarnings("unchecked")
private void search(HttpServletRequest req, HttpServletResponse resp, OutputStream os) throws IOException {

    String query = req.getParameter("q");

    if (query == null) {
        query = ServletUtil.getResource(req);
    }/*from   w ww . ja  va 2 s .com*/

    if (query == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No query specified");
        return;
    }

    int offset = 0;
    int max = DEFAULT_MAX_MATCHES;

    if (req.getParameter("offset") != null) {
        try {
            offset = Integer.parseInt(req.getParameter("offset"));
        } catch (NumberFormatException e) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad offset param");
            return;
        }
    }

    if (req.getParameter("max") != null) {
        try {
            max = Integer.parseInt(req.getParameter("max"));
        } catch (NumberFormatException e) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad max param");
            return;
        }
    }

    if (offset < 0) {
        offset = 0;
    }

    if (max < 0) {
        max = DEFAULT_MAX_MATCHES;
    }

    if (max > MAX_MATCHES_UPPER_BOUND) {
        max = MAX_MATCHES_UPPER_BOUND;
    }

    ResultFormat fmt = ResultFormat.find(req);

    if (fmt == null) {
        resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Unknown response format requested");
        return;
    }

    resp.setContentType(fmt.mimeType());

    List<String> params = new ArrayList<String>();

    for (Object o : Collections.list(req.getParameterNames())) {
        String name = (String) o;

        if (name.startsWith("_")) {
            params.add(name.substring(1));
            params.add(req.getParameter(name));
        }
    }

    QueryResult<DcsEntity> result;

    try {
        result = config.dcpQueryService().query(query, offset, max, params.toArray(new String[] {}));
    } catch (QueryServiceException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Error running query: " + e.getMessage());
        return;
    }

    resp.setHeader("X-TOTAL-MATCHES", "" + result.getTotal());

    if (os == null) {
        return;
    }

    for (QueryMatch<DcsEntity> match : result.getMatches()) {
        DcsEntity entity = match.getObject();

        if (entity instanceof DcsFile) {
            DcsFile file = (DcsFile) entity;

            file.setSource(config.publicDatastreamUrl() + ServletUtil.encodeURLPath(file.getId()));
        }
    }

    if (fmt == ResultFormat.JSON || fmt == ResultFormat.JAVASCRIPT) {
        String jsoncallback = req.getParameter("callback");

        if (jsoncallback != null) {
            os.write(jsoncallback.getBytes("UTF-8"));
            os.write('(');
        }

        jsonbuilder.toXML(result, os);

        if (jsoncallback != null) {
            os.write(')');
        }
    } else if (fmt == ResultFormat.DCP) {
        ResearchObject dcp = new ResearchObject();

        for (QueryMatch<DcsEntity> match : result.getMatches()) {
            dcp = new SeadUtil().add(dcp, match.getObject());
        }

        dcpbuilder.buildSip(dcp, os);
    }
}

From source file:net.pocketmine.server.HomeActivity.java

public static String getIPAddress(boolean useIPv4) {
    try {/*from   w  w  w.  j av  a 2 s. c o  m*/
        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(Locale.US);
                    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) {
    }
    return ha.getResources().getString(R.string.unknown);
}

From source file:org.apache.servicecomb.foundation.vertx.http.TestStandardHttpServletRequestEx.java

@Test
public void parameterMap_merge() throws IOException {
    Map<String, String[]> inherited = new HashMap<>();
    String[] v1 = new String[] { "v1-1", "v1-2" };
    inherited.put("p1", v1);

    Buffer buffer = Buffer.buffer("p1=v1-3;p2=v2");
    BufferInputStream inputStream = new BufferInputStream(buffer.getByteBuf());
    new Expectations() {
        {/*from   www  . ja v  a  2  s  . c om*/
            request.getParameterMap();
            result = inherited;
            request.getMethod();
            result = HttpMethod.PUT;
            request.getContentType();
            result = MediaType.APPLICATION_FORM_URLENCODED.toUpperCase(Locale.US) + ";abc";
            request.getInputStream();
            result = inputStream;
        }
    };

    Assert.assertThat(Collections.list(requestEx.getParameterNames()), Matchers.contains("p1", "p2"));
    Assert.assertThat(requestEx.getParameterValues("p1"), Matchers.arrayContaining("v1-1", "v1-2", "v1-3"));
    Assert.assertEquals("v1-1", requestEx.getParameter("p1"));
}

From source file:io.github.zlika.reproducible.ZipStripper.java

private List<String> sortEntriesByName(Enumeration<ZipArchiveEntry> entries) {
    return Collections.list(entries).stream().map(e -> e.getName()).sorted().collect(Collectors.toList());
}

From source file:org.apache.pdfbox.util.PDFStreamEngine.java

/**
 * Constructor with engine properties.  The property keys are all
 * PDF operators, the values are class names used to execute those
 * operators. An empty value means that the operator will be silently
 * ignored.//from   www .j  a  v a 2 s . c  o m
 *
 * @param properties The engine properties.
 *
 * @throws IOException If there is an error setting the engine properties.
 */
public PDFStreamEngine(Properties properties) throws IOException {
    if (properties == null) {
        throw new NullPointerException("properties cannot be null");
    }
    Enumeration<?> names = properties.propertyNames();
    for (Object name : Collections.list(names)) {
        String operator = name.toString();
        String processorClassName = properties.getProperty(operator);
        if ("".equals(processorClassName)) {
            unsupportedOperators.add(operator);
        } else {
            try {
                Class<?> klass = Class.forName(processorClassName);
                OperatorProcessor processor = (OperatorProcessor) klass.newInstance();
                registerOperatorProcessor(operator, processor);
            } catch (Exception e) {
                throw new WrappedIOException(
                        "OperatorProcessor class " + processorClassName + " could not be instantiated", e);
            }
        }
    }
    validCharCnt = 0;
    totalCharCnt = 0;
}

From source file:org.dkpro.tc.ml.weka.util.WekaUtils.java

/**
 * Adapts the test data class labels to the training data. Class labels from the test data
 * unseen in the training data will be deleted from the test data. Class labels from the
 * training data unseen in the test data will be added to the test data. If training and test
 * class labels are equal, nothing will be done.
 *///from w w w. j a va2 s  . c  o m
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Instances makeOutcomeClassesCompatible(Instances trainData, Instances testData,
        boolean multilabel) throws Exception {
    // new (compatible) test data
    Instances compTestData = null;

    // ================ SINGLE LABEL BRANCH ======================
    if (!multilabel) {
        // retrieve class labels
        Enumeration trainOutcomeValues = trainData.classAttribute().enumerateValues();
        Enumeration testOutcomeValues = testData.classAttribute().enumerateValues();
        ArrayList trainLabels = Collections.list(trainOutcomeValues);
        ArrayList testLabels = Collections.list(testOutcomeValues);

        // add new outcome class attribute to test data
        Add addFilter = new Add();
        addFilter.setNominalLabels(StringUtils.join(trainLabels, ','));
        addFilter.setAttributeName(Constants.CLASS_ATTRIBUTE_NAME + COMPATIBLE_OUTCOME_CLASS);
        addFilter.setInputFormat(testData);
        testData = Filter.useFilter(testData, addFilter);

        // fill NEW test data with values from old test data plus the new class attribute
        compTestData = new Instances(testData, testData.numInstances());
        for (int i = 0; i < testData.numInstances(); i++) {
            weka.core.Instance instance = testData.instance(i);
            String label = (String) testLabels.get((int) instance.value(testData.classAttribute()));
            if (trainLabels.indexOf(label) != -1) {
                instance.setValue(testData.attribute(Constants.CLASS_ATTRIBUTE_NAME + COMPATIBLE_OUTCOME_CLASS),
                        label);
            } else {
                instance.setMissing(testData.classIndex());
            }
            compTestData.add(instance);
        }

        // remove old class attribute
        Remove remove = new Remove();
        remove.setAttributeIndices(
                Integer.toString(compTestData.attribute(Constants.CLASS_ATTRIBUTE_NAME).index() + 1));
        remove.setInvertSelection(false);
        remove.setInputFormat(compTestData);
        compTestData = Filter.useFilter(compTestData, remove);

        // set new class attribute
        compTestData
                .setClass(compTestData.attribute(Constants.CLASS_ATTRIBUTE_NAME + COMPATIBLE_OUTCOME_CLASS));
    }
    // ================ MULTI LABEL BRANCH ======================
    else {

        int numTrainLabels = trainData.classIndex();
        int numTestLabels = testData.classIndex();

        ArrayList<String> trainLabels = getLabels(trainData);
        // ArrayList<String> testLabels = getLabels(testData);

        // add new outcome class attributes to test data

        Add filter = new Add();
        for (int i = 0; i < numTrainLabels; i++) {
            // numTestLabels +i (because index starts from 0)
            filter.setAttributeIndex(new Integer(numTestLabels + i + 1).toString());
            filter.setNominalLabels("0,1");
            filter.setAttributeName(trainData.attribute(i).name() + COMPATIBLE_OUTCOME_CLASS);
            filter.setInputFormat(testData);
            testData = Filter.useFilter(testData, filter);
        }

        // fill NEW test data with values from old test data plus the new class attributes
        compTestData = new Instances(testData, testData.numInstances());
        for (int i = 0; i < testData.numInstances(); i++) {
            weka.core.Instance instance = testData.instance(i);
            // fullfill with 0.
            for (int j = 0; j < numTrainLabels; j++) {
                instance.setValue(j + numTestLabels, 0.);
            }
            // fill the real values:
            for (int j = 0; j < numTestLabels; j++) {
                // part of train data: forget labels which are not part of the train data
                if (trainLabels.indexOf(instance.attribute(j).name()) != -1) {
                    // class label found in test data
                    int index = trainLabels.indexOf(instance.attribute(j).name());
                    instance.setValue(index + numTestLabels, instance.value(j));
                }
            }
            compTestData.add(instance);
        }

        // remove old class attributes
        for (int i = 0; i < numTestLabels; i++) {
            Remove remove = new Remove();
            remove.setAttributeIndices("1");
            remove.setInvertSelection(false);
            remove.setInputFormat(compTestData);
            compTestData = Filter.useFilter(compTestData, remove);
        }

        // adapt header and set new class label
        String relationTag = compTestData.relationName();
        compTestData.setRelationName(
                relationTag.substring(0, relationTag.indexOf("-C") + 2) + " " + numTrainLabels + " ");
        compTestData.setClassIndex(numTrainLabels);
    }
    return compTestData;
}

From source file:org.bessle.neo4j.proxy.HttpRequestLoggingFilter.java

protected Map<String, Object> getTrace(HttpServletRequestWrapper wrappedRequest) {

    Map<String, Object> headers = new LinkedHashMap<String, Object>();
    Enumeration<String> names = wrappedRequest.getHeaderNames();

    while (names.hasMoreElements()) {
        String name = names.nextElement();
        List<String> values = Collections.list(wrappedRequest.getHeaders(name));
        Object value = values;//from www .  jav  a2  s .  co m
        if (values.size() == 1) {
            value = values.get(0);
        } else if (values.isEmpty()) {
            value = "";
        }
        headers.put(name, value);

    }
    Map<String, Object> trace = new LinkedHashMap<String, Object>();
    Map<String, Object> allHeaders = new LinkedHashMap<String, Object>();
    allHeaders.put("request", headers);
    trace.put("method", wrappedRequest.getMethod());
    trace.put("path", wrappedRequest.getRequestURI());
    trace.put("headers", allHeaders);
    Throwable exception = (Throwable) wrappedRequest.getAttribute("javax.servlet.error.exception");
    if (exception != null && this.errorAttributes != null) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(wrappedRequest);
        Map<String, Object> error = this.errorAttributes.getErrorAttributes(requestAttributes, true);
        trace.put("error", error);
    }
    String body = "unknown";
    try {
        //body = IOUtils.toString(wrappedRequest.getInputStream(), "UTF-8");
        trace.put("body", body);
        InputStream wrappedInputStream = IOUtils.toInputStream(body, "UTF-8");
        //wrappedRequest.
    } catch (IOException ioe) {
        trace.put("body", "untraceable");
    }
    return trace;
}

From source file:org.springframework.osgi.extender.internal.support.NamespaceManager.java

/**
 * Registers the namespace plugin handler if this bundle defines handler mapping or schema mapping resources.
 * //from   w  ww  .  ja v  a 2  s.co m
 * <p/> This method considers only the bundle space and not the class space.
 * 
 * @param bundle target bundle
 * @param isLazyBundle indicator if the bundle analyzed is lazily activated
 */
public void maybeAddNamespaceHandlerFor(Bundle bundle, boolean isLazyBundle) {
    // Ignore system bundle
    if (OsgiBundleUtils.isSystemBundle(bundle)) {
        return;
    }

    // Ignore non-wired Spring DM bundles
    if ("org.springframework.osgi.core".equals(bundle.getSymbolicName())
            && !bundle.equals(BundleUtils.getDMCoreBundle(context))) {
        return;
    }

    boolean debug = log.isDebugEnabled();
    boolean trace = log.isTraceEnabled();
    // FIXME: Blueprint uber bundle temporary hack
    // since embedded libraries are not discovered by findEntries and inlining them doesn't work
    // (due to resource classes such as namespace handler definitions)
    // we use getResource

    boolean hasHandlers = false, hasSchemas = false;

    if (trace) {
        log.trace("Inspecting bundle " + bundle + " for Spring namespaces");
    }
    // extender/RFC 124 bundle
    if (context.getBundle().equals(bundle)) {

        try {
            Enumeration<?> handlers = bundle.getResources(META_INF + SPRING_HANDLERS);
            Enumeration<?> schemas = bundle.getResources(META_INF + SPRING_SCHEMAS);

            hasHandlers = handlers != null;
            hasSchemas = schemas != null;

            if (hasHandlers && debug) {
                log.debug("Found namespace handlers: " + Collections.list(schemas));
            }
        } catch (IOException ioe) {
            log.warn("Cannot discover own namespaces", ioe);
        }
    } else {
        hasHandlers = bundle.findEntries(META_INF, SPRING_HANDLERS, false) != null;
        hasSchemas = bundle.findEntries(META_INF, SPRING_SCHEMAS, false) != null;
    }

    // if the bundle defines handlers
    if (hasHandlers) {

        if (trace)
            log.trace("Bundle " + bundle + " provides Spring namespace handlers...");

        if (isLazyBundle) {
            this.namespacePlugins.addPlugin(bundle, isLazyBundle, true);
        } else {
            // check type compatibility between the bundle's and spring-extender's spring version
            if (hasCompatibleNamespaceType(bundle)) {
                this.namespacePlugins.addPlugin(bundle, isLazyBundle, false);
            } else {
                if (debug)
                    log.debug("Bundle [" + OsgiStringUtils.nullSafeNameAndSymName(bundle)
                            + "] declares namespace handlers but is not compatible with extender ["
                            + extenderInfo + "]; ignoring...");
            }
        }
    } else {
        // bundle declares only schemas, add it though the handlers might not be compatible...
        if (hasSchemas) {
            this.namespacePlugins.addPlugin(bundle, isLazyBundle, false);
            if (trace)
                log.trace("Bundle " + bundle + " provides Spring schemas...");
        }
    }
}

From source file:com.vinexs.tool.NetworkManager.java

public static String getIPAddress(boolean useIPv4) {
    try {// ww  w . j a v  a 2s  . c om
        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 = InetAddressUtilsHC4.isIPv4Address(sAddr);
                    if (useIPv4) {
                        if (isIPv4) {
                            return sAddr;
                        }
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                            return delim < 0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}