Example usage for java.util Arrays asList

List of usage examples for java.util Arrays asList

Introduction

In this page you can find the example usage for java.util Arrays asList.

Prototype

@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) 

Source Link

Document

Returns a fixed-size list backed by the specified array.

Usage

From source file:com.asakusafw.generator.HadoopBulkLoaderDDLGenerator.java

/**
 * HadoopBulkLoader?????/*from  w w w  . jav a 2 s  .  c  o m*/
 *
 * @param args
 *            ??
 * @throws Exception
 *             ??????
 */
public static void main(String[] args) throws Exception {
    String outputTablesString = findVariable(ENV_BULKLOADER_TABLES, true);
    List<String> outputTableList = null;
    if (outputTablesString != null && !OUTPUT_TABLES_PROPERTY.equals(outputTablesString)) {
        String[] outputTables = outputTablesString.trim().split("\\s+");
        outputTableList = Arrays.asList(outputTables);
    }

    String ddlTemplate;
    InputStream in = HadoopBulkLoaderDDLGenerator.class.getResourceAsStream(TEMPLATE_DDL_FILENAME);
    try {
        ddlTemplate = IOUtils.toString(in);
    } finally {
        in.close();
    }
    StringBuilder sb = new StringBuilder();

    for (String tableName : args) {
        if (outputTableList == null || outputTableList.contains(tableName)) {
            String tableddl = ddlTemplate.replaceAll(TABLENAME_REPLACE_STRING, tableName);
            sb.append(tableddl);
        }
    }

    String outputFilePath = findVariable(ENV_BULKLOADER_GENDDL, true);
    if (outputFilePath == null) {
        throw new RuntimeException(
                "ASAKUSA_BULKLOADER_TABLES???????");
    }
    FileUtils.write(new File(outputFilePath), sb);
}

From source file:com.dhenton9000.screenshots.ScreenShotLauncher.java

/**
 * main launching method that takes command line arguments
 *
 * @param args//from  w  ww  . j av a2s  .c  o  m
 */
public static void main(String[] args) {

    final String[] actions = { ACTIONS.source.toString(), ACTIONS.target.toString(),
            ACTIONS.compare.toString() };
    final List actionArray = Arrays.asList(actions);

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("action").hasArg().isRequired().withArgName("action").create());
    HelpFormatter formatter = new HelpFormatter();

    String header = "Process screenshots\n" + "--action=source   create source screenshots\n"
            + "--action=target     create the screenshots for comparison\n"
            + "--action=compare  compare the images\n" + "%s\n\n";

    String action = null;
    try {
        // parse the command line arguments
        CommandLineParser parser = new PosixParser();
        CommandLine line = parser.parse(options, args);

        // validate that action option has been set
        if (line.hasOption("action")) {
            action = line.getOptionValue("action");
            LOG.debug("action '" + action + "'");
            if (!actionArray.contains(action)) {

                formatter.printHelp(ScreenShotLauncher.class.getName(),
                        String.format(header, String.format("action option '%s' is invalid", action)), options,
                        "\n\n", true);
                System.exit(1);

            }

        } else {
            formatter.printHelp(ScreenShotLauncher.class.getName(), String.format(header, "not found"), options,
                    "\n\n", false);
            System.exit(1);
        }
    } catch (ParseException exp) {
        formatter.printHelp(ScreenShotLauncher.class.getName(),
                String.format(header, "problem " + exp.getMessage()), options, "\n\n", false);
        System.exit(1);

    }
    ACTIONS actionEnum = ACTIONS.valueOf(action);
    ScreenShotLauncher launcher = new ScreenShotLauncher();
    try {
        launcher.handleRequest(actionEnum);
    } catch (Exception ex) {
        LOG.error(ex.getMessage(), ex);

    }
}

From source file:ArrayToVector.java

public static void main(String[] args) {
    Object[] a1d = { "Hello World", new Date(), Calendar.getInstance(), };
    // Arrays.asList(Object[]) --> List
    List l = Arrays.asList(a1d);

    // Vector contstructor takes Collection
    // List is a subclass of Collection
    Vector v;/*from w  w  w.j  ava2s  . c  om*/
    v = new Vector(l);

    // Or, more simply:
    v = new Vector(Arrays.asList(a1d));

    // Just to prove that it worked.
    Enumeration e = v.elements();
    while (e.hasMoreElements()) {
        System.out.println(e.nextElement());
    }
}

From source file:com.databasepreservation.Main.java

/**
 * @param args//from   w  w w . j  a  v a 2 s.c  om
 *          the console arguments
 */
public static void main(String[] args) {
    CLI cli = new CLI(Arrays.asList(args), databaseModuleFactories);
    System.exit(internal_main(cli));
}

From source file:Tweedle.java

public static void main(String... args) {
    Book book = new Book();
    String fmt = "%6S:  %-12s = %s%n";

    try {//from w ww . ja va  2 s . c  o m
        Class<?> c = book.getClass();

        Field chap = c.getDeclaredField("chapters");
        out.format(fmt, "before", "chapters", book.chapters);
        chap.setLong(book, 12);
        out.format(fmt, "after", "chapters", chap.getLong(book));

        Field chars = c.getDeclaredField("characters");
        out.format(fmt, "before", "characters", Arrays.asList(book.characters));
        String[] newChars = { "Queen", "King" };
        chars.set(book, newChars);
        out.format(fmt, "after", "characters", Arrays.asList(book.characters));

        Field t = c.getDeclaredField("twin");
        out.format(fmt, "before", "twin", book.twin);
        t.set(book, Tweedle.DUM);
        out.format(fmt, "after", "twin", t.get(book));

        // production code should handle these exceptions more gracefully
    } catch (NoSuchFieldException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    }
}

From source file:com.athena.peacock.controller.common.util.DiffUtil.java

public static void main(String[] args) {
    List<String> original = null;
    List<String> revised = null;

    String a = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8\nLine 9\nLine 10";
    String b = "Line 1\nLine 3 with changes\nLine 4\nLine 5 with changes and\na new line\nLine 6\nnew line 6.1\nLine 7\nLine 8\nLine 9\nLine 10 with changes";

    original = Arrays.asList(a.split("\n"));
    revised = Arrays.asList(b.split("\n"));

    Patch<String> patch = DiffUtils.diff(original, revised);

    for (Delta<String> delta : patch.getDeltas()) {
        System.out.println(delta);
    }/*from www. j  av a  2s . com*/

    System.out.println(original);
    System.out.println(revised);
}

From source file:OysterMonths.java

public static void main(String[] args) {
    OysterMonths om = new OysterMonths();
    DateFormatSymbols dfs = new DateFormatSymbols();
    String[] monthArray = dfs.getMonths();
    Collection<String> months = Arrays.asList(monthArray);
    om.safeMonths = om.filter(months);//from   w w w  . j a v a  2  s  . c om
    System.out.println("The following months are safe for oysters:");
    System.out.println(om.safeMonths);
}

From source file:com.cloud.test.utils.TestClient.java

public static void main(String[] args) {
    String host = "http://localhost";
    String port = "8080";
    String testUrl = "/client/test";
    int numThreads = 1;

    try {//from w w w.  ja  va  2  s  . c  o  m
        // Parameters
        List<String> argsList = Arrays.asList(args);
        Iterator<String> iter = argsList.iterator();
        while (iter.hasNext()) {
            String arg = iter.next();
            // host
            if (arg.equals("-h")) {
                host = "http://" + iter.next();
            }

            if (arg.equals("-p")) {
                port = iter.next();
            }

            if (arg.equals("-t")) {
                numThreads = Integer.parseInt(iter.next());
            }

            if (arg.equals("-s")) {
                sleepTime = Long.parseLong(iter.next());
            }

            if (arg.equals("-c")) {
                cleanUp = Boolean.parseBoolean(iter.next());
                if (!cleanUp)
                    sleepTime = 0L; // no need to wait if we don't ever cleanup
            }

            if (arg.equals("-r")) {
                repeat = Boolean.parseBoolean(iter.next());
            }

            if (arg.equals("-u")) {
                numOfUsers = Integer.parseInt(iter.next());
            }

            if (arg.equals("-i")) {
                internet = Boolean.parseBoolean(iter.next());
            }
        }

        final String server = host + ":" + port + testUrl;
        s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)");
        if (cleanUp)
            s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up");

        if (numOfUsers > 0) {
            s_logger.info("Pre-generating users for test of size : " + numOfUsers);
            users = new String[numOfUsers];
            Random ran = new Random();
            for (int i = 0; i < numOfUsers; i++) {
                users[i] = Math.abs(ran.nextInt()) + "-user";
            }
        }

        for (int i = 0; i < numThreads; i++) {
            new Thread(new Runnable() {
                public void run() {
                    do {
                        String username = null;
                        try {
                            long now = System.currentTimeMillis();
                            Random ran = new Random();
                            if (users != null) {
                                username = users[Math.abs(ran.nextInt()) % numOfUsers];
                            } else {
                                username = Math.abs(ran.nextInt()) + "-user";
                            }
                            NDC.push(username);

                            String url = server + "?email=" + username + "&password=" + username
                                    + "&command=deploy";
                            s_logger.info("Launching test for user: " + username + " with url: " + url);
                            HttpClient client = new HttpClient();
                            HttpMethod method = new GetMethod(url);
                            int responseCode = client.executeMethod(method);
                            boolean success = false;
                            String reason = null;
                            if (responseCode == 200) {
                                if (internet) {
                                    s_logger.info("Deploy successful...waiting 5 minute before SSH tests");
                                    Thread.sleep(300000L); // Wait 60 seconds so the linux VM can boot up.

                                    s_logger.info("Begin Linux SSH test");
                                    reason = sshTest(method.getResponseHeader("linuxIP").getValue());

                                    if (reason == null) {
                                        s_logger.info("Linux SSH test successful");
                                        s_logger.info("Begin Windows SSH test");
                                        reason = sshWinTest(method.getResponseHeader("windowsIP").getValue());
                                    }
                                }
                                if (reason == null) {
                                    if (internet) {
                                        s_logger.info("Windows SSH test successful");
                                    } else {
                                        s_logger.info("deploy test successful....now cleaning up");
                                        if (cleanUp) {
                                            s_logger.info(
                                                    "Waiting " + sleepTime + " ms before cleaning up vms");
                                            Thread.sleep(sleepTime);
                                        } else {
                                            success = true;
                                        }
                                    }
                                    if (users == null) {
                                        s_logger.info("Sending cleanup command");
                                        url = server + "?email=" + username + "&password=" + username
                                                + "&command=cleanup";
                                    } else {
                                        s_logger.info("Sending stop DomR / destroy VM command");
                                        url = server + "?email=" + username + "&password=" + username
                                                + "&command=stopDomR";
                                    }
                                    method = new GetMethod(url);
                                    responseCode = client.executeMethod(method);
                                    if (responseCode == 200) {
                                        success = true;
                                    } else {
                                        reason = method.getStatusText();
                                    }
                                } else {
                                    // Just stop but don't destroy the VMs/Routers
                                    s_logger.info("SSH test failed with reason '" + reason + "', stopping VMs");
                                    url = server + "?email=" + username + "&password=" + username
                                            + "&command=stop";
                                    responseCode = client.executeMethod(new GetMethod(url));
                                }
                            } else {
                                // Just stop but don't destroy the VMs/Routers
                                reason = method.getStatusText();
                                s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs");
                                url = server + "?email=" + username + "&password=" + username + "&command=stop";
                                client.executeMethod(new GetMethod(url));
                            }

                            if (success) {
                                s_logger.info("***** Completed test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L) + " seconds");
                            } else {
                                s_logger.info("##### FAILED test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L)
                                        + " seconds with reason : " + reason);
                            }
                        } catch (Exception e) {
                            s_logger.warn("Error in thread", e);
                            try {
                                HttpClient client = new HttpClient();
                                String url = server + "?email=" + username + "&password=" + username
                                        + "&command=stop";
                                client.executeMethod(new GetMethod(url));
                            } catch (Exception e1) {
                            }
                        } finally {
                            NDC.clear();
                        }
                    } while (repeat);
                }
            }).start();
        }
    } catch (Exception e) {
        s_logger.error(e);
    }
}

From source file:acmi.l2.clientmod.l2_version_switcher.Main.java

public static void main(String[] args) {
    if (args.length != 3 && args.length != 4) {
        System.out.println("USAGE: l2_version_switcher.jar host game version <--splash> <filter>");
        System.out.println("EXAMPLE: l2_version_switcher.jar " + L2.NCWEST_HOST + " " + L2.NCWEST_GAME
                + " 1 \"system\\*\"");
        System.out.println(/*from  ww w. j  av a 2 s . c  om*/
                "         l2_version_switcher.jar " + L2.PLAYNC_TEST_HOST + " " + L2.PLAYNC_TEST_GAME + " 48");
        System.exit(0);
    }

    List<String> argsList = new ArrayList<>(Arrays.asList(args));
    String host = argsList.get(0);
    String game = argsList.get(1);
    int version = Integer.parseInt(argsList.get(2));
    Helper helper = new Helper(host, game, version);
    boolean available = false;

    try {
        available = helper.isAvailable();
    } catch (IOException e) {
        System.err.print(e.getClass().getSimpleName());
        if (e.getMessage() != null) {
            System.err.print(": " + e.getMessage());
        }

        System.err.println();
    }

    System.out.println(String.format("Version %d available: %b", version, available));
    if (!available) {
        System.exit(0);
    }

    List<FileInfo> fileInfoList = null;
    try {
        fileInfoList = helper.getFileInfoList();
    } catch (IOException e) {
        System.err.println("Couldn\'t get file info map");
        System.exit(1);
    }

    boolean splash = argsList.remove("--splash");
    if (splash) {
        Optional<FileInfo> splashObj = fileInfoList.stream()
                .filter(fi -> fi.getPath().contains("sp_32b_01.bmp")).findAny();
        if (splashObj.isPresent()) {
            try (InputStream is = new FilterInputStream(
                    Util.getUnzipStream(helper.getDownloadStream(splashObj.get().getPath()))) {
                @Override
                public int read() throws IOException {
                    int b = super.read();
                    if (b >= 0)
                        b ^= 0x36;
                    return b;
                }

                @Override
                public int read(byte[] b, int off, int len) throws IOException {
                    int r = super.read(b, off, len);
                    if (r >= 0) {
                        for (int i = 0; i < r; i++)
                            b[off + i] ^= 0x36;
                    }
                    return r;
                }
            }) {
                new DataInputStream(is).readFully(new byte[28]);
                BufferedImage bi = ImageIO.read(is);

                JFrame frame = new JFrame("Lineage 2 [" + version + "] " + splashObj.get().getPath());
                frame.setContentPane(new JComponent() {
                    {
                        setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
                    }

                    @Override
                    protected void paintComponent(Graphics g) {
                        g.drawImage(bi, 0, 0, null);
                    }
                });
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Splash not found");
        }
        return;
    }

    String filter = argsList.size() > 3 ? separatorsToSystem(argsList.get(3)) : null;

    File l2Folder = new File(System.getProperty("user.dir"));
    List<FileInfo> toUpdate = fileInfoList.parallelStream().filter(fi -> {
        String filePath = separatorsToSystem(fi.getPath());

        if (filter != null && !wildcardMatch(filePath, filter, IOCase.INSENSITIVE))
            return false;
        File file = new File(l2Folder, filePath);

        try {
            if (file.exists() && file.length() == fi.getSize() && Util.hashEquals(file, fi.getHash())) {
                System.out.println(filePath + ": OK");
                return false;
            }
        } catch (IOException e) {
            System.out.println(filePath + ": couldn't check hash: " + e);
            return true;
        }

        System.out.println(filePath + ": need update");
        return true;
    }).collect(Collectors.toList());

    List<String> errors = Collections.synchronizedList(new ArrayList<>());
    ExecutorService executor = Executors.newFixedThreadPool(16);
    CompletableFuture[] tasks = toUpdate.stream().map(fi -> CompletableFuture.runAsync(() -> {
        String filePath = separatorsToSystem(fi.getPath());
        File file = new File(l2Folder, filePath);

        File folder = file.getParentFile();
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                errors.add(filePath + ": couldn't create parent dir");
                return;
            }
        }

        try (InputStream input = Util
                .getUnzipStream(new BufferedInputStream(helper.getDownloadStream(fi.getPath())));
                OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) {
            byte[] buffer = new byte[Math.min(fi.getSize(), 1 << 24)];
            int pos = 0;
            int r;
            while ((r = input.read(buffer, pos, buffer.length - pos)) >= 0) {
                pos += r;
                if (pos == buffer.length) {
                    output.write(buffer, 0, pos);
                    pos = 0;
                }
            }
            if (pos != 0) {
                output.write(buffer, 0, pos);
            }
            System.out.println(filePath + ": OK");
        } catch (IOException e) {
            String msg = filePath + ": FAIL: " + e.getClass().getSimpleName();
            if (e.getMessage() != null) {
                msg += ": " + e.getMessage();
            }
            errors.add(msg);
        }
    }, executor)).toArray(CompletableFuture[]::new);
    CompletableFuture.allOf(tasks).thenRun(() -> {
        for (String err : errors)
            System.err.println(err);
        executor.shutdown();
    });
}

From source file:edu.harvard.med.iccbl.dev.HibernateConsole.java

public static void main(String[] args) {
    BufferedReader br = null;/*from  w w  w.  j  a va2 s.c om*/
    try {
        CommandLineApplication app = new CommandLineApplication(args);
        app.processOptions(true, false);
        br = new BufferedReader(new InputStreamReader(System.in));

        EntityManagerFactory emf = (EntityManagerFactory) app.getSpringBean("entityManagerFactory");
        EntityManager em = emf.createEntityManager();

        do {
            System.out.println("Enter HQL query (blank to quit): ");
            String input = br.readLine();
            if (input.length() == 0) {
                System.out.println("Goodbye!");
                System.exit(0);
            }
            try {
                List list = ((Session) em.getDelegate()).createQuery(input).list(); // note: this uses the Hibernate Session object, to allow HQL (and JPQL)
                // List list = em.createQuery(input).getResultList();  // note: this JPA method supports JPQL

                System.out.println("Result:");
                for (Iterator iter = list.iterator(); iter.hasNext();) {
                    Object item = iter.next();
                    // format output from multi-item selects ("select a, b, c, ... from ...")
                    if (item instanceof Object[]) {
                        List<Object> fields = Arrays.asList((Object[]) item);
                        System.out.println(StringUtils.makeListString(fields, ", "));
                    }
                    // format output from single-item selected ("select a from ..." or "from ...")
                    else {
                        System.out.println("[" + item.getClass().getName() + "]: " + item);
                    }
                }
                System.out.println("(" + list.size() + " rows)\n");
            } catch (Exception e) {
                System.out.println("Hibernate Error: " + e.getMessage());
                log.error("Hibernate error", e);
            }
            System.out.println();
        } while (true);
    } catch (Exception e) {
        System.err.println("Fatal Error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(br);
    }
}