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:de.tudarmstadt.ukp.dkpro.tc.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.
 *
 * @param trainData//w w w . j  a v a2  s  . c o  m
 *            training data
 * @param testData
 *            test data
 * @param multilabel
 *            whether this is a multi-label classification problem
 * @return the adapted test data
 * @throws Exception
 */
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.apache.hadoop.hdfs.server.datanode.TestDataNodeMetricsLogger.java

@Test
public void testMetricsLoggerIsAsync() throws IOException {
    startDNForTest(true);/* w w  w. ja v a  2s.  c o  m*/
    assertNotNull(dn);
    org.apache.log4j.Logger logger = ((Log4JLogger) DataNode.METRICS_LOG).getLogger();
    @SuppressWarnings("unchecked")
    List<Appender> appenders = Collections.list(logger.getAllAppenders());
    assertTrue(appenders.get(0) instanceof AsyncAppender);
}

From source file:javax.portlet.tck.portlets.AddlRequestTests_SPEC2_11_ActionReq.java

@SuppressWarnings("deprecation")
@Override/*from   w  w  w  .  j a v a2 s  .c  o m*/
public void processAction(ActionRequest portletReq, ActionResponse portletResp)
        throws PortletException, IOException {

    portletResp.setRenderParameters(portletReq.getParameterMap());
    long tid = Thread.currentThread().getId();
    portletReq.setAttribute(THREADID_ATTR, tid);

    StringWriter writer = new StringWriter();

    JSR286SpecTestCaseDetails tcd = new JSR286SpecTestCaseDetails();

    // Create result objects for the tests

    /* TestCase: V2AddlRequestTests_SPEC2_11_ActionReq_contentType1 */
    /* Details: "The getResponseContentType method returns a String */
    /* representing the default content type the portlet container */
    /* assumes for the output" */
    TestResult tr0 = tcd.getTestResultFailed(V2ADDLREQUESTTESTS_SPEC2_11_ACTIONREQ_CONTENTTYPE1);
    if (portletReq.getResponseContentType() != null && !portletReq.getResponseContentType().isEmpty())
        tr0.setTcSuccess(true);
    tr0.writeTo(writer);

    /* TestCase: V2AddlRequestTests_SPEC2_11_ActionReq_contentType2 */
    /* Details: "The getResponseContentTypes method returns an */
    /* Enumeration of String elements representing the acceptable content */
    /* types for the output in order of preference" */
    TestResult tr1 = tcd.getTestResultFailed(V2ADDLREQUESTTESTS_SPEC2_11_ACTIONREQ_CONTENTTYPE2);
    Enumeration<String> contentTypesTr1 = portletReq.getResponseContentTypes();
    if (contentTypesTr1 != null) {
        List<String> list = Collections.list(contentTypesTr1);
        if (list.isEmpty()) {
            tr1.appendTcDetail("Enumeration was empty.");
        } else {
            if (list.get(0).isEmpty()) {
                tr1.appendTcDetail("First content type string is empty.");
            } else {
                tr1.setTcSuccess(true);
            }
        }
    } else {
        tr1.appendTcDetail("Enumeration was null.");
    }
    tr1.writeTo(writer);

    /* TestCase: V2AddlRequestTests_SPEC2_11_ActionReq_contentType3 */
    /* Details: "The first element of the Enumeration returned by the */
    /* getResponseContentTypes method must equal the value returned by */
    /* the getResponseContentType method" */
    TestResult tr2 = tcd.getTestResultFailed(V2ADDLREQUESTTESTS_SPEC2_11_ACTIONREQ_CONTENTTYPE3);
    Enumeration<String> contentTypesTr2 = portletReq.getResponseContentTypes();
    if (contentTypesTr2 != null) {
        List<String> list = Collections.list(contentTypesTr2);
        if (list.isEmpty()) {
            tr2.appendTcDetail("Enumeration was empty.");
        } else {
            if (!list.get(0).equals(portletReq.getResponseContentType())) {
                tr2.appendTcDetail(
                        "First content type string does not equal PortletRequest#getResponseContentType().");
            } else {
                tr2.setTcSuccess(true);
            }
        }
    } else {
        tr2.appendTcDetail("Enumeration was null.");
    }
    tr2.writeTo(writer);

    /* TestCase: V2AddlRequestTests_SPEC2_11_ActionReq_windowId4 */
    /* Details: "The string returned by getWindowID method must be the */
    /* same ID used for scoping portlet-scope session attributes" */
    TestResult tr5 = tcd.getTestResultFailed(V2ADDLREQUESTTESTS_SPEC2_11_ACTIONREQ_WINDOWID4);
    String tr5SessionAttribute = (String) portletReq.getPortletSession()
            .getAttribute("javax.portlet.p." + portletReq.getWindowID() + "?tr5", APPLICATION_SCOPE);
    if (tr5SessionAttribute != null && tr5SessionAttribute.equals(portletReq.getWindowID())) {
        tr5.setTcSuccess(true);
    } else {
        tr5.appendTcDetail("Couldn't find javax.portlet.p." + portletReq.getWindowID() + ".tr5 attribute");
    }
    tr5.writeTo(writer);

    /* TestCase: V2AddlRequestTests_SPEC2_11_ActionReq_contentType6 */
    /* Details: "Within the processAction method, the content type must */
    /* include only the MIME type, not the character set" */
    TestResult tr6 = tcd.getTestResultFailed(V2ADDLREQUESTTESTS_SPEC2_11_ACTIONREQ_CONTENTTYPE6);
    if (!StringUtils.containsIgnoreCase(portletReq.getResponseContentType(), portletReq.getCharacterEncoding()))
        tr6.setTcSuccess(true);
    tr6.writeTo(writer);

    portletReq.getPortletSession().setAttribute(RESULT_ATTR_PREFIX + "AddlRequestTests_SPEC2_11_ActionReq",
            writer.toString(), APPLICATION_SCOPE);
}

From source file:com.DPFaragir.DPFUtils.java

public static String getIPAddress(boolean useIPv4) {
    try {//from   w  w  w  .  j a  va 2s .  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();
                    boolean isIPv4 = InetAddressUtils.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 ex) {
    } // for now eat exceptions
    return "";
}

From source file:org.eclipse.gemini.blueprint.extender.internal.support.NamespaceManager.java

/**
 * Registers the namespace plugin handler if this bundle defines handler mapping or schema mapping resources.
 * /*from   ww  w  .  j  a va  2s . c o  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.eclipse.gemini.blueprint.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:org.springframework.cloud.function.deployer.ApplicationBootstrap.java

private URL[] findClassPath(Class<?> mainClass) {
    ClassLoader base = mainClass.getClassLoader();
    if (!(base instanceof URLClassLoader)) {
        try {//from   ww  w.j  a v a  2s.c  o m
            // Guess the classpath, based on where we can resolve existing resources
            List<URL> list = Collections.list(mainClass.getClassLoader().getResources("META-INF"));
            List<URL> result = new ArrayList<>();
            result.add(mainClass.getProtectionDomain().getCodeSource().getLocation());
            for (URL url : list) {
                String path = url.toString();
                path = path.substring(0, path.length() - "/META-INF".length()) + "/";
                result.add(new URL(path));
            }
            return result.toArray(new URL[result.size()]);
        } catch (IOException e) {
            throw new IllegalStateException("Cannot find class path", e);
        }
    } else {
        @SuppressWarnings("resource")
        URLClassLoader urlClassLoader = (URLClassLoader) base;
        return urlClassLoader.getURLs();
    }
}

From source file:edu.ucsb.eucalyptus.ic.WalrusReplyQueue.java

public void handle(ExceptionMessage muleMsg) {
    try {//from   w  w w .j av  a 2  s .  c o  m
        Object requestMsg = muleMsg.getPayload();
        String requestString = requestMsg.toString();
        EucalyptusMessage msg = (EucalyptusMessage) BindingManager.getBinding("msgs_eucalyptus_ucsb_edu")
                .fromOM(requestString);
        Throwable ex = muleMsg.getException().getCause();
        EucalyptusMessage errMsg;

        String ipAddr = "127.0.0.1";
        List<NetworkInterface> ifaces = null;
        try {
            ifaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        } catch (SocketException e1) {
        }

        for (NetworkInterface iface : ifaces) {
            try {
                if (!iface.isLoopback() && !iface.isVirtual() && iface.isUp()) {
                    for (InetAddress iaddr : Collections.list(iface.getInetAddresses())) {
                        if (!iaddr.isSiteLocalAddress() && !(iaddr instanceof Inet6Address)) {
                            ipAddr = iaddr.getHostAddress();
                            break;
                        }
                    }
                }
            } catch (SocketException e1) {
            }
        }

        if (ex instanceof NoSuchBucketException) {
            errMsg = new WalrusBucketErrorMessageType(((NoSuchBucketException) ex).getBucketName(),
                    "NoSuchBucket", "The specified bucket was not found", HttpStatus.SC_NOT_FOUND,
                    msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof AccessDeniedException) {
            errMsg = new WalrusBucketErrorMessageType(((AccessDeniedException) ex).getBucketName(),
                    "AccessDenied", "No U", HttpStatus.SC_FORBIDDEN, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof NotAuthorizedException) {
            errMsg = new WalrusBucketErrorMessageType(((NotAuthorizedException) ex).getValue(), "Unauthorized",
                    "No U", HttpStatus.SC_UNAUTHORIZED, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof BucketAlreadyOwnedByYouException) {
            errMsg = new WalrusBucketErrorMessageType(((BucketAlreadyOwnedByYouException) ex).getBucketName(),
                    "BucketAlreadyOwnedByYou",
                    "Your previous request to create the named bucket succeeded and you already own it.",
                    HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof BucketAlreadyExistsException) {
            errMsg = new WalrusBucketErrorMessageType(((BucketAlreadyExistsException) ex).getBucketName(),
                    "BucketAlreadyExists",
                    "The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.",
                    HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof BucketNotEmptyException) {
            errMsg = new WalrusBucketErrorMessageType(((BucketNotEmptyException) ex).getBucketName(),
                    "BucketNotEmpty", "The bucket you tried to delete is not empty.", HttpStatus.SC_CONFLICT,
                    msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof PreconditionFailedException) {
            errMsg = new WalrusBucketErrorMessageType(((PreconditionFailedException) ex).getPrecondition(),
                    "PreconditionFailed", "At least one of the pre-conditions you specified did not hold.",
                    HttpStatus.SC_PRECONDITION_FAILED, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof NotModifiedException) {
            errMsg = new WalrusBucketErrorMessageType(((NotModifiedException) ex).getPrecondition(),
                    "NotModified", "Object Not Modified", HttpStatus.SC_NOT_MODIFIED, msg.getCorrelationId(),
                    ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof TooManyBucketsException) {
            errMsg = new WalrusBucketErrorMessageType(((TooManyBucketsException) ex).getBucketName(),
                    "TooManyBuckets", "You have attempted to create more buckets than allowed.",
                    HttpStatus.SC_BAD_REQUEST, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof EntityTooLargeException) {
            errMsg = new WalrusBucketErrorMessageType(((EntityTooLargeException) ex).getEntityName(),
                    "EntityTooLarge", "Your proposed upload exceeds the maximum allowed object size.",
                    HttpStatus.SC_BAD_REQUEST, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof NoSuchEntityException) {
            errMsg = new WalrusBucketErrorMessageType(((NoSuchEntityException) ex).getBucketName(),
                    "NoSuchEntity", "The specified entity was not found", HttpStatus.SC_NOT_FOUND,
                    msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof DecryptionFailedException) {
            errMsg = new WalrusBucketErrorMessageType(((DecryptionFailedException) ex).getValue(),
                    "Decryption Failed", "Fail", SC_DECRYPTION_FAILED, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof ImageAlreadyExistsException) {
            errMsg = new WalrusBucketErrorMessageType(((ImageAlreadyExistsException) ex).getValue(),
                    "Image Already Exists", "Fail", HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof NotImplementedException) {
            errMsg = new WalrusBucketErrorMessageType(((NotImplementedException) ex).getValue(),
                    "Not Implemented", "NA", HttpStatus.SC_NOT_IMPLEMENTED, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else {
            errMsg = new EucalyptusErrorMessageType(muleMsg.getComponentName(), msg, ex.getMessage());
        }
        replies.putMessage(errMsg);
    } catch (Exception e) {
        LOG.error(e, e);
    }
}

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

/**
 * Returns the URLs of the resources associated with the given package name.
 * /* w  w w .  j  a  va2  s.co  m*/
 * @param packageName
 *            the package name associated with the resources URLs to return
 * 
 * @return the URLs of the resources associated with the given package name
 */
private final List<URL> getResourceURLs(final String packageName) {
    try {
        return Collections.list(_classLoader.getResources(makePath(packageName)));
    } catch (IOException ioEx) {
        throw new RuntimeException(
                "couldn't get resources from package '" + packageName + "': " + ioEx.getMessage(), ioEx);
    }
}

From source file:org.apache.hadoop.hdfs.server.common.MetricsLoggerTask.java

/**
 * Make the metrics logger async and add all pre-existing appenders to the
 * async appender.//from w w  w.java 2 s  .  co m
 */
public static void makeMetricsLoggerAsync(Log metricsLog) {
    if (!(metricsLog instanceof Log4JLogger)) {
        LOG.warn("Metrics logging will not be async since " + "the logger is not log4j");
        return;
    }
    org.apache.log4j.Logger logger = ((Log4JLogger) metricsLog).getLogger();
    logger.setAdditivity(false); // Don't pollute actual logs with metrics dump

    @SuppressWarnings("unchecked")
    List<Appender> appenders = Collections.list(logger.getAllAppenders());
    // failsafe against trying to async it more than once
    if (!appenders.isEmpty() && !(appenders.get(0) instanceof AsyncAppender)) {
        AsyncAppender asyncAppender = new AsyncAppender();
        // change logger to have an async appender containing all the
        // previously configured appenders
        for (Appender appender : appenders) {
            logger.removeAppender(appender);
            asyncAppender.addAppender(appender);
        }
        logger.addAppender(asyncAppender);
    }
}

From source file:org.apache.sling.scripting.sightly.impl.compiler.CompileTimeObjectModel.java

@SuppressWarnings("unchecked")
private static Collection<Object> obtainCollection(Object obj) {
    if (obj == null) {
        return Collections.emptyList();
    }// w  ww . j av  a  2 s.c  o m
    if (obj instanceof Object[]) {
        return Arrays.asList((Object[]) obj);
    }
    if (obj instanceof Collection) {
        return (Collection<Object>) obj;
    }
    if (obj instanceof Map) {
        return ((Map) obj).keySet();
    }
    if (obj instanceof Enumeration) {
        return Collections.list((Enumeration<Object>) obj);
    }
    if (obj instanceof Iterator) {
        return fromIterator((Iterator<Object>) obj);
    }
    if (obj instanceof Iterable) {
        Iterable iterable = (Iterable) obj;
        return fromIterator(iterable.iterator());
    }
    if (obj instanceof String || obj instanceof Number) {
        Collection list = new ArrayList();
        list.add(obj);
        return list;
    }
    return Collections.emptyList();
}