Example usage for java.lang String toLowerCase

List of usage examples for java.lang String toLowerCase

Introduction

In this page you can find the example usage for java.lang String toLowerCase.

Prototype

public String toLowerCase() 

Source Link

Document

Converts all of the characters in this String to lower case using the rules of the default locale.

Usage

From source file:com.seanmadden.net.fast.SerialInterface.java

public static void main(String[] args) {
    SerialInterface inter = new SerialInterface(new JSONObject());
    inter.open();/*  ww w .j  a  va 2s  .  co  m*/

    System.out.println("Welcome.  Commands with 'help'");
    String cmd = "";
    Scanner scan = new Scanner(System.in);
    do {
        System.out.print("> ");
        cmd = scan.nextLine();
        if (cmd.toLowerCase().equals("help")) {
            System.out.println("Commands:");
            System.out.println("help : prints this message");
            System.out.println("send <message> : sends <message> to interpretype.");
            System.out.println("quit : exits this program");
        } else if (cmd.toLowerCase().startsWith("send")) {
            String message = cmd.substring(cmd.toLowerCase().indexOf(' ') + 1);
            inter.sendDataToPort(message);
        }
    } while (!cmd.toLowerCase().equals("quit"));

    inter.close();
}

From source file:org.apache.flink.benchmark.Runner.java

public static void main(String[] args) throws Exception {
    final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    env.getConfig().enableObjectReuse();
    env.getConfig().disableSysoutLogging();

    ParameterTool parameters = ParameterTool.fromArgs(args);

    if (!(parameters.has("p") && parameters.has("types") && parameters.has("algorithms"))) {
        printUsage();/* www .  j a  va  2 s .c  o m*/
        System.exit(-1);
    }

    int parallelism = parameters.getInt("p");
    env.setParallelism(parallelism);

    Set<IdType> types = new HashSet<>();

    if (parameters.get("types").equals("all")) {
        types.add(IdType.INT);
        types.add(IdType.LONG);
        types.add(IdType.STRING);
    } else {
        for (String type : parameters.get("types").split(",")) {
            if (type.toLowerCase().equals("int")) {
                types.add(IdType.INT);
            } else if (type.toLowerCase().equals("long")) {
                types.add(IdType.LONG);
            } else if (type.toLowerCase().equals("string")) {
                types.add(IdType.STRING);
            } else {
                printUsage();
                throw new RuntimeException("Unknown type: " + type);
            }
        }
    }

    Queue<RunnerWithScore> queue = new PriorityQueue<>();

    if (parameters.get("algorithms").equals("all")) {
        for (Map.Entry<String, Class> entry : AVAILABLE_ALGORITHMS.entrySet()) {
            for (IdType type : types) {
                AlgorithmRunner runner = (AlgorithmRunner) entry.getValue().newInstance();
                runner.initialize(type, SAMPLES, parallelism);
                runner.warmup(env);
                queue.add(new RunnerWithScore(runner, 1.0));
            }
        }
    } else {
        for (String algorithm : parameters.get("algorithms").split(",")) {
            double ratio = 1.0;
            if (algorithm.contains("=")) {
                String[] split = algorithm.split("=");
                algorithm = split[0];
                ratio = Double.parseDouble(split[1]);
            }

            if (AVAILABLE_ALGORITHMS.containsKey(algorithm.toLowerCase())) {
                Class clazz = AVAILABLE_ALGORITHMS.get(algorithm.toLowerCase());

                for (IdType type : types) {
                    AlgorithmRunner runner = (AlgorithmRunner) clazz.newInstance();
                    runner.initialize(type, SAMPLES, parallelism);
                    runner.warmup(env);
                    queue.add(new RunnerWithScore(runner, ratio));
                }
            } else {
                printUsage();
                throw new RuntimeException("Unknown algorithm: " + algorithm);
            }
        }
    }

    JsonFactory factory = new JsonFactory();

    while (queue.size() > 0) {
        RunnerWithScore current = queue.poll();
        AlgorithmRunner runner = current.getRunner();

        StringWriter writer = new StringWriter();
        JsonGenerator gen = factory.createGenerator(writer);
        gen.writeStartObject();
        gen.writeStringField("algorithm", runner.getClass().getSimpleName());

        boolean running = true;

        while (running) {
            try {
                runner.run(env, gen);
                running = false;
            } catch (ProgramInvocationException e) {
                // only suppress job cancellations
                if (!(e.getCause() instanceof JobCancellationException)) {
                    throw e;
                }
            }
        }

        JobExecutionResult result = env.getLastJobExecutionResult();

        long runtime_ms = result.getNetRuntime();
        gen.writeNumberField("runtime_ms", runtime_ms);
        current.credit(runtime_ms);

        if (!runner.finished()) {
            queue.add(current);
        }

        gen.writeObjectFieldStart("accumulators");
        for (Map.Entry<String, Object> accumulatorResult : result.getAllAccumulatorResults().entrySet()) {
            gen.writeStringField(accumulatorResult.getKey(), accumulatorResult.getValue().toString());
        }
        gen.writeEndObject();

        gen.writeEndObject();
        gen.close();
        System.out.println(writer.toString());
    }
}

From source file:DIA_Umpire_Quant.DIA_Umpire_LCMSIDGen.java

/**
 * @param args the command line arguments
 *///from   w w w  .j  a  v  a  2  s.c  o m
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println("DIA-Umpire LCMSID geneartor (version: " + UmpireInfo.GetInstance().Version + ")");
    if (args.length != 1) {
        System.out.println(
                "command format error, the correct format should be: java -jar -Xmx10G DIA_Umpire_LCMSIDGen.jar diaumpire_module.params");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.INFO);
        ConsoleLogger.SetFileLogger(Level.DEBUG,
                FilenameUtils.getFullPath(args[0]) + "diaumpire_lcmsidgen.log");
    } catch (Exception e) {
    }

    Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version);
    Logger.getRootLogger().info("Parameter file:" + args[0]);

    BufferedReader reader = new BufferedReader(new FileReader(args[0]));
    String line = "";
    String WorkFolder = "";
    int NoCPUs = 2;

    TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
    HashMap<String, File> AssignFiles = new HashMap<>();

    //<editor-fold defaultstate="collapsed" desc="Reading parameter file">
    while ((line = reader.readLine()) != null) {
        line = line.trim();
        Logger.getRootLogger().info(line);
        if (!"".equals(line) && !line.startsWith("#")) {
            //System.out.println(line);
            if (line.equals("==File list begin")) {
                do {
                    line = reader.readLine();
                    line = line.trim();
                    if (line.equals("==File list end")) {
                        continue;
                    } else if (!"".equals(line)) {
                        File newfile = new File(line);
                        if (newfile.exists()) {
                            AssignFiles.put(newfile.getAbsolutePath(), newfile);
                        } else {
                            Logger.getRootLogger().info("File: " + newfile + " does not exist.");
                        }
                    }
                } while (!line.equals("==File list end"));
            }
            if (line.split("=").length < 2) {
                continue;
            }
            String type = line.split("=")[0].trim();
            String value = line.split("=")[1].trim();
            switch (type) {
            case "Path": {
                WorkFolder = value;
                break;
            }
            case "path": {
                WorkFolder = value;
                break;
            }
            case "Thread": {
                NoCPUs = Integer.parseInt(value);
                break;
            }
            case "DecoyPrefix": {
                if (!"".equals(value)) {
                    tandemPara.DecoyPrefix = value;
                }
                break;
            }
            case "PeptideFDR": {
                tandemPara.PepFDR = Float.parseFloat(value);
                break;
            }
            }
        }
    }
    //</editor-fold>

    //Initialize PTM manager using compomics library
    PTMManager.GetInstance();

    //Generate DIA file list
    ArrayList<DIAPack> FileList = new ArrayList<>();

    File folder = new File(WorkFolder);
    if (!folder.exists()) {
        Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found.");
        System.exit(1);
    }
    for (final File fileEntry : folder.listFiles()) {
        if (fileEntry.isFile()
                && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                        | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
            AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry);
        }
        if (fileEntry.isDirectory()) {
            for (final File fileEntry2 : fileEntry.listFiles()) {
                if (fileEntry2.isFile()
                        && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                                | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                        && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                        && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                        && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                    AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2);
                }
            }
        }
    }

    Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size());
    for (File fileEntry : AssignFiles.values()) {
        Logger.getRootLogger().info(fileEntry.getAbsolutePath());
    }

    //process each DIA file to genearate untargeted identifications
    for (File fileEntry : AssignFiles.values()) {
        String mzXMLFile = fileEntry.getAbsolutePath();
        if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) {
            long time = System.currentTimeMillis();

            DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs);
            FileList.add(DiaFile);
            Logger.getRootLogger().info(
                    "=================================================================================================");
            Logger.getRootLogger().info("Processing " + mzXMLFile);
            if (!DiaFile.LoadDIASetting()) {
                Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete");
                System.exit(1);
            }
            if (!DiaFile.LoadParams()) {
                Logger.getRootLogger().info("Loading parameters failed, job is incomplete");
                System.exit(1);
            }
            Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "....");

            DiaFile.ParsePepXML(tandemPara, null);
            DiaFile.BuildStructure();
            if (!DiaFile.MS1FeatureMap.ReadPeakCluster()) {
                Logger.getRootLogger().info("Loading peak and structure failed, job is incomplete");
                System.exit(1);
            }
            DiaFile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster();
            //Generate mapping between index of precursor feature and pseudo MS/MS scan index 
            DiaFile.GenerateClusterScanNomapping();
            //Doing quantification
            DiaFile.AssignQuant();
            DiaFile.ClearStructure();

            DiaFile.IDsummary.ReduceMemoryUsage();
            time = System.currentTimeMillis() - time;
            Logger.getRootLogger().info(mzXMLFile + " processed time:"
                    + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time),
                            TimeUnit.MILLISECONDS.toMinutes(time)
                                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)),
                            TimeUnit.MILLISECONDS.toSeconds(time)
                                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))));
        }
        Logger.getRootLogger().info("Job done");
        Logger.getRootLogger().info(
                "=================================================================================================");
    }
}

From source file:me.timothy.ddd.DrunkDuckDispatch.java

License:asdf

public static void main(String[] args) throws LWJGLException {
    try {/*www. j  a  v a2s .  c  om*/
        float defaultDisplayWidth = SizeScaleSystem.EXPECTED_WIDTH / 2;
        float defaultDisplayHeight = SizeScaleSystem.EXPECTED_HEIGHT / 2;
        boolean fullscreen = false, defaultDisplay = !fullscreen;
        File resolutionInfo = new File("graphics.json");

        if (resolutionInfo.exists()) {
            try (FileReader fr = new FileReader(resolutionInfo)) {
                JSONObject obj = (JSONObject) new JSONParser().parse(fr);
                Set<?> keys = obj.keySet();
                for (Object o : keys) {
                    if (o instanceof String) {
                        String key = (String) o;
                        switch (key.toLowerCase()) {
                        case "width":
                            defaultDisplayWidth = JSONCompatible.getFloat(obj, key);
                            break;
                        case "height":
                            defaultDisplayHeight = JSONCompatible.getFloat(obj, key);
                            break;
                        case "fullscreen":
                            fullscreen = JSONCompatible.getBoolean(obj, key);
                            defaultDisplay = !fullscreen;
                            break;
                        }
                    }
                }
            } catch (IOException | ParseException e) {
                e.printStackTrace();
            }
            float expHeight = defaultDisplayWidth
                    * (SizeScaleSystem.EXPECTED_HEIGHT / SizeScaleSystem.EXPECTED_WIDTH);
            float expWidth = defaultDisplayHeight
                    * (SizeScaleSystem.EXPECTED_WIDTH / SizeScaleSystem.EXPECTED_HEIGHT);
            if (Math.round(defaultDisplayWidth) != Math.round(expWidth)) {
                if (defaultDisplayHeight < expHeight) {
                    System.err.printf("%f x %f is an invalid resolution; adjusting to %f x %f\n",
                            defaultDisplayWidth, defaultDisplayHeight, defaultDisplayWidth, expHeight);
                    defaultDisplayHeight = expHeight;
                } else {
                    System.err.printf("%f x %f is an invalid resolution; adjusting to %f x %f\n",
                            defaultDisplayWidth, defaultDisplayHeight, expWidth, defaultDisplayHeight);
                    defaultDisplayWidth = expWidth;
                }
            }
        }
        File dir = null;
        String os = getOS();
        if (os.equals("windows")) {
            dir = new File(System.getenv("APPDATA"), "timgames/");
        } else {
            dir = new File(System.getProperty("user.home"), ".timgames/");
        }
        File lwjglDir = new File(dir, "lwjgl-2.9.1/");
        Resources.init();
        Resources.downloadIfNotExists(lwjglDir, "lwjgl-2.9.1.zip", "http://umad-barnyard.com/lwjgl-2.9.1.zip",
                "Necessary LWJGL natives couldn't be found, I can attempt "
                        + "to download it, but I make no promises",
                "Unfortunately I was unable to download it, so I'll open up the "
                        + "link to the official download. Make sure you get LWJGL version 2.9.1, "
                        + "and you put it at " + dir.getAbsolutePath() + "/lwjgl-2.9.1.zip",
                new Runnable() {

                    @Override
                    public void run() {
                        if (!Desktop.isDesktopSupported()) {
                            JOptionPane.showMessageDialog(null,
                                    "I couldn't " + "even do that! Download it manually and try again");
                            return;
                        }

                        try {
                            Desktop.getDesktop().browse(new URI("http://www.lwjgl.org/download.php"));
                        } catch (IOException | URISyntaxException e) {
                            JOptionPane.showMessageDialog(null,
                                    "Oh cmon.. Address is http://www.lwjgl.org/download.php, good luck");
                            System.exit(1);
                        }
                    }

                }, 5843626);

        Resources.extractIfNotFound(lwjglDir, "lwjgl-2.9.1.zip", "lwjgl-2.9.1");
        System.setProperty("org.lwjgl.librarypath",
                new File(dir, "lwjgl-2.9.1/lwjgl-2.9.1/native/" + os).getAbsolutePath()); // deal w/ it
        System.setProperty("net.java.games.input.librarypath", System.getProperty("org.lwjgl.librarypath"));

        Resources.downloadIfNotExists("entities.json", "http://umad-barnyard.com/ddd/entities.json", 16142);
        Resources.downloadIfNotExists("map.binary", "http://umad-barnyard.com/ddd/map.binary", 16142);
        Resources.downloadIfNotExists("victory.txt", "http://umad-barnyard.com/ddd/victory.txt", 168);
        Resources.downloadIfNotExists("failure.txt", "http://umad-barnyard.com/ddd/failure.txt", 321);
        File resFolder = new File("resources/");
        if (!resFolder.exists() && !new File("player-still.png").exists()) {
            Resources.downloadIfNotExists("resources.zip", "http://umad-barnyard.com/ddd/resources.zip", 54484);
            Resources.extractIfNotFound(new File("."), "resources.zip", "player-still.png");
            new File("resources.zip").delete();
        }
        File soundFolder = new File("sounds/");
        if (!soundFolder.exists()) {
            soundFolder.mkdirs();
            Resources.downloadIfNotExists("sounds/sounds.zip", "http://umad-barnyard.com/ddd/sounds.zip",
                    1984977);
            Resources.extractIfNotFound(soundFolder, "sounds.zip", "asdfasdffadasdf");
            new File(soundFolder, "sounds.zip").delete();
        }
        AppGameContainer appgc;
        ddd = new DrunkDuckDispatch();
        appgc = new AppGameContainer(ddd);
        appgc.setTargetFrameRate(60);
        appgc.setShowFPS(false);
        appgc.setAlwaysRender(true);
        if (fullscreen) {
            DisplayMode[] modes = Display.getAvailableDisplayModes();
            DisplayMode current, best = null;
            float ratio = 0f;
            for (int i = 0; i < modes.length; i++) {
                current = modes[i];
                float rX = (float) current.getWidth() / SizeScaleSystem.EXPECTED_WIDTH;
                float rY = (float) current.getHeight() / SizeScaleSystem.EXPECTED_HEIGHT;
                System.out.println(current.getWidth() + "x" + current.getHeight() + " -> " + rX + "x" + rY);
                if (rX == rY && rX > ratio) {
                    best = current;
                    ratio = rX;
                }
            }
            if (best == null) {
                System.out.println("Failed to find an appropriately scaled resolution, using default display");
                defaultDisplay = true;
            } else {
                appgc.setDisplayMode(best.getWidth(), best.getHeight(), true);
                SizeScaleSystem.setRealHeight(best.getHeight());
                SizeScaleSystem.setRealWidth(best.getWidth());
                System.out.println("I choose " + best.getWidth() + "x" + best.getHeight());
            }
        }

        if (defaultDisplay) {
            SizeScaleSystem.setRealWidth(Math.round(defaultDisplayWidth));
            SizeScaleSystem.setRealHeight(Math.round(defaultDisplayHeight));
            appgc.setDisplayMode(Math.round(defaultDisplayWidth), Math.round(defaultDisplayHeight), false);
        }
        ddd.logger.info(
                "SizeScaleSystem: " + SizeScaleSystem.getRealWidth() + "x" + SizeScaleSystem.getRealHeight());
        appgc.start();
    } catch (SlickException ex) {
        LogManager.getLogger(DrunkDuckDispatch.class.getSimpleName()).catching(Level.ERROR, ex);
    }
}

From source file:com.betfair.cougar.test.socket.app.SocketCompatibilityTestingApp.java

public static void main(String[] args) throws Exception {

    Parser parser = new PosixParser();
    Options options = new Options();
    options.addOption("r", "repo", true, "Repository type to search: local|central");
    options.addOption("c", "client-concurrency", true,
            "Max threads to allow each client tester to run tests, defaults to 10");
    options.addOption("t", "test-concurrency", true, "Max client testers to run concurrently, defaults to 5");
    options.addOption("m", "max-time", true,
            "Max time (in minutes) to allow tests to complete, defaults to 10");
    options.addOption("v", "version", false, "Print version and exit");
    options.addOption("h", "help", false, "This help text");
    CommandLine commandLine = parser.parse(options, args);
    if (commandLine.hasOption("h")) {
        System.out.println(options);
        System.exit(0);/*from   w w w  .  ja va 2  s.c o m*/
    }
    if (commandLine.hasOption("v")) {
        System.out.println("How the hell should I know?");
        System.exit(0);
    }
    // 1. Find all testers in given repos
    List<RepoSearcher> repoSearchers = new ArrayList<>();
    for (String repo : commandLine.getOptionValues("r")) {
        if ("local".equals(repo.toLowerCase())) {
            repoSearchers.add(new LocalRepoSearcher());
        } else if ("central".equals(repo.toLowerCase())) {
            repoSearchers.add(new CentralRepoSearcher());
        } else {
            System.err.println("Unrecognized repo: " + repo);
            System.err.println(options);
            System.exit(1);
        }
    }
    int clientConcurrency = 10;
    if (commandLine.hasOption("c")) {
        try {
            clientConcurrency = Integer.parseInt(commandLine.getOptionValue("c"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "client-concurrency is not a valid integer: '" + commandLine.getOptionValue("c") + "'");
            System.exit(1);
        }
    }
    int testConcurrency = 5;
    if (commandLine.hasOption("t")) {
        try {
            testConcurrency = Integer.parseInt(commandLine.getOptionValue("t"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "test-concurrency is not a valid integer: '" + commandLine.getOptionValue("t") + "'");
            System.exit(1);
        }
    }
    int maxMinutes = 10;
    if (commandLine.hasOption("m")) {
        try {
            maxMinutes = Integer.parseInt(commandLine.getOptionValue("m"));
        } catch (NumberFormatException nfe) {
            System.err.println("max-time is not a valid integer: '" + commandLine.getOptionValue("m") + "'");
            System.exit(1);
        }
    }

    Properties clientProps = new Properties();
    clientProps.setProperty("client.concurrency", String.valueOf(clientConcurrency));

    File baseRunDir = new File(System.getProperty("user.dir") + "/run");
    baseRunDir.mkdirs();

    File tmpDir = new File(baseRunDir, "jars");
    tmpDir.mkdirs();

    List<ServerRunner> serverRunners = new ArrayList<>();
    List<ClientRunner> clientRunners = new ArrayList<>();
    for (RepoSearcher searcher : repoSearchers) {
        List<File> jars = searcher.findAndCache(tmpDir);
        for (File f : jars) {
            ServerRunner serverRunner = new ServerRunner(f, baseRunDir);
            System.out.println("Found tester: " + serverRunner.getVersion());
            serverRunners.add(serverRunner);
            clientRunners.add(new ClientRunner(f, baseRunDir, clientProps));
        }
    }

    // 2. Start servers and collect ports
    System.out.println();
    System.out.println("Starting " + serverRunners.size() + " servers...");
    for (ServerRunner server : serverRunners) {
        server.startServer();
    }
    System.out.println();

    List<TestCombo> tests = new ArrayList<>(serverRunners.size() * clientRunners.size());
    for (ServerRunner server : serverRunners) {
        for (ClientRunner client : clientRunners) {
            tests.add(new TestCombo(server, client));
        }
    }

    System.out.println("Enqueued " + tests.size() + " test combos to run...");

    long startTime = System.currentTimeMillis();
    // 3. Run every client against every server, collecting results
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(serverRunners.size() * clientRunners.size());
    ThreadPoolExecutor service = new ThreadPoolExecutor(testConcurrency, testConcurrency, 5000,
            TimeUnit.MILLISECONDS, workQueue);
    service.prestartAllCoreThreads();
    workQueue.addAll(tests);
    while (!workQueue.isEmpty()) {
        Thread.sleep(1000);
    }
    service.shutdown();
    service.awaitTermination(maxMinutes, TimeUnit.MINUTES);
    long endTime = System.currentTimeMillis();
    long totalTimeSecs = Math.round((endTime - startTime) / 1000.0);
    for (ServerRunner server : serverRunners) {
        server.shutdownServer();
    }

    System.out.println();
    System.out.println("=======");
    System.out.println("Results");
    System.out.println("-------");
    // print a summary
    int totalTests = 0;
    int totalSuccess = 0;
    for (TestCombo combo : tests) {
        String clientVer = combo.getClientVersion();
        String serverVer = combo.getServerVersion();
        String results = combo.getClientResults();
        ObjectMapper mapper = new ObjectMapper(new JsonFactory());
        JsonNode node = mapper.reader().readTree(results);
        JsonNode resultsArray = node.get("results");
        int numTests = resultsArray.size();
        int numSuccess = 0;
        for (int i = 0; i < numTests; i++) {
            if ("success".equals(resultsArray.get(i).get("result").asText())) {
                numSuccess++;
            }
        }
        totalSuccess += numSuccess;
        totalTests += numTests;
        System.out.println(clientVer + "/" + serverVer + ": " + numSuccess + "/" + numTests
                + " succeeded - took " + String.format("%2f", combo.getRunningTime()) + " seconds");
    }
    System.out.println("-------");
    System.out.println(
            "Overall: " + totalSuccess + "/" + totalTests + " succeeded - took " + totalTimeSecs + " seconds");

    FileWriter out = new FileWriter("results.json");
    PrintWriter pw = new PrintWriter(out);

    // 4. Output full results
    pw.println("{\n  \"results\": [");
    for (TestCombo combo : tests) {
        combo.emitResults(pw, "    ");
    }
    pw.println("  ],");
    pw.println("  \"servers\": [");
    for (ServerRunner server : serverRunners) {
        server.emitInfo(pw, "    ");
    }
    pw.println("  ],");
    pw.close();
}

From source file:POP3Demo.java

public static void main(String[] args) throws Exception {
    int POP3Port = 110;
    Socket client = new Socket("127.0.0.1", POP3Port);
    InputStream is = client.getInputStream();
    BufferedReader sockin = new BufferedReader(new InputStreamReader(is));
    OutputStream os = client.getOutputStream();
    PrintWriter sockout = new PrintWriter(os, true);
    String cmd = "user Smith";
    sockout.println(cmd);/*from w w  w .  ja va2  s. co  m*/
    String reply = sockin.readLine();
    cmd = "pass ";
    sockout.println(cmd + "popPassword");
    reply = sockin.readLine();
    cmd = "stat";
    sockout.println(cmd);
    reply = sockin.readLine();
    if (reply == null)
        return;
    cmd = "retr 1";
    sockout.println(cmd);
    if (cmd.toLowerCase().startsWith("retr") && reply.charAt(0) == '+')
        do {
            reply = sockin.readLine();
            System.out.println("S:" + reply);
            if (reply != null && reply.length() > 0)
                if (reply.charAt(0) == '.')
                    break;
        } while (true);
    cmd = "quit";
    sockout.println(cmd);
    client.close();
}

From source file:com.github.braully.graph.UtilResult.java

public static void main(String... args) throws Exception {
    Options options = new Options();

    Option input = new Option("i", "input", true, "input file path");
    input.setRequired(false);//w w w  . ja  v a 2s . co  m
    options.addOption(input);

    Option verb = new Option("v", "verbose", false, "verbose process");
    input.setRequired(false);
    options.addOption(verb);

    Option output = new Option("o", "output", true, "output file");
    output.setRequired(false);
    options.addOption(output);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("UtilResult", options);

        System.exit(1);
        return;
    }

    String inputFilePath = cmd.getOptionValue("input");
    if (inputFilePath == null) {
        inputFilePath = "/home/strike/grafos-para-processar/mft2/resultado.txt";
    }
    if (inputFilePath != null) {
        if (inputFilePath.toLowerCase().endsWith(".txt")) {
            processFileTxt(inputFilePath);
        } else if (inputFilePath.toLowerCase().endsWith(".json")) {
            processFileJson(inputFilePath);
        }
    }
}

From source file:kindleclippings.word.QuizletSync.java

public static void main(String[] args) throws IOException, JSONException, URISyntaxException,
        InterruptedException, BackingStoreException, BadLocationException {

    JFileChooser fc = new JFileChooser();
    fc.setFileFilter(new FileNameExtensionFilter("Word documents", "doc", "rtf", "txt"));
    fc.setMultiSelectionEnabled(true);//from ww w .  j ava2  s .c o m
    int result = fc.showOpenDialog(null);
    if (result != JFileChooser.APPROVE_OPTION) {
        return;
    }
    File[] clf = fc.getSelectedFiles();
    if (clf == null || clf.length == 0)
        return;

    ProgressMonitor progress = new ProgressMonitor(null, "QuizletSync", "loading notes files", 0, 100);
    progress.setMillisToPopup(0);
    progress.setMillisToDecideToPopup(0);
    progress.setProgress(0);
    try {

        progress.setNote("checking Quizlet account");
        progress.setProgress(5);

        Preferences prefs = kindleclippings.quizlet.QuizletSync.getPrefs();

        QuizletAPI api = new QuizletAPI(prefs.get("access_token", null));

        Collection<TermSet> sets = null;
        try {
            progress.setNote("checking Quizlet library");
            progress.setProgress(10);
            sets = api.getSets(prefs.get("user_id", null));
        } catch (IOException e) {
            if (e.toString().contains("401")) {
                // Not Authorized => Token has been revoked
                kindleclippings.quizlet.QuizletSync.clearPrefs();
                prefs = kindleclippings.quizlet.QuizletSync.getPrefs();
                api = new QuizletAPI(prefs.get("access_token", null));
                sets = api.getSets(prefs.get("user_id", null));
            } else {
                throw e;
            }
        }

        progress.setProgress(15);
        progress.setMaximum(15 + clf.length * 10);
        progress.setNote("uploading new notes");

        int pro = 15;

        int addedSets = 0;
        int updatedTerms = 0;
        int updatedSets = 0;

        for (File f : clf) {
            progress.setProgress(pro);
            List<Clipping> clippings = readClippingsFile(f);

            if (clippings == null) {
                pro += 10;
                continue;
            }

            if (clippings.isEmpty()) {
                pro += 10;
                continue;
            }

            if (clippings.size() < 2) {
                pro += 10;
                continue;
            }

            String book = clippings.get(0).getBook();
            progress.setNote(book);

            TermSet termSet = null;
            String x = book.toLowerCase().replaceAll("\\W", "");

            for (TermSet t : sets) {
                if (t.getTitle().toLowerCase().replaceAll("\\W", "").equals(x)) {
                    termSet = t;
                    break;
                }
            }

            if (termSet == null) {

                addSet(api, book, clippings);
                addedSets++;
                pro += 10;
                continue;
            }

            // compare against existing terms
            boolean hasUpdated = false;
            for (Clipping cl : clippings) {
                if (!kindleclippings.quizlet.QuizletSync.checkExistingTerm(cl, termSet)) {
                    kindleclippings.quizlet.QuizletSync.addTerm(api, termSet, cl);
                    updatedTerms++;
                    hasUpdated = true;
                }
            }

            pro += 10;

            if (hasUpdated)
                updatedSets++;

        }

        if (updatedTerms == 0 && addedSets == 0) {
            JOptionPane.showMessageDialog(null, "Done.\nNo new data was uploaded", "QuizletSync",
                    JOptionPane.OK_OPTION);
        } else {
            if (addedSets > 0) {
                JOptionPane.showMessageDialog(null,
                        String.format("Done.\nCreated %d new sets and added %d cards to %d existing sets",
                                addedSets, updatedSets, updatedTerms),
                        "QuizletSync", JOptionPane.OK_OPTION);
            } else {
                JOptionPane.showMessageDialog(null,
                        String.format("Done.\nAdded %d cards to %d existing sets", updatedTerms, updatedSets),
                        "QuizletSync", JOptionPane.OK_OPTION);
            }
        }
    } finally {
        progress.close();
    }

    System.exit(0);
}

From source file:com.genentech.chemistry.tool.align.SDFAlign.java

public static void main(String... args) {
    Options options = new Options();
    Option opt = new Option("in", true, "input sd file");
    opt.setRequired(true);/*from  w  ww .  ja  va  2 s  .  c om*/
    options.addOption(opt);

    opt = new Option("out", true, "output file");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("method", true, "fss|sss|MCS|clique (default mcs).");
    options.addOption(opt);

    opt = new Option("ref", true,
            "reference molecule if not given first in file is used. If multiple ref molecules are read the min RMSD is reported");
    options.addOption(opt);

    opt = new Option("mirror", false, "If given and the molecule is not chiral, return best mirror image.");
    options.addOption(opt);

    opt = new Option("rmsdTag", true, "Tagname for output of rmsd, default: no output.");
    options.addOption(opt);

    opt = new Option("atomMatch", true,
            "Sequence of none|default|hcount|noAromatic specifing how atoms are matched cf. oe document.\n"
                    + "noAromatic can be used to make terminal atoms match aliphatic and aromatic atoms.\n"
                    + "Queryfeatures are considered only if default is used.");
    options.addOption(opt);

    opt = new Option("bondMatch", true,
            "Sequence of none|default specifing how bonds are matched cf. oe document.");
    options.addOption(opt);

    opt = new Option("keepCoreHydrogens", false,
            "If not specified the hydrigen atoms are removed from the core.");
    options.addOption(opt);

    opt = new Option("outputMol", true, "aligned|original (def: aligned) use original to just compute rmsd.");
    options.addOption(opt);

    opt = new Option("doNotOptimize", false,
            "If specified the RMSD is computed without moving optimizing the overlay.");
    options.addOption(opt);

    opt = new Option("quiet", false, "Reduced warining messages");
    options.addOption(opt);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        exitWithHelp(e.getMessage(), options);
    }

    if (cmd.getArgs().length > 0)
        exitWithHelp("To many arguments", options);

    // do not check aromaticity on atoms so that a terminal atom matches aromatic and non aromatic atoms
    int atomExpr = OEExprOpts.DefaultAtoms;
    int bondExpr = OEExprOpts.DefaultBonds;

    String atomMatch = cmd.getOptionValue("atomMatch");
    if (atomMatch == null)
        atomMatch = "";
    atomMatch = '|' + atomMatch.toLowerCase() + '|';

    String bondMatch = cmd.getOptionValue("bondMatch");
    if (bondMatch == null)
        bondMatch = "";
    bondMatch = '|' + bondMatch.toLowerCase() + '|';

    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String refFile = cmd.getOptionValue("ref");
    String method = cmd.getOptionValue("method");
    String rmsdTag = cmd.getOptionValue("rmsdTag");
    String oMol = cmd.getOptionValue("outputMol");
    boolean doMirror = cmd.hasOption("mirror");
    boolean doOptimize = !cmd.hasOption("doNotOptimize");
    boolean quiet = cmd.hasOption("quiet");

    OUTType outputMol = oMol == null ? OUTType.ALIGNED : OUTType.valueOf(oMol.toUpperCase());

    if (atomMatch.startsWith("|none"))
        atomExpr = 0;
    if (atomMatch.contains("|hcount|"))
        atomExpr |= OEExprOpts.HCount;
    if (atomMatch.contains("|noAromatic|"))
        atomExpr &= (~OEExprOpts.Aromaticity);

    if (bondMatch.startsWith("|none"))
        bondExpr = 0;

    ArrayList<OEMol> refmols = new ArrayList<OEMol>();
    if (refFile != null) {
        oemolistream reffs = new oemolistream(refFile);
        if (!is3DFormat(reffs.GetFormat()))
            oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates");
        reffs.SetFormat(OEFormat.MDL);

        int aromodel = OEIFlavor.Generic.OEAroModelOpenEye;
        int qflavor = reffs.GetFlavor(reffs.GetFormat());
        reffs.SetFlavor(reffs.GetFormat(), (qflavor | aromodel));

        OEMol rmol = new OEMol();
        while (oechem.OEReadMDLQueryFile(reffs, rmol)) {
            if (!cmd.hasOption("keepCoreHydrogens"))
                oechem.OESuppressHydrogens(rmol);
            refmols.add(rmol);
            rmol = new OEMol();
        }
        rmol.delete();

        if (refmols.size() == 0)
            throw new Error("reference file had no entries");

        reffs.close();
    }

    oemolistream fitfs = new oemolistream(inFile);
    if (!is3DFormat(fitfs.GetFormat()))
        oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates");

    oemolostream ofs = new oemolostream(outFile);
    if (!is3DFormat(ofs.GetFormat()))
        oechem.OEThrow.Fatal("Invalid output format: need 3D coordinates");

    AlignInterface aligner = null;
    OEGraphMol fitmol = new OEGraphMol();

    if (oechem.OEReadMolecule(fitfs, fitmol)) {
        if (refmols.size() == 0) {
            OEMol rmol = new OEMol(fitmol);
            if (!cmd.hasOption("keepCoreHydrogens"))
                oechem.OESuppressHydrogens(rmol);

            refmols.add(rmol);
        }

        if ("sss".equalsIgnoreCase(method)) {
            aligner = new SSSAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr,
                    quiet);

        } else if ("clique".equalsIgnoreCase(method)) {
            aligner = new CliqueAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr,
                    quiet);

        } else if ("fss".equalsIgnoreCase(method)) {
            if (cmd.hasOption("atomMatch") || cmd.hasOption("bondMatch"))
                exitWithHelp("method fss does not support '-atomMatch' or '-bondMatch'", options);
            aligner = new FSSAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror);

        } else {
            aligner = new McsAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr,
                    quiet);
        }

        do {
            aligner.align(fitmol);
            oechem.OEWriteMolecule(ofs, fitmol);
        } while (oechem.OEReadMolecule(fitfs, fitmol));

    }

    fitmol.delete();
    if (aligner != null)
        aligner.close();
    for (OEMolBase mol : refmols)
        mol.delete();
    fitfs.close();
    ofs.close();
}

From source file:com.nextdoor.bender.Bender.java

/**
 * Main entrypoint for the Bender CLI tool - handles the argument parsing and triggers the
 * appropriate methods for ultimately invoking a Bender Handler.
 *
 * @param args/*from  www  .  j ava  2 s.co m*/
 * @throws ParseException
 */
public static void main(String[] args) throws ParseException {

    /*
     * Create the various types of options that we support
     */
    Option help = Option.builder("H").longOpt("help").desc("Print this message").build();
    Option handler = Option.builder("h").longOpt("handler").hasArg()
            .desc("Which Event Handler do you want to simulate? \n"
                    + "Your options are: KinesisHandler, S3Handler. \n" + "Default: KinesisHandler")
            .build();
    Option source_file = Option.builder("s").longOpt("source_file").required().hasArg()
            .desc("Reference to the file that you want to process. Usage depends "
                    + "on the Handler you chose. If you chose KinesisHandler "
                    + "then this is a local file (file://path/to/file). If you chose "
                    + "S3Handler, then this is the path to the file in S3 that you want to process "
                    + "(s3://bucket/file...)")
            .build();
    Option kinesis_stream_name = Option.builder().longOpt("kinesis_stream_name").hasArg()
            .desc("What stream name should we mimic? " + "Default: " + KINESIS_STREAM_NAME
                    + " (Kinesis Handler Only)")
            .build();

    /*
     * Build out the option handler and parse the options
     */
    Options options = new Options();
    options.addOption(help);
    options.addOption(handler);
    options.addOption(kinesis_stream_name);
    options.addOption(source_file);

    /*
     * Prepare our help formatter
     */
    HelpFormatter formatter = new HelpFormatter();
    formatter.setWidth(100);
    formatter.setSyntaxPrefix("usage: BENDER_CONFIG=file://config.yaml java -jar");

    /*
     * Parse the options themselves. Throw an error and help if necessary.
     */
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (UnrecognizedOptionException | MissingOptionException | MissingArgumentException e) {
        logger.error(e.getMessage());
        formatter.printHelp(name, options);
        System.exit(1);
    }

    /*
     * The CLI tool doesn't have any configuration files built into it. We require that the user set
     * BENDER_CONFIG to something reasonable.
     */
    if (System.getenv("BENDER_CONFIG") == null) {
        logger.error("You must set the BENDER_CONFIG environment variable. \n"
                + "Valid options include: file://<file>");
        formatter.printHelp(name, options);
        System.exit(1);
    }

    if (cmd.hasOption("help")) {
        formatter.printHelp(name, options);
        System.exit(0);
    }

    /*
     * Depending on the desired Handler, we invoke a specific method and pass in the options (or
     * defaults) required for that handler.
     */
    String handler_value = cmd.getOptionValue(handler.getLongOpt(), KINESIS);
    try {

        switch (handler_value.toLowerCase()) {

        case KINESIS:
            invokeKinesisHandler(cmd.getOptionValue(kinesis_stream_name.getLongOpt(), KINESIS_STREAM_NAME),
                    cmd.getOptionValue(source_file.getLongOpt()));
            break;

        case S3:
            invokeS3Handler(cmd.getOptionValue(source_file.getLongOpt()));
            break;

        /*
         * Error out if an invalid handler was supplied.
         */
        default:
            logger.error("Invalid Handler Option (" + handler_value + "), valid options are: " + KINESIS);
            formatter.printHelp(name, options);
            System.exit(1);
        }
    } catch (HandlerException e) {
        logger.error("Error executing handler: " + e);
        System.exit(1);
    }
}