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:nl.nn.adapterframework.extensions.tibco.TibcoLogJmsListener.java

public String getStringFromRawMessage(Object rawMessage, Map context, boolean soap, String soapHeaderSessionKey,
        SoapWrapper soapWrapper) throws JMSException, DomBuilderException, TransformerException, IOException {
    TibjmsMapMessage tjmMessage;/* www  .  j a v  a  2  s .co  m*/
    try {
        tjmMessage = (TibjmsMapMessage) rawMessage;
    } catch (ClassCastException e) {
        log.error(
                "message received by listener on [" + getDestinationName()
                        + "] was not of type TibjmsMapMessage, but [" + rawMessage.getClass().getName() + "]",
                e);
        return null;
    }
    Enumeration enumeration = tjmMessage.getMapNames();
    List list = Collections.list(enumeration);
    Collections.sort(list);
    Iterator it = list.iterator();
    StringBuffer sb = new StringBuffer();
    long creationTimes = 0;
    int severity = 0;
    String severityStr = null;
    String msg = null;
    String engineName = null;
    String jobId = null;
    String environment = null;
    String node = null;
    boolean first = true;
    while (it.hasNext()) {
        String mapName = (String) it.next();
        if (mapName.equalsIgnoreCase("_cl.creationTimes")) {
            creationTimes = tjmMessage.getLong(mapName);
        } else {
            if (mapName.equalsIgnoreCase("_cl.severity")) {
                severity = tjmMessage.getInt(mapName);
                severityStr = logLevelToText(severity);
                if (severityStr == null) {
                    severityStr = "[" + severity + "]";
                }
                severityStr = StringUtils.rightPad(severityStr, 5);
            } else {
                if (mapName.equalsIgnoreCase("_cl.msg")) {
                    msg = tjmMessage.getString(mapName);
                } else {
                    if (mapName.equalsIgnoreCase("_cl.engineName")) {
                        engineName = tjmMessage.getString(mapName);
                    } else {
                        if (mapName.equalsIgnoreCase("_cl.jobId")) {
                            jobId = tjmMessage.getString(mapName);
                        } else {
                            String mapValue = tjmMessage.getString(mapName);
                            if (mapName.equalsIgnoreCase("_cl.physicalCompId.matrix.env")) {
                                environment = mapValue;
                                context.put("environment", environment);
                            }
                            if (mapName.equalsIgnoreCase("_cl.physicalCompId.matrix.node")) {
                                node = mapValue;
                            }
                            if (first) {
                                first = false;
                            } else {
                                sb.append(",");
                            }
                            sb.append("[" + mapName + "]=[" + mapValue + "]");
                        }
                    }
                }
            }
        }
    }
    return DateUtils.format(creationTimes) + " " + severityStr + " ["
            + (engineName != null ? engineName : (environment + "-" + node)) + "] ["
            + (jobId != null ? jobId : "") + "] " + msg + " " + sb.toString();
}

From source file:org.openmrs.module.logmanager.impl.ManagerProxy.java

/**
 * Gets all loggers currently being used
 * @param incImplicit true to include loggers with inherited levels and appenders
 * @return the list of loggers/*ww w . j a  va 2  s.c o  m*/
 */
@SuppressWarnings("unchecked")
public static List<LoggerProxy> getLoggers(boolean incImplicit) {
    Enumeration<Logger> loggersEnum = (Enumeration<Logger>) LogManager.getCurrentLoggers();

    // Convert enum to a list
    List<Logger> loggers = incImplicit ? Collections.list(loggersEnum)
            : getExplicitLoggersFromEnum(loggersEnum);

    // Sort list by logger name
    Collections.sort(loggers, new Comparator<Logger>() {
        public int compare(Logger log1, Logger log2) {
            return log1.getName().compareTo(log2.getName());
        }
    });

    // Convert to proxy objects
    List<LoggerProxy> proxies = new ArrayList<LoggerProxy>();
    for (Logger logger : loggers)
        proxies.add(new LoggerProxy(logger));

    return proxies;
}

From source file:org.apache.hadoop.hive.ql.io.merge.BlockMergeTask.java

public static void main(String[] args) {
    String inputPathStr = null;//from w w  w.  j  a  v  a  2  s.  c  om
    String outputDir = null;
    String jobConfFileName = null;
    Class<? extends Mapper> mapperClass = RCFileMergeMapper.class;
    Class<? extends FileInputFormat> inputFormatClass = RCFileBlockMergeInputFormat.class;

    try {
        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("-input")) {
                inputPathStr = args[++i];
            } else if (args[i].equals("-jobconffile")) {
                jobConfFileName = args[++i];
            } else if (args[i].equals("-outputDir")) {
                outputDir = args[++i];
            } else if (args[i].equals("-inputformat")) {
                String inputFormat = args[++i];
                if (inputFormat.equalsIgnoreCase("ORC")) {
                    mapperClass = OrcMergeMapper.class;
                    inputFormatClass = OrcBlockMergeInputFormat.class;
                } else if (!inputFormat.equalsIgnoreCase("RCFile")) {
                    System.err.println("Only RCFile and OrcFile inputs are supported.");
                    printUsage();
                }
            }
        }
    } catch (IndexOutOfBoundsException e) {
        System.err.println("Missing argument to option");
        printUsage();
    }

    if (inputPathStr == null || outputDir == null || outputDir.trim().equals("")) {
        printUsage();
    }

    List<String> inputPaths = new ArrayList<String>();
    String[] paths = inputPathStr.split(INPUT_SEPERATOR);
    if (paths == null || paths.length == 0) {
        printUsage();
    }

    FileSystem fs = null;
    JobConf conf = new JobConf(BlockMergeTask.class);
    for (String path : paths) {
        try {
            Path pathObj = new Path(path);
            if (fs == null) {
                fs = FileSystem.get(pathObj.toUri(), conf);
            }
            FileStatus fstatus = fs.getFileStatus(pathObj);
            if (fstatus.isDir()) {
                FileStatus[] fileStatus = fs.listStatus(pathObj);
                for (FileStatus st : fileStatus) {
                    inputPaths.add(st.getPath().toString());
                }
            } else {
                inputPaths.add(fstatus.getPath().toString());
            }
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
    }

    if (jobConfFileName != null) {
        conf.addResource(new Path(jobConfFileName));
    }
    HiveConf hiveConf = new HiveConf(conf, BlockMergeTask.class);

    Log LOG = LogFactory.getLog(BlockMergeTask.class.getName());
    boolean isSilent = HiveConf.getBoolVar(conf, HiveConf.ConfVars.HIVESESSIONSILENT);
    LogHelper console = new LogHelper(LOG, isSilent);

    // print out the location of the log file for the user so
    // that it's easy to find reason for local mode execution failures
    for (Appender appender : Collections
            .list((Enumeration<Appender>) LogManager.getRootLogger().getAllAppenders())) {
        if (appender instanceof FileAppender) {
            console.printInfo("Execution log at: " + ((FileAppender) appender).getFile());
        }
    }

    MergeWork mergeWork = new MergeWork(inputPaths, outputDir, mapperClass, inputFormatClass);
    DriverContext driverCxt = new DriverContext();
    BlockMergeTask taskExec = new BlockMergeTask();
    taskExec.initialize(hiveConf, null, driverCxt);
    taskExec.setWork(mergeWork);
    int ret = taskExec.execute(driverCxt);

    if (ret != 0) {
        System.exit(2);
    }

}

From source file:psiprobe.controllers.truststore.TrustStoreController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    List<Map<String, String>> certificateList = new ArrayList<>();
    try {//from   w w w  .j  ava  2 s.  c o  m
        String trustStoreType = System.getProperty("javax.net.ssl.trustStoreType");
        KeyStore ks;
        if (trustStoreType != null) {
            ks = KeyStore.getInstance(trustStoreType);
        } else {
            ks = KeyStore.getInstance("JKS");
        }
        String trustStore = System.getProperty("javax.net.ssl.trustStore");
        String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
        if (trustStore != null) {
            try (FileInputStream fis = new FileInputStream(trustStore)) {
                ks.load(fis, trustStorePassword != null ? trustStorePassword.toCharArray() : null);
            }
            Map<String, String> attributes;
            for (String alias : Collections.list(ks.aliases())) {
                attributes = new HashMap<>();
                if (ks.getCertificate(alias).getType().equals("X.509")) {
                    X509Certificate cert = (X509Certificate) ks.getCertificate(alias);

                    attributes.put("alias", alias);
                    attributes.put("cn", cert.getSubjectDN().toString());
                    attributes.put("expirationDate",
                            new SimpleDateFormat("yyyy-MM-dd").format(cert.getNotAfter()));
                    certificateList.add(attributes);
                }
            }
        }
    } catch (Exception e) {
        logger.error("There was an exception obtaining truststore: ", e);
    }
    ModelAndView mv = new ModelAndView(getViewName());
    mv.addObject("certificates", certificateList);
    return mv;
}

From source file:license.mac.MacTest.java

/**
 * mac?//  w  ww .  j  a va2  s .  co  m
 * @return
 * @throws SocketException
 */
public boolean checkMac() throws SocketException {
    StringBuffer sb = new StringBuffer();
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    int i = 12;
    Base64 base64 = new Base64();
    for (NetworkInterface ni : Collections.list(interfaces)) {
        if (ni.getName().substring(0, 1).equalsIgnoreCase("e")) {
            sb.append(String.valueOf(i)).append('=').append(ni.getName()).append('\n');
            i++;
            byte[] mac = ni.getHardwareAddress();
            sb.append(String.valueOf(i)).append('=').append(base64.encodeAsString(mac)).append('\n');
            i++;
        }
    }
    System.out.println(sb.toString());
    return true;
}

From source file:org.cloudfoundry.identity.uaa.ldap.ExtendedLdapUserMapper.java

@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username,
        Collection<? extends GrantedAuthority> authorities) {
    LdapUserDetails ldapUserDetails = (LdapUserDetails) super.mapUserFromContext(ctx, username, authorities);

    DirContextAdapter adapter = (DirContextAdapter) ctx;
    Map<String, String[]> record = new HashMap<String, String[]>();
    List<String> attributeNames = Collections.list(adapter.getAttributes().getIDs());
    for (String attributeName : attributeNames) {
        try {/*w  ww  . j  a  v a2s  .c o  m*/
            String[] values = adapter.getStringAttributes(attributeName);
            if (values == null || values.length == 0) {
                logger.debug("No attribute value found for '" + attributeName + "'");
            } else {
                record.put(attributeName, values);
            }
        } catch (ArrayStoreException x) {
            logger.debug("Attribute value is not a string for '" + attributeName + "'");
        }
    }
    record.put(DN_KEY, new String[] { adapter.getDn().toString() });
    String mailAttr = configureMailAttribute(username, record);
    ExtendedLdapUserImpl result = new ExtendedLdapUserImpl(ldapUserDetails, record);
    result.setMailAttributeName(mailAttr);
    return result;
}

From source file:org.paxle.se.index.lucene.impl.StopwordsManager.java

@Activate
protected void activate(ComponentContext context) {
    @SuppressWarnings("unchecked")
    final Enumeration<URL> stopwords = context.getBundleContext().getBundle()
            .findEntries("/stopwords/snowball/", "*" + StopwordsManager.STOPWORDS_FILE_EXT, true);
    final Collection<URL> stopWordsURLs = (stopwords != null) ? Collections.list(stopwords) : null;
    this.initStopWords(stopWordsURLs);
}

From source file:org.sipfoundry.sipxconfig.phone.yealink.YealinkDirectoryConfiguration.java

void transformPhoneBook(Collection<PhonebookEntry> phonebookEntries,
        Collection<YealinkPhonebookEntry> yealinkEntries) {
    for (PhonebookEntry entry : phonebookEntries) {
        yealinkEntries.add(new YealinkPhonebookEntry(entry));
    }/*  w  w w.  j  av a  2s .  c o m*/
    List<YealinkPhonebookEntry> tmp = Collections.list(Collections.enumeration(yealinkEntries));
    Collections.sort(tmp);
    yealinkEntries.clear();
    for (YealinkPhonebookEntry entry : tmp) {
        yealinkEntries.add(entry);
    }
}

From source file:org.apache.zeppelin.interpreter.remote.RemoteInterpreterUtils.java

public static String findAvailableHostAddress() throws UnknownHostException, SocketException {
    InetAddress address = InetAddress.getLocalHost();
    if (address.isLoopbackAddress()) {
        for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
            if (!networkInterface.isLoopback()) {
                for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                    InetAddress a = interfaceAddress.getAddress();
                    if (a instanceof Inet4Address) {
                        return a.getHostAddress();
                    }/*from  w  w  w.j ava  2  s .co m*/
                }
            }
        }
    }
    return address.getHostAddress();
}

From source file:org.cloudfoundry.identity.uaa.provider.ldap.ExtendedLdapUserMapper.java

@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username,
        Collection<? extends GrantedAuthority> authorities) {
    LdapUserDetails ldapUserDetails = (LdapUserDetails) super.mapUserFromContext(ctx, username, authorities);

    DirContextAdapter adapter = (DirContextAdapter) ctx;
    Map<String, String[]> record = new HashMap<String, String[]>();
    List<String> attributeNames = Collections.list(adapter.getAttributes().getIDs());
    for (String attributeName : attributeNames) {
        try {//  w w w  .ja  v a2s .  co m
            Object[] objValues = adapter.getObjectAttributes(attributeName);
            String[] values = new String[objValues != null ? objValues.length : 0];
            for (int i = 0; i < values.length; i++) {
                if (objValues[i] != null) {
                    if (objValues[i].getClass().isAssignableFrom(String.class)) {
                        values[i] = (String) objValues[i];
                    } else if (objValues[i] instanceof byte[]) {
                        values[i] = new String((byte[]) objValues[i]);
                    } else {
                        values[i] = objValues[i].toString();
                    }
                }
            }
            if (values == null || values.length == 0) {
                logger.debug("No attribute value found for '" + attributeName + "'");
            } else {
                record.put(attributeName, values);
            }
        } catch (ArrayStoreException x) {
            logger.debug("Attribute value is not a string for '" + attributeName + "'");
        }
    }
    record.put(DN_KEY, new String[] { adapter.getDn().toString() });
    String mailAttr = configureMailAttribute(username, record);
    ExtendedLdapUserImpl result = new ExtendedLdapUserImpl(ldapUserDetails, record);
    result.setMailAttributeName(mailAttr);
    result.setGivenNameAttributeName(givenNameAttributeName);
    result.setFamilyNameAttributeName(familyNameAttributeName);
    result.setPhoneNumberAttributeName(phoneNumberAttributeName);
    return result;
}