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:org.apache.hadoop.hive.ql.io.rcfile.merge.BlockMergeTask.java

public static void main(String[] args) {

    ArrayList<String> jobConfArgs = new ArrayList<String>();

    String inputPathStr = null;//  w w  w . ja  va 2 s  .c  om
    String outputDir = null;

    try {
        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("-input")) {
                inputPathStr = args[++i];
            } else if (args[i].equals("-jobconf")) {
                jobConfArgs.add(args[++i]);
            } else if (args[i].equals("-outputDir")) {
                outputDir = args[++i];
            }
        }
    } 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);
        }
    }

    StringBuilder sb = new StringBuilder("JobConf:\n");

    for (String one : jobConfArgs) {
        int eqIndex = one.indexOf('=');
        if (eqIndex != -1) {
            try {
                String key = one.substring(0, eqIndex);
                String value = URLDecoder.decode(one.substring(eqIndex + 1), "UTF-8");
                conf.set(key, value);
                sb.append(key).append("=").append(value).append("\n");
            } catch (UnsupportedEncodingException e) {
                System.err.println(
                        "Unexpected error " + e.getMessage() + " while encoding " + one.substring(eqIndex + 1));
                System.exit(3);
            }
        }
    }
    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());
        }
    }

    // log the list of job conf parameters for reference
    LOG.info(sb.toString());

    MergeWork mergeWork = new MergeWork(inputPaths, outputDir);
    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:io.stallion.monitoring.ExceptionInfo.java

public static ExceptionInfo newForException(Throwable e) {
    ExceptionInfo info = new ExceptionInfo();
    info.thrownAt = utcNow();/*from   w w w  . ja  v a2 s  .c  o m*/
    info.stackTraces = ExceptionUtils.getRootCauseStackTrace(e);
    if (e instanceof InvocationTargetException) {
        e = ((InvocationTargetException) e).getTargetException();
    }
    info.className = e.getClass().getSimpleName();
    info.message = e.getMessage();
    info.requestUrl = request().getRequestUrl();
    info.requestUrlWithQuery = request().getRequestUrlWithQuery();
    info.requestMethod = request().getMethod();
    info.remoteAddr = request().getRemoteAddr();
    info.actualIp = request().getActualIp();
    info.requestHeaders = map();
    for (String name : Collections.list(request().getHeaderNames())) {
        info.requestHeaders.put(name, request().getHeader(name));
    }
    try {
        info.setRequestBody(request().getContent());
    } catch (RuntimeException e2) {
        Log.info("Error logging the exception - could not get the request body: {0}", e2);
    }
    if (!Context.getUser().isAnon()) {
        info.setEmail(Context.getUser().getEmail());
        info.setUsername(Context.getUser().getUsername());
        info.setUserId(Context.getUser().getId());
        info.setValetId(Context.getValetUserId());
    }
    return info;
}

From source file:me.j360.trace.server.brave.BraveConfiguration.java

/** This gets the lanIP without trying to lookup its name. */
// http://stackoverflow.com/questions/8765578/get-local-ip-address-without-connecting-to-the-internet
@Bean/*from  w ww  .  j  a  v  a2  s  . c om*/
@Scope
Endpoint local(@Value("${server.port:9411}") int port) {
    int ipv4;
    try {
        ipv4 = Collections.list(NetworkInterface.getNetworkInterfaces()).stream()
                .flatMap(i -> Collections.list(i.getInetAddresses()).stream())
                .filter(ip -> ip instanceof Inet4Address && ip.isSiteLocalAddress())
                .map(InetAddress::getAddress).map(bytes -> new BigInteger(bytes).intValue()).findAny().get();
    } catch (Exception ignored) {
        ipv4 = 127 << 24 | 1;
    }
    return Endpoint.create("zipkin-server", ipv4, port);
}

From source file:psiprobe.controllers.jsp.RecompileJspController.java

@Override
protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession(false);
    Summary summary = (Summary) session.getAttribute(DisplayJspController.SUMMARY_ATTRIBUTE);

    if (request.getMethod().equalsIgnoreCase("post") && summary != null) {
        List<String> names = new ArrayList<>();
        for (String name : Collections.list(request.getParameterNames())) {
            if ("on".equals(request.getParameter(name))) {
                names.add(name);//from ww  w  .j  av a  2s .  c  om
            }
        }
        getContainerWrapper().getTomcatContainer().recompileJsps(context, summary, names);
        session.setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE, summary);
    } else if (summary != null && contextName.equals(summary.getName())) {
        String name = ServletRequestUtils.getStringParameter(request, "source", null);
        if (name != null) {
            List<String> names = new ArrayList<>();
            names.add(name);
            getContainerWrapper().getTomcatContainer().recompileJsps(context, summary, names);
            session.setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE, summary);
        } else {
            logger.error("source is not passed, nothing to do");
        }
    }
    return new ModelAndView(new RedirectView(
            request.getContextPath() + ServletRequestUtils.getStringParameter(request, "view", getViewName())
                    + "?" + request.getQueryString()));
}

From source file:org.nuxeo.runtime.jtajca.NuxeoConnectionManagerFactory.java

public static NuxeoConnectionManagerConfiguration getConfig(Reference ref) {
    NuxeoConnectionManagerConfiguration config = new NuxeoConnectionManagerConfiguration();
    IllegalArgumentException errors = new IllegalArgumentException("wrong naming config");
    for (RefAddr addr : Collections.list(ref.getAll())) {
        String name = addr.getType();
        String value = (String) addr.getContent();
        try {//w  ww.j  av  a2 s. co  m
            BeanUtils.setProperty(config, name, value);
        } catch (ReflectiveOperationException cause) {
            errors.addSuppressed(cause);
        }
    }
    if (errors.getSuppressed().length > 0) {
        throw errors;
    }
    return config;
}

From source file:eu.eubrazilcc.lvl.core.util.NetworkingUtils.java

/**
 * Gets the first public IP address of the host. If no public address are found, one of the private
 * IPs are randomly selected. Otherwise, it returns {@code localhost}.
 * @return the first public IP address of the host.
 *//*from w ww. ja  va 2  s  .c  om*/
public static final String getInet4Address() {
    String inet4Address = null;
    final List<String> localAddresses = new ArrayList<String>();
    try {
        final Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
        if (networks != null) {
            final List<NetworkInterface> ifs = Collections.list(networks);
            for (int i = 0; i < ifs.size() && inet4Address == null; i++) {
                final Enumeration<InetAddress> inetAddresses = ifs.get(i).getInetAddresses();
                if (inetAddresses != null) {
                    final List<InetAddress> addresses = Collections.list(inetAddresses);
                    for (int j = 0; j < addresses.size() && inet4Address == null; j++) {
                        final InetAddress address = addresses.get(j);
                        if (address instanceof Inet4Address && !address.isAnyLocalAddress()
                                && !address.isLinkLocalAddress() && !address.isLoopbackAddress()
                                && StringUtils.isNotBlank(address.getHostAddress())) {
                            final String hostAddress = address.getHostAddress().trim();
                            if (!hostAddress.startsWith("10.") && !hostAddress.startsWith("172.16.")
                                    && !hostAddress.startsWith("192.168.")) {
                                inet4Address = hostAddress;
                            } else {
                                localAddresses.add(hostAddress);
                            }
                            LOGGER.trace(
                                    "IP found - Name: " + address.getHostName() + ", Addr: " + hostAddress);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.warn("Failed to discover public IP address for this host", e);
    }
    return (StringUtils.isNotBlank(inet4Address) ? inet4Address
            : (!localAddresses.isEmpty() ? localAddresses.get(new Random().nextInt(localAddresses.size()))
                    : "localhost")).trim();
}

From source file:exercise.servletfeature.ServletFeatureResource.java

@GET
@Path("demo1")
@Produces(MediaType.APPLICATION_JSON)//from   w w w  .  j ava 2 s  .  com
public Response getServletContextAndConfigs() throws JsonProcessingException {
    Map<String, String> dump = new HashMap<>();

    dump.put("servlet-name", servletConfig.getServletName());
    /*
     * Enumeration to for: http://d.hatena.ne.jp/chiheisen/20110410/1302447986
     * http://stackoverflow.com/questions/7160568
     * /iterating-through-enumeration-of-hastable-keys-throws-nosuchelementexception-err
     */
    for (String pname : Collections.list(servletConfig.getInitParameterNames())) {
        String k = "servlet-init-param-" + pname;
        dump.put(k, servletConfig.getInitParameter(pname));
    }

    dump.put("server-info", servletContext.getServerInfo());
    StringBuilder sb = new StringBuilder();
    sb.append(servletContext.getMajorVersion());
    sb.append(".");
    sb.append(servletContext.getMinorVersion());
    dump.put("version", sb.toString());
    dump.put("context-path", servletContext.getContextPath());

    ObjectMapper objectMapper = new ObjectMapper();
    String jsonout = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(dump);
    return Response.status(Status.OK).type(MediaType.APPLICATION_JSON_TYPE.withCharset("UTF-8")).entity(jsonout)
            .encoding("UTF-8").build();
}

From source file:org.nuxeo.runtime.jtajca.NuxeoTransactionManagerFactory.java

@Override
public Object getObjectInstance(Object obj, Name objName, Context nameCtx, Hashtable<?, ?> env) {
    Reference ref = (Reference) obj;
    if (!TransactionManager.class.getName().equals(ref.getClassName())) {
        return null;
    }/*from  w w w . ja v  a2 s.co m*/
    if (NuxeoContainer.tm != null) {
        return NuxeoContainer.tm;
    }

    // initialize
    TransactionManagerConfiguration config = new TransactionManagerConfiguration();
    for (RefAddr addr : Collections.list(ref.getAll())) {
        String name = addr.getType();
        String value = (String) addr.getContent();
        try {
            BeanUtils.setProperty(config, name, value);
        } catch (ReflectiveOperationException e) {
            log.error(String.format("NuxeoTransactionManagerFactory cannot set %s = %s", name, value));
        }
    }
    return NuxeoContainer.initTransactionManager(config);
}

From source file:com.rest4j.impl.ApiRequestServletImpl.java

@Override
public Iterable<String> paramNames() {
    return Collections.list(request.getParameterNames());
}

From source file:org.vosao.i18n.VosaoResourceBundle.java

@Override
public Enumeration<String> getKeys() {
    List<String> result = new ArrayList<String>();
    for (ResourceBundle bundle : getResourceBundles()) {
        result.addAll(Collections.list(bundle.getKeys()));
    }//from  w ww  .  j a v a2 s  .  com
    return Collections.enumeration(result);
}