Example usage for java.lang String startsWith

List of usage examples for java.lang String startsWith

Introduction

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

Prototype

public boolean startsWith(String prefix) 

Source Link

Document

Tests if this string starts with the specified prefix.

Usage

From source file:org.callimachusproject.rdfa.test.RDFaGenerationTest.java

public static void main(String[] args) {
    try {/*from   w  ww .java  2 s.  c  o m*/

        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if (arg.equals("-verbose"))
                verbose = true;
            // just show the generated queries (don't run the test)
            else if (arg.equals("-rdf"))
                show_rdf = true;
            else if (arg.equals("-sparql"))
                show_sparql = true;
            else if (arg.equals("-xml"))
                show_xml = true;
            else if (arg.equals("-results"))
                show_results = true;
            //else if (arg.equals("-legacy")) test_set = "legacy";
            //else if (arg.equals("-construct")) test_set = "construct";
            else if (arg.equals("-select"))
                test_set = "select";
            //else if (arg.equals("-fragment")) test_set = "fragment";
            else if (arg.equals("-data"))
                test_set = "data";
            else if (!arg.startsWith("-"))
                test_dir = arg;
        }

        // run the dynamically generated test-cases
        System.exit(TestRunner.run(RDFaGenerationTest.suite()).wasSuccessful() ? 0 : 1);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.fcrepo.client.test.PerformanceTests.java

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

    if (args.length < 8 || args.length > 9) {
        usage();//from  w  w  w  .  java  2s  .  com
    }

    String host = args[0];
    String port = args[1];
    String username = args[2];
    String password = args[3];
    String itr = args[4];
    String thrds = args[5];
    String output = args[6];
    String name = args[7];
    String context = Constants.FEDORA_DEFAULT_APP_CONTEXT;

    if (args.length == 9 && !args[8].equals("")) {
        context = args[8];
    }

    if (host == null || host.startsWith("$") || port == null || port.startsWith("$") || username == null
            || username.startsWith("$") || password == null || password.startsWith("$") || itr == null
            || itr.startsWith("$") || thrds == null || thrds.startsWith("$") || output == null
            || output.startsWith("$") || name == null || name.startsWith("$")) {
        usage();
    }
    name = name.replaceAll(",", ";");
    iterations = Integer.parseInt(itr);
    threads = Integer.parseInt(thrds);

    boolean newFile = true;
    File outputFile = new File(output);

    File tempFile = null;
    BufferedReader reader = null;
    String line = "";
    if (outputFile.exists()) {
        newFile = false;

        // Create a copy of the file to read from
        tempFile = File.createTempFile("performance-test", "tmp");
        BufferedReader input = new BufferedReader(new FileReader(outputFile));
        PrintStream tempOut = new PrintStream(tempFile);

        while ((line = input.readLine()) != null) {
            tempOut.println(line);
        }
        input.close();
        tempOut.close();

        reader = new BufferedReader(new FileReader(tempFile));
    }
    PrintStream out = new PrintStream(outputFile);

    if (newFile) {
        out.println(
                "--------------------------------------------------------------" + " Performance Test Results "
                        + "--------------------------------------------------------------");
    }

    PerformanceTests tests = new PerformanceTests();
    tests.init(host, port, context, username, password);
    System.out.println("Running Ingest Round-Trip Test...");
    long ingestResults = tests.runIngestTest();
    System.out.println("Running AddDatastream Round-Trip Test...");
    long addDsResults = tests.runAddDatastreamTest();
    System.out.println("Running ModifyDatastreamByReference Round-Trip Test...");
    long modifyRefResults = tests.runModifyDatastreamByRefTest();
    System.out.println("Running ModifyDatastreamByValue Round-Trip Test...");
    long modifyValResults = tests.runModifyDatastreamByValueTest();
    System.out.println("Running PurgeDatastream Round-Trip Test...");
    long purgeDsResults = tests.runPurgeDatastreamTest();
    System.out.println("Running PurgeObject Round-Trip Test...");
    long purgeObjectResults = tests.runPurgeObjectTest();
    System.out.println("Running GetDatastream Round-Trip Test...");
    long getDatastreamResults = tests.runGetDatastreamTest();
    System.out.println("Running GetDatastreamREST Round-Trip Test...");
    long getDatastreamRestResults = tests.runGetDatastreamRestTest();
    System.out.println("Running Throughput Tests...");
    long[] tpResults = tests.runThroughputTests();
    System.out.println("Running Threaded Throughput Tests...");
    long[] tptResults = tests.runThreadedThroughputTests();

    if (newFile) {
        out.println(
                "1. Test performing each operation in isolation. Time (in ms) is the average required to perform each operation.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    out.println(name + ", " + ingestResults + ", " + addDsResults + ", " + modifyRefResults + ", "
            + modifyValResults + ", " + purgeDsResults + ", " + purgeObjectResults + ", "
            + getDatastreamResults / iterations + ", " + getDatastreamRestResults / iterations);

    out.println();
    if (newFile) {
        out.println("2. Operations-Per-Second based on results listed in item 1.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    double ingestPerSecond = 1000 / (double) ingestResults;
    double addDsPerSecond = 1000 / (double) addDsResults;
    double modifyRefPerSecond = 1000 / (double) modifyRefResults;
    double modifyValPerSecond = 1000 / (double) modifyValResults;
    double purgeDsPerSecond = 1000 / (double) purgeDsResults;
    double purgeObjPerSecond = 1000 / (double) purgeObjectResults;
    double getDatastreamPerSecond = 1000 / ((double) getDatastreamResults / iterations);
    double getDatastreamRestPerSecond = 1000 / ((double) getDatastreamRestResults / iterations);
    out.println(name + ", " + round(ingestPerSecond) + ", " + round(addDsPerSecond) + ", "
            + round(modifyRefPerSecond) + ", " + round(modifyValPerSecond) + ", " + round(purgeDsPerSecond)
            + ", " + round(purgeObjPerSecond) + ", " + round(getDatastreamPerSecond) + ", "
            + round(getDatastreamRestPerSecond));

    out.println();
    if (newFile) {
        out.println(
                "3. Test performing operations back-to-back. Time (in ms) is that required to perform all iterations.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    out.println(name + ", " + tpResults[0] + ", " + tpResults[1] + ", " + tpResults[2] + ", " + tpResults[3]
            + ", " + tpResults[4] + ", " + tpResults[5] + ", " + getDatastreamResults + ", "
            + getDatastreamRestResults);

    out.println();
    if (newFile) {
        out.println("4. Operations-Per-Second based on results listed in item 3.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    double ingestItPerSecond = (double) (iterations * 1000) / tpResults[0];
    double addDsItPerSecond = (double) (iterations * 1000) / tpResults[1];
    double modifyRefItPerSecond = (double) (iterations * 1000) / tpResults[2];
    double modifyValItPerSecond = (double) (iterations * 1000) / tpResults[3];
    double purgeDsItPerSecond = (double) (iterations * 1000) / tpResults[4];
    double purgeObjItPerSecond = (double) (iterations * 1000) / tpResults[5];
    double getDsItPerSecond = (double) (iterations * 1000) / getDatastreamResults;
    double getDsRestItPerSecond = (double) (iterations * 1000) / getDatastreamRestResults;
    out.println(name + ", " + round(ingestItPerSecond) + ", " + round(addDsItPerSecond) + ", "
            + round(modifyRefItPerSecond) + ", " + round(modifyValItPerSecond) + ", "
            + round(purgeDsItPerSecond) + ", " + round(purgeObjItPerSecond) + ", " + round(getDsItPerSecond)
            + ", " + round(getDsRestItPerSecond));

    out.println();
    if (newFile) {
        out.println(
                "5. Test performing operations using a thread pool. Time (in ms) is that required to perform all iterations.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    out.println(name + ", " + tptResults[0] + ", " + tptResults[1] + ", " + tptResults[2] + ", " + tptResults[3]
            + ", " + tptResults[4] + ", " + tptResults[5] + ", " + tptResults[6] + ", " + tptResults[7]);

    out.println();
    if (newFile) {
        out.println("6. Operations-Per-Second based on results listed in item 5.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    double thrdIngestItPerSecond = (double) (iterations * 1000) / tptResults[0];
    double thrdAddDsItPerSecond = (double) (iterations * 1000) / tptResults[1];
    double thrdModifyRefItPerSecond = (double) (iterations * 1000) / tptResults[2];
    double thrdModifyValItPerSecond = (double) (iterations * 1000) / tptResults[3];
    double thrdPurgeDsItPerSecond = (double) (iterations * 1000) / tptResults[4];
    double thrdPurgeObjItPerSecond = (double) (iterations * 1000) / tptResults[5];
    double thrdGetDsItPerSecond = (double) (iterations * 1000) / tptResults[6];
    double thrdGetDsRestItPerSecond = (double) (iterations * 1000) / tptResults[7];
    out.println(name + ", " + round(thrdIngestItPerSecond) + ", " + round(thrdAddDsItPerSecond) + ", "
            + round(thrdModifyRefItPerSecond) + ", " + round(thrdModifyValItPerSecond) + ", "
            + round(thrdPurgeDsItPerSecond) + ", " + round(thrdPurgeObjItPerSecond) + ", "
            + round(thrdGetDsItPerSecond) + ", " + round(thrdGetDsRestItPerSecond));

    if (!newFile) {
        reader.close();
        tempFile.delete();
    }
    out.close();

    System.out.println("Performance Tests Complete.");
}

From source file:Writer.java

/** Main program entry point. */
public static void main(String argv[]) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();/*  w w w.ja  va  2 s. c  o  m*/
        System.exit(1);
    }

    // variables
    Writer writer = null;
    XMLReader parser = null;
    boolean namespaces = DEFAULT_NAMESPACES;
    boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES;
    boolean validation = DEFAULT_VALIDATION;
    boolean externalDTD = DEFAULT_LOAD_EXTERNAL_DTD;
    boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
    boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION;
    boolean xincludeProcessing = DEFAULT_XINCLUDE;
    boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS;
    boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE;
    boolean canonical = DEFAULT_CANONICAL;

    // process arguments
    for (int i = 0; i < argv.length; i++) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("p")) {
                // get parser name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -p option.");
                }
                String parserName = argv[i];

                // create parser
                try {
                    parser = XMLReaderFactory.createXMLReader(parserName);
                } catch (Exception e) {
                    try {
                        Parser sax1Parser = ParserFactory.makeParser(parserName);
                        parser = new ParserAdapter(sax1Parser);
                        System.err.println("warning: Features and properties not supported on SAX1 parsers.");
                    } catch (Exception ex) {
                        parser = null;
                        System.err.println("error: Unable to instantiate parser (" + parserName + ")");
                        e.printStackTrace(System.err);
                    }
                }
                continue;
            }
            if (option.equalsIgnoreCase("n")) {
                namespaces = option.equals("n");
                continue;
            }
            if (option.equalsIgnoreCase("np")) {
                namespacePrefixes = option.equals("np");
                continue;
            }
            if (option.equalsIgnoreCase("v")) {
                validation = option.equals("v");
                continue;
            }
            if (option.equalsIgnoreCase("xd")) {
                externalDTD = option.equals("xd");
                continue;
            }
            if (option.equalsIgnoreCase("s")) {
                schemaValidation = option.equals("s");
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("ga")) {
                generateSyntheticAnnotations = option.equals("ga");
                continue;
            }
            if (option.equalsIgnoreCase("dv")) {
                dynamicValidation = option.equals("dv");
                continue;
            }
            if (option.equalsIgnoreCase("xi")) {
                xincludeProcessing = option.equals("xi");
                continue;
            }
            if (option.equalsIgnoreCase("xb")) {
                xincludeFixupBaseURIs = option.equals("xb");
                continue;
            }
            if (option.equalsIgnoreCase("xl")) {
                xincludeFixupLanguage = option.equals("xl");
                continue;
            }
            if (option.equalsIgnoreCase("c")) {
                canonical = option.equals("c");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
        }

        // use default parser?
        if (parser == null) {

            // create parser
            try {
                parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
            } catch (Exception e) {
                System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")");
                e.printStackTrace(System.err);
                continue;
            }
        }

        // set parser features
        try {
            parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + NAMESPACE_PREFIXES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(VALIDATION_FEATURE_ID, validation);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(LOAD_EXTERNAL_DTD_FEATURE_ID, externalDTD);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err
                    .println("warning: Parser does not support feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err
                    .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Parser does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            parser.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }
        try {
            parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Parser does not recognize feature (" + XINCLUDE_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        }

        // setup writer
        if (writer == null) {
            writer = new Writer();
            try {
                writer.setOutput(System.out, "UTF8");
            } catch (UnsupportedEncodingException e) {
                System.err.println("error: Unable to set output. Exiting.");
                System.exit(1);
            }
        }

        // set parser
        parser.setContentHandler(writer);
        parser.setErrorHandler(writer);
        try {
            parser.setProperty(LEXICAL_HANDLER_PROPERTY_ID, writer);
        } catch (SAXException e) {
            // ignore
        }

        // parse file
        writer.setCanonical(canonical);
        try {
            parser.parse(arg);
        } catch (SAXParseException e) {
            // ignore
        } catch (Exception e) {
            System.err.println("error: Parse error occurred - " + e.getMessage());
            if (e instanceof SAXException) {
                Exception nested = ((SAXException) e).getException();
                if (nested != null) {
                    e = nested;
                }
            }
            e.printStackTrace(System.err);
        }
    }

}

From source file:examples.mail.IMAPExportMbox.java

public static void main(String[] args) throws IOException {
    int connect_timeout = CONNECT_TIMEOUT;
    int read_timeout = READ_TIMEOUT;

    int argIdx = 0;
    String eol = EOL_DEFAULT;/*  w ww  . j a v a 2s  . c  o  m*/
    boolean printHash = false;
    boolean printMarker = false;
    int retryWaitSecs = 0;

    for (argIdx = 0; argIdx < args.length; argIdx++) {
        if (args[argIdx].equals("-c")) {
            connect_timeout = Integer.parseInt(args[++argIdx]);
        } else if (args[argIdx].equals("-r")) {
            read_timeout = Integer.parseInt(args[++argIdx]);
        } else if (args[argIdx].equals("-R")) {
            retryWaitSecs = Integer.parseInt(args[++argIdx]);
        } else if (args[argIdx].equals("-LF")) {
            eol = LF;
        } else if (args[argIdx].equals("-CRLF")) {
            eol = CRLF;
        } else if (args[argIdx].equals("-.")) {
            printHash = true;
        } else if (args[argIdx].equals("-X")) {
            printMarker = true;
        } else {
            break;
        }
    }

    final int argCount = args.length - argIdx;

    if (argCount < 2) {
        System.err.println("Usage: IMAPExportMbox [-LF|-CRLF] [-c n] [-r n] [-R n] [-.] [-X]"
                + " imap[s]://user:password@host[:port]/folder/path [+|-]<mboxfile> [sequence-set] [itemnames]");
        System.err.println(
                "\t-LF | -CRLF set end-of-line to LF or CRLF (default is the line.separator system property)");
        System.err.println("\t-c connect timeout in seconds (default 10)");
        System.err.println("\t-r read timeout in seconds (default 10)");
        System.err.println("\t-R temporary failure retry wait in seconds (default 0; i.e. disabled)");
        System.err.println("\t-. print a . for each complete message received");
        System.err.println("\t-X print the X-IMAP line for each complete message received");
        System.err.println(
                "\tthe mboxfile is where the messages are stored; use '-' to write to standard output.");
        System.err.println(
                "\tPrefix filename with '+' to append to the file. Prefix with '-' to allow overwrite.");
        System.err.println(
                "\ta sequence-set is a list of numbers/number ranges e.g. 1,2,3-10,20:* - default 1:*");
        System.err
                .println("\titemnames are the message data item name(s) e.g. BODY.PEEK[HEADER.FIELDS (SUBJECT)]"
                        + " or a macro e.g. ALL - default (INTERNALDATE BODY.PEEK[])");
        System.exit(1);
    }

    final URI uri = URI.create(args[argIdx++]);
    final String file = args[argIdx++];
    String sequenceSet = argCount > 2 ? args[argIdx++] : "1:*";
    final String itemNames;
    // Handle 0, 1 or multiple item names
    if (argCount > 3) {
        if (argCount > 4) {
            StringBuilder sb = new StringBuilder();
            sb.append("(");
            for (int i = 4; i <= argCount; i++) {
                if (i > 4) {
                    sb.append(" ");
                }
                sb.append(args[argIdx++]);
            }
            sb.append(")");
            itemNames = sb.toString();
        } else {
            itemNames = args[argIdx++];
        }
    } else {
        itemNames = "(INTERNALDATE BODY.PEEK[])";
    }

    final boolean checkSequence = sequenceSet.matches("\\d+:(\\d+|\\*)"); // are we expecting a sequence?
    final MboxListener chunkListener;
    if (file.equals("-")) {
        chunkListener = null;
    } else if (file.startsWith("+")) {
        final File mbox = new File(file.substring(1));
        System.out.println("Appending to file " + mbox);
        chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, true)), eol, printHash,
                printMarker, checkSequence);
    } else if (file.startsWith("-")) {
        final File mbox = new File(file.substring(1));
        System.out.println("Writing to file " + mbox);
        chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, false)), eol, printHash,
                printMarker, checkSequence);
    } else {
        final File mbox = new File(file);
        if (mbox.exists()) {
            throw new IOException("mailbox file: " + mbox + " already exists!");
        }
        System.out.println("Creating file " + mbox);
        chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox)), eol, printHash, printMarker,
                checkSequence);
    }

    String path = uri.getPath();
    if (path == null || path.length() < 1) {
        throw new IllegalArgumentException("Invalid folderPath: '" + path + "'");
    }
    String folder = path.substring(1); // skip the leading /

    // suppress login details
    final PrintCommandListener listener = new PrintCommandListener(System.out, true) {
        @Override
        public void protocolReplyReceived(ProtocolCommandEvent event) {
            if (event.getReplyCode() != IMAPReply.PARTIAL) { // This is dealt with by the chunk listener
                super.protocolReplyReceived(event);
            }
        }
    };

    // Connect and login
    final IMAPClient imap = IMAPUtils.imapLogin(uri, connect_timeout * 1000, listener);

    String maxIndexInFolder = null;

    try {

        imap.setSoTimeout(read_timeout * 1000);

        if (!imap.select(folder)) {
            throw new IOException("Could not select folder: " + folder);
        }

        for (String line : imap.getReplyStrings()) {
            maxIndexInFolder = matches(line, PATEXISTS, 1);
            if (maxIndexInFolder != null) {
                break;
            }
        }

        if (chunkListener != null) {
            imap.setChunkListener(chunkListener);
        } // else the command listener displays the full output without processing

        while (true) {
            boolean ok = imap.fetch(sequenceSet, itemNames);
            // If the fetch failed, can we retry?
            if (!ok && retryWaitSecs > 0 && chunkListener != null && checkSequence) {
                final String replyString = imap.getReplyString(); //includes EOL
                if (startsWith(replyString, PATTEMPFAIL)) {
                    System.err.println("Temporary error detected, will retry in " + retryWaitSecs + "seconds");
                    sequenceSet = (chunkListener.lastSeq + 1) + ":*";
                    try {
                        Thread.sleep(retryWaitSecs * 1000);
                    } catch (InterruptedException e) {
                        // ignored
                    }
                } else {
                    throw new IOException(
                            "FETCH " + sequenceSet + " " + itemNames + " failed with " + replyString);
                }
            } else {
                break;
            }
        }

    } catch (IOException ioe) {
        String count = chunkListener == null ? "?" : Integer.toString(chunkListener.total);
        System.err.println("FETCH " + sequenceSet + " " + itemNames + " failed after processing " + count
                + " complete messages ");
        if (chunkListener != null) {
            System.err.println("Last complete response seen: " + chunkListener.lastFetched);
        }
        throw ioe;
    } finally {

        if (printHash) {
            System.err.println();
        }

        if (chunkListener != null) {
            chunkListener.close();
            final Iterator<String> missingIds = chunkListener.missingIds.iterator();
            if (missingIds.hasNext()) {
                StringBuilder sb = new StringBuilder();
                for (;;) {
                    sb.append(missingIds.next());
                    if (!missingIds.hasNext()) {
                        break;
                    }
                    sb.append(",");
                }
                System.err.println("*** Missing ids: " + sb.toString());
            }
        }
        imap.logout();
        imap.disconnect();
    }
    if (chunkListener != null) {
        System.out.println("Processed " + chunkListener.total + " messages.");
    }
    if (maxIndexInFolder != null) {
        System.out.println("Folder contained " + maxIndexInFolder + " messages.");
    }
}

From source file:com.genentech.struchk.oeStruchk.OEStruchk.java

/**
 * Command line interface to {@link OEStruchk}.
 *//*from   w ww  .  j  a  va  2 s.  c o m*/
public static void main(String[] args) throws ParseException, JDOMException, IOException {
    long start = System.currentTimeMillis();
    int nMessages = 0;
    int nErrors = 0;
    int nStruct = 0;
    System.err.printf("OEChem Version: %s\n", oechem.OEChemGetVersion());

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("f", true, "specify the configuration file name");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("noMsg", false, "Do not add any additional sd-tags to the sdf file");
    options.addOption(opt);

    opt = new Option("printRules", true, "Print HTML listing all the rules to filename.");
    options.addOption(opt);

    opt = new Option("errorsAsWarnings", false, "Treat errors as warnings.");
    options.addOption(opt);

    opt = new Option("stopForDebug", false, "Stop and read from stdin for user tu start debugger.");
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    args = cmd.getArgs();

    if (cmd.hasOption("stopForDebug")) {
        BufferedReader localRdr = new BufferedReader(new InputStreamReader(System.in));
        System.err.print("Please press return:");

        localRdr.readLine();
    }

    URL confFile;
    if (cmd.hasOption("f")) {
        confFile = new File(cmd.getOptionValue("f")).toURI().toURL();
    } else {
        confFile = getResourceURL(OEStruchk.class, "Struchk.xml");
    }
    boolean errorsAsWarnings = cmd.hasOption("errorsAsWarnings");

    if (cmd.hasOption("printRules")) {
        String fName = cmd.getOptionValue("printRules");
        PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(fName)));
        OEStruchk structFlagAssigner = new OEStruchk(confFile, CHECKConfig.ASSIGNStructFlag, errorsAsWarnings);
        structFlagAssigner.printRules(out);
        out.close();
        return;
    }

    if (args.length < 1) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("oeStruck", options);
        throw new Error("missing input file\n");
    }

    BufferedReader in = null;
    try {
        in = new BufferedReader(new FileReader(args[0]));
        StringBuilder mol = new StringBuilder();
        StringBuilder data = new StringBuilder();
        PrintStream out = System.out;
        if (args.length > 1)
            out = new PrintStream(args[1]);

        // create OEStruchk from config file
        OEStruchk structFlagAssigner = new OEStruchk(confFile, CHECKConfig.ASSIGNStructFlag, errorsAsWarnings);

        OEStruchk structFlagChecker = new OEStruchk(confFile, CHECKConfig.CHECKStructFlag, errorsAsWarnings);

        Pattern sFlagPat = Pattern.compile("<StructFlag>\\s*([^\\n\\r]+)");
        String line;
        boolean inMolFile = true;
        boolean atEnd = false;
        while (!atEnd) {
            if ((line = in.readLine()) == null) {
                if ("".equals(mol.toString().trim()))
                    break;

                if (!inMolFile)
                    throw new Error("Invalid end of sd file!");

                line = "$$$$";
                atEnd = true;
            }

            if (line.startsWith("$$$$")) {

                OEStruchk oeStruchk;
                StructureFlag sFlag = null;
                Matcher mat = sFlagPat.matcher(data);
                if (!mat.find()) {
                    oeStruchk = structFlagAssigner;
                } else {
                    oeStruchk = structFlagChecker;
                    sFlag = StructureFlag.fromString(mat.group(1));
                }
                if (!oeStruchk.applyRules(mol.toString(), null, sFlag))
                    nErrors++;

                out.print(oeStruchk.getTransformedMolfile(null));

                out.print(data);

                if (!cmd.hasOption("noMsg")) {
                    List<Message> msgs = oeStruchk.getStructureMessages(null);
                    if (msgs.size() > 0) {
                        nMessages += msgs.size();

                        out.println("> <errors_oe2>");
                        for (Message msg : msgs)
                            out.printf("%s: %s\n", msg.getLevel(), msg.getText());
                        out.println();
                    }
                    //System.err.println(oeStruchk.getTransformedMolfile("substance"));
                    out.printf("> <outStereo>\n%s\n\n", oeStruchk.getStructureFlag().getName());
                    out.printf("> <TISM>\n%s\n\n", oeStruchk.getTransformedIsoSmiles(null));
                    out.printf("> <TSMI>\n%s\n\n", oeStruchk.getTransformedSmiles(null));
                    out.printf("> <pISM>\n%s\n\n", oeStruchk.getTransformedIsoSmiles("parent"));
                    out.printf("> <salt>\n%s\n\n", oeStruchk.getSaltCode());
                    out.printf("> <stereoCounts>\n%s.%s\n\n", oeStruchk.countChiralCentersStr(),
                            oeStruchk.countStereoDBondStr());
                }

                out.println(line);
                nStruct++;

                mol.setLength(0);
                data.setLength(0);

                inMolFile = true;
            } else if (!inMolFile || line.startsWith(">")) {
                inMolFile = false;
                data.append(line).append("\n");
            } else {
                mol.append(line).append("\n");
            }
        }

        structFlagAssigner.delete();
        structFlagChecker.delete();

    } catch (Exception e) {
        throw new Error(e);
    } finally {
        System.err.printf("Checked %d structures %d errors, %d messages in %dsec\n", nStruct, nErrors,
                nMessages, (System.currentTimeMillis() - start) / 1000);
        if (in != null)
            in.close();
    }
    if (cmd.hasOption("stopForDebug")) {
        BufferedReader localRdr = new BufferedReader(new InputStreamReader(System.in));
        System.err.print("Please press return:");

        localRdr.readLine();
    }
}

From source file:it.anyplace.sync.client.Main.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("C", "set-config", true, "set config file for s-client");
    options.addOption("c", "config", false, "dump config");
    options.addOption("sp", "set-peers", true, "set peer, or comma-separated list of peers");
    options.addOption("q", "query", true, "query directory server for device id");
    options.addOption("d", "discovery", true, "discovery local network for device id");
    options.addOption("p", "pull", true, "pull file from network");
    options.addOption("P", "push", true, "push file to network");
    options.addOption("o", "output", true, "set output file/directory");
    options.addOption("i", "input", true, "set input file/directory");
    options.addOption("lp", "list-peers", false, "list peer addresses");
    options.addOption("a", "address", true, "use this peer addresses");
    options.addOption("L", "list-remote", false, "list folder (root) content from network");
    options.addOption("I", "list-info", false, "dump folder info from network");
    options.addOption("li", "list-info", false, "list folder info from local db");
    //        options.addOption("l", "list-local", false, "list folder content from local (saved) index");
    options.addOption("s", "search", true, "search local index for <term>");
    options.addOption("D", "delete", true, "push delete to network");
    options.addOption("M", "mkdir", true, "push directory create to network");
    options.addOption("h", "help", false, "print help");
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("s-client", options);
        return;//from   w  w  w.ja  v  a  2  s. c om
    }

    File configFile = cmd.hasOption("C") ? new File(cmd.getOptionValue("C"))
            : new File(System.getProperty("user.home"), ".s-client.properties");
    logger.info("using config file = {}", configFile);
    ConfigurationService configuration = ConfigurationService.newLoader().loadFrom(configFile);
    FileUtils.cleanDirectory(configuration.getTemp());
    KeystoreHandler.newLoader().loadAndStore(configuration);
    if (cmd.hasOption("c")) {
        logger.info("configuration =\n{}", configuration.newWriter().dumpToString());
    } else {
        logger.trace("configuration =\n{}", configuration.newWriter().dumpToString());
    }
    logger.debug("{}", configuration.getStorageInfo().dumpAvailableSpace());

    if (cmd.hasOption("sp")) {
        List<String> peers = Lists.newArrayList(Lists.transform(
                Arrays.<String>asList(cmd.getOptionValue("sp").split(",")), new Function<String, String>() {
                    @Override
                    public String apply(String input) {
                        return input.trim();
                    }
                }));
        logger.info("set peers = {}", peers);
        configuration.edit().setPeers(Collections.<DeviceInfo>emptyList());
        for (String peer : peers) {
            KeystoreHandler.validateDeviceId(peer);
            configuration.edit().addPeers(new DeviceInfo(peer, null));
        }
        configuration.edit().persistNow();
    }

    if (cmd.hasOption("q")) {
        String deviceId = cmd.getOptionValue("q");
        logger.info("query device id = {}", deviceId);
        List<DeviceAddress> deviceAddresses = new GlobalDiscoveryHandler(configuration).query(deviceId);
        logger.info("server response = {}", deviceAddresses);
    }
    if (cmd.hasOption("d")) {
        String deviceId = cmd.getOptionValue("d");
        logger.info("discovery device id = {}", deviceId);
        List<DeviceAddress> deviceAddresses = new LocalDiscorveryHandler(configuration).queryAndClose(deviceId);
        logger.info("local response = {}", deviceAddresses);
    }

    if (cmd.hasOption("p")) {
        String path = cmd.getOptionValue("p");
        logger.info("file path = {}", path);
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        try (SyncthingClient client = new SyncthingClient(configuration);
                BlockExchangeConnectionHandler connectionHandler = client.connectToBestPeer()) {
            InputStream inputStream = client.pullFile(connectionHandler, folder, path).waitForComplete()
                    .getInputStream();
            String fileName = client.getIndexHandler().getFileInfoByPath(folder, path).getFileName();
            File file;
            if (cmd.hasOption("o")) {
                File param = new File(cmd.getOptionValue("o"));
                file = param.isDirectory() ? new File(param, fileName) : param;
            } else {
                file = new File(fileName);
            }
            FileUtils.copyInputStreamToFile(inputStream, file);
            logger.info("saved file to = {}", file.getAbsolutePath());
        }
    }
    if (cmd.hasOption("P")) {
        String path = cmd.getOptionValue("P");
        File file = new File(cmd.getOptionValue("i"));
        checkArgument(!path.startsWith("/")); //TODO check path syntax
        logger.info("file path = {}", path);
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        try (SyncthingClient client = new SyncthingClient(configuration);
                BlockPusher.FileUploadObserver fileUploadObserver = client.pushFile(new FileInputStream(file),
                        folder, path)) {
            while (!fileUploadObserver.isCompleted()) {
                fileUploadObserver.waitForProgressUpdate();
                logger.debug("upload progress {}", fileUploadObserver.getProgressMessage());
            }
            logger.info("uploaded file to network");
        }
    }
    if (cmd.hasOption("D")) {
        String path = cmd.getOptionValue("D");
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        logger.info("delete path = {}", path);
        try (SyncthingClient client = new SyncthingClient(configuration);
                IndexEditObserver observer = client.pushDelete(folder, path)) {
            observer.waitForComplete();
            logger.info("deleted path");
        }
    }
    if (cmd.hasOption("M")) {
        String path = cmd.getOptionValue("M");
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        logger.info("dir path = {}", path);
        try (SyncthingClient client = new SyncthingClient(configuration);
                IndexEditObserver observer = client.pushDir(folder, path)) {
            observer.waitForComplete();
            logger.info("uploaded dir to network");
        }
    }
    if (cmd.hasOption("L")) {
        try (SyncthingClient client = new SyncthingClient(configuration)) {
            client.waitForRemoteIndexAquired();
            for (String folder : client.getIndexHandler().getFolderList()) {
                try (IndexBrowser indexBrowser = client.getIndexHandler().newIndexBrowserBuilder()
                        .setFolder(folder).build()) {
                    logger.info("list folder = {}", indexBrowser.getFolder());
                    for (FileInfo fileInfo : indexBrowser.listFiles()) {
                        logger.info("\t\t{} {} {}", fileInfo.getType().name().substring(0, 1),
                                fileInfo.getPath(), fileInfo.describeSize());
                    }
                }
            }
        }
    }
    if (cmd.hasOption("I")) {
        try (SyncthingClient client = new SyncthingClient(configuration)) {
            if (cmd.hasOption("a")) {
                String deviceId = cmd.getOptionValue("a").substring(0, 63),
                        address = cmd.getOptionValue("a").substring(64);
                try (BlockExchangeConnectionHandler connection = client.getConnection(
                        DeviceAddress.newBuilder().setDeviceId(deviceId).setAddress(address).build())) {
                    client.getIndexHandler().waitForRemoteIndexAquired(connection);
                }
            } else {
                client.waitForRemoteIndexAquired();
            }
            String folderInfo = "";
            for (String folder : client.getIndexHandler().getFolderList()) {
                folderInfo += "\n\t\tfolder info : " + client.getIndexHandler().getFolderInfo(folder);
                folderInfo += "\n\t\tfolder stats : "
                        + client.getIndexHandler().newFolderBrowser().getFolderStats(folder).dumpInfo() + "\n";
            }
            logger.info("folders:\n{}\n", folderInfo);
        }
    }
    if (cmd.hasOption("li")) {
        try (SyncthingClient client = new SyncthingClient(configuration)) {
            String folderInfo = "";
            for (String folder : client.getIndexHandler().getFolderList()) {
                folderInfo += "\n\t\tfolder info : " + client.getIndexHandler().getFolderInfo(folder);
                folderInfo += "\n\t\tfolder stats : "
                        + client.getIndexHandler().newFolderBrowser().getFolderStats(folder).dumpInfo() + "\n";
            }
            logger.info("folders:\n{}\n", folderInfo);
        }
    }
    if (cmd.hasOption("lp")) {
        try (SyncthingClient client = new SyncthingClient(configuration);
                DeviceAddressSupplier deviceAddressSupplier = client.getDiscoveryHandler()
                        .newDeviceAddressSupplier()) {
            String deviceAddressesStr = "";
            for (DeviceAddress deviceAddress : Lists.newArrayList(deviceAddressSupplier)) {
                deviceAddressesStr += "\n\t\t" + deviceAddress.getDeviceId() + " : "
                        + deviceAddress.getAddress();
            }
            logger.info("device addresses:\n{}\n", deviceAddressesStr);
        }
    }
    if (cmd.hasOption("s")) {
        String term = cmd.getOptionValue("s");
        try (SyncthingClient client = new SyncthingClient(configuration);
                IndexFinder indexFinder = client.getIndexHandler().newIndexFinderBuilder().build()) {
            client.waitForRemoteIndexAquired();
            logger.info("search term = '{}'", term);
            IndexFinder.SearchCompletedEvent event = indexFinder.doSearch(term);
            if (event.hasGoodResults()) {
                logger.info("search results for term = '{}' :", term);
                for (FileInfo fileInfo : event.getResultList()) {
                    logger.info("\t\t{} {} {}", fileInfo.getType().name().substring(0, 1), fileInfo.getPath(),
                            fileInfo.describeSize());
                }
            } else if (event.hasTooManyResults()) {
                logger.info("too many results found for term = '{}'", term);
            } else {
                logger.info("no result found for term = '{}'", term);
            }
        }
    }
    //        if (cmd.hasOption("l")) {
    //            String indexDump = new IndexHandler(configuration).dumpIndex();
    //            logger.info("index dump = \n\n{}\n", indexDump);
    //        }
    IOUtils.closeQuietly(configuration);
}

From source file:RoucairolCarvahloBasicVersion.java

public static void main(String[] args) throws FileNotFoundException, IOException, InterruptedException {
    //For parsing the file and storing the information
    String line;
    String configurationFile = "configuration.txt";
    int lineCountInFile = 0;
    myProcessId = Integer.parseInt(args[0]);
    FileReader fileReader = new FileReader(configurationFile);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    while ((line = bufferedReader.readLine()) != null) {
        if ((!(line.startsWith("#"))) && (!(line.isEmpty()))) {
            lineCountInFile = lineCountInFile + 1;
            String[] splitLine = line.split(" ");
            switch (lineCountInFile) {
            case 1:
                numberOfProcesses = Integer.parseInt(splitLine[0]);
                interRequestDelay = Integer.parseInt(splitLine[1]);
                csExecutionTime = Integer.parseInt(splitLine[2]);
                maxNumberOfRequest = Integer.parseInt(splitLine[3]);
                machineNames = new String[Integer.parseInt(splitLine[0])];
                portNumbers = new int[Integer.parseInt(splitLine[0])];
                break;
            default:
                machineNames[lineCountInFile - 2] = splitLine[1];
                portNumbers[lineCountInFile - 2] = Integer.parseInt(splitLine[2]);
                break;
            }//from  w  w w  .  j a va 2  s.  c o  m
        }
    }
    //Initializing finish array
    finishFlagArray = new int[numberOfProcesses];
    //Initializing vector class
    VectorClass.initialize(numberOfProcesses);
    //Fill the arrays with zero false value
    for (int o = 0; o < numberOfProcesses; o++) {
        finishFlagArray[o] = 0;
    }
    //Initializing key array and inserting values
    keyArray = new int[numberOfProcesses];
    for (int q = 0; q < numberOfProcesses; q++) {
        if (q >= myProcessId) {
            keyArray[q] = 1;
        }
    }
    filename = filename + Integer.toString(myProcessId) + ".out";
    file = new File(filename);
    file.createNewFile();
    writer = new FileWriter(file);
    // Write clocks to file
    filenameClock = filenameClock + Integer.toString(myProcessId) + ".out";
    fileClock = new File(filenameClock);
    fileClock.createNewFile();
    //writerClock = new FileWriter(fileClock);
    fw = new FileWriter(fileClock);
    bw = new BufferedWriter(fw);
    //
    // Expo mean insert
    csExecutionExpoDelay = new ExponentialDistribution(csExecutionTime);
    interRequestExpoDelay = new ExponentialDistribution(interRequestDelay);
    //
    System.out.println("********************************************************");
    System.out.println("My process id : " + myProcessId);
    System.out.println("Number of processes : " + numberOfProcesses);
    System.out.println("Inter-request delay : " + interRequestDelay);
    System.out.println("Critical section execution time : " + csExecutionTime);
    System.out.println("Maximum number of request : " + maxNumberOfRequest);
    System.out.println(
            "My process name : " + machineNames[myProcessId] + " My port number : " + portNumbers[myProcessId]);
    for (int i = 0; i < numberOfProcesses; i++) {
        System.out.println("Process name : " + machineNames[i] + " Port number : " + portNumbers[i]);
    }
    System.out.println("********************************************************");
    for (int q = 0; q < numberOfProcesses; q++) {
        System.out.println("KeyArray" + q + " - " + keyArray[q]);
    }
    System.out.println("********************************************************");
    //For hosting server localhost
    SctpServerChannel sctpServerChannel = SctpServerChannel.open();
    InetSocketAddress serverAddr = new InetSocketAddress(portNumbers[myProcessId]);
    sctpServerChannel.bind(serverAddr);
    System.out.println("********************************************************");
    System.out.println("Local server hosted");
    System.out.println("********************************************************");
    //For creating neighbor SCTP channels
    Thread.sleep(30000);
    socketAddress = new SocketAddress[numberOfProcesses];
    sctpChannel = new SctpChannel[numberOfProcesses];
    System.out.println("********************************************************");
    System.out.println("Neighbor channels created");
    System.out.println("********************************************************");
    //Thread spanned for generating critical section request
    new Thread(new RoucairolCarvahloBasicVersion()).start();
    while (true) {
        try (SctpChannel sctpChannelFromClient = sctpServerChannel.accept()) {
            mutex.acquire();
            byteBufferFromNeighbor.clear();
            String receiveMessage;
            MessageInfo messageInfoFromNeighbor = sctpChannelFromClient.receive(byteBufferFromNeighbor, null,
                    null);
            //System.out.println("Raw Message : " + messageInfoFromNeighbor);
            receiveMessage = byteToString(byteBufferFromNeighbor, messageInfoFromNeighbor);
            System.out.println("Received Message : " + receiveMessage);
            if (receiveMessage.contains("Request")) {
                String[] parseMessage = receiveMessage.split("-");
                lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1;
                //vector clock update
                String[] stringNumericalTimestamp = parseMessage[4].split(",");
                int[] numericalTimestamp = new int[stringNumericalTimestamp.length];
                for (int d = 0; d < stringNumericalTimestamp.length; d++) {
                    numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]);
                }
                VectorClass.update(myProcessId, numericalTimestamp);
                //
                int requestMade = Integer.parseInt(parseMessage[3] + parseMessage[1]);
                if (outstandingRequest == 1) {
                    if (requestMade < currentRequestBeingServed) {
                        lamportClock++;
                        //Newly inserted for vector timesatmp
                        int[] vector = VectorClass.increment(myProcessId);
                        String vectorClockConstruction = "";
                        for (int g = 0; g < vector.length; g++) {
                            if (g == 0) {
                                vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]);
                            } else {
                                vectorClockConstruction = vectorClockConstruction + ","
                                        + Integer.toString(vector[g]);
                            }
                        }
                        //
                        keyArray[Integer.parseInt(parseMessage[1])] = 0;
                        try {
                            byteBufferToNeighbor.clear();
                            initializeChannels();
                            sctpChannel[Integer.parseInt(parseMessage[1])]
                                    .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                            String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-"
                                    + lamportClock + "-" + vectorClockConstruction;
                            System.out.println("Message sent is : " + sendMessage);
                            MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                            byteBufferToNeighbor.put(sendMessage.getBytes());
                            byteBufferToNeighbor.flip();
                            sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                    messageInfoToNeighbor);
                            totalMessageCount++;
                            sctpChannel[Integer.parseInt(parseMessage[1])].close();
                        } catch (IOException ex) {
                            Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE,
                                    null, ex);
                        }
                        //Include block for reverse request
                        lamportClock++;
                        //Newly inserted for vector timesatmp
                        int[] vector1 = VectorClass.increment(myProcessId);
                        String vectorClockConstruction1 = "";
                        for (int g = 0; g < vector1.length; g++) {
                            if (g == 0) {
                                vectorClockConstruction1 = vectorClockConstruction1
                                        + Integer.toString(vector1[g]);
                            } else {
                                vectorClockConstruction1 = vectorClockConstruction1 + ","
                                        + Integer.toString(vector1[g]);
                            }
                        }
                        //
                        try {
                            byteBufferToNeighbor.clear();
                            initializeChannels();
                            sctpChannel[Integer.parseInt(parseMessage[1])]
                                    .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                            String sendMessage = "ReverseSend from Process-" + myProcessId + "-"
                                    + currentRequestBeingServed + "-" + lamportClock + "-"
                                    + vectorClockConstruction1;
                            System.out.println("Message sent is : " + sendMessage);
                            MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                            byteBufferToNeighbor.put(sendMessage.getBytes());
                            byteBufferToNeighbor.flip();
                            sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                    messageInfoToNeighbor);
                            totalMessageCount++;
                            sctpChannel[Integer.parseInt(parseMessage[1])].close();
                        } catch (IOException ex) {
                            Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE,
                                    null, ex);
                        }
                    } else if (requestMade == currentRequestBeingServed) {
                        if (Integer.parseInt(parseMessage[1]) < myProcessId) {
                            lamportClock++;
                            //Newly inserted for vector timesatmp
                            int[] vector = VectorClass.increment(myProcessId);
                            String vectorClockConstruction = "";
                            for (int g = 0; g < vector.length; g++) {
                                if (g == 0) {
                                    vectorClockConstruction = vectorClockConstruction
                                            + Integer.toString(vector[g]);
                                } else {
                                    vectorClockConstruction = vectorClockConstruction + ","
                                            + Integer.toString(vector[g]);
                                }
                            }
                            //
                            keyArray[Integer.parseInt(parseMessage[1])] = 0;
                            try {
                                byteBufferToNeighbor.clear();
                                initializeChannels();
                                sctpChannel[Integer.parseInt(parseMessage[1])]
                                        .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                                String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-"
                                        + lamportClock + "-" + vectorClockConstruction;
                                System.out.println("Message sent is : " + sendMessage);
                                MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                                byteBufferToNeighbor.put(sendMessage.getBytes());
                                byteBufferToNeighbor.flip();
                                sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                        messageInfoToNeighbor);
                                totalMessageCount++;
                                sctpChannel[Integer.parseInt(parseMessage[1])].close();
                            } catch (IOException ex) {
                                Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName())
                                        .log(Level.SEVERE, null, ex);
                            }
                            //Include block for reverse request
                            lamportClock++;
                            //Newly inserted for vector timesatmp
                            int[] vector1 = VectorClass.increment(myProcessId);
                            String vectorClockConstruction1 = "";
                            for (int g = 0; g < vector1.length; g++) {
                                if (g == 0) {
                                    vectorClockConstruction1 = vectorClockConstruction1
                                            + Integer.toString(vector1[g]);
                                } else {
                                    vectorClockConstruction1 = vectorClockConstruction1 + ","
                                            + Integer.toString(vector1[g]);
                                }
                            }
                            //
                            try {
                                byteBufferToNeighbor.clear();
                                initializeChannels();
                                sctpChannel[Integer.parseInt(parseMessage[1])]
                                        .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                                String sendMessage = "ReverseSend from Process-" + myProcessId + "-"
                                        + currentRequestBeingServed + "-" + lamportClock + "-"
                                        + vectorClockConstruction1;
                                System.out.println("Message sent is : " + sendMessage);
                                MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                                byteBufferToNeighbor.put(sendMessage.getBytes());
                                byteBufferToNeighbor.flip();
                                sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                        messageInfoToNeighbor);
                                totalMessageCount++;
                                sctpChannel[Integer.parseInt(parseMessage[1])].close();
                            } catch (IOException ex) {
                                Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName())
                                        .log(Level.SEVERE, null, ex);
                            }
                        } else if (myProcessId < Integer.parseInt(parseMessage[1])) {
                            queue.add(requestMade);
                        }
                    } else if (requestMade > currentRequestBeingServed) {
                        queue.add(requestMade);
                    }
                } else if (outstandingRequest == 0) {
                    lamportClock++;
                    //Newly inserted for vector timesatmp
                    int[] vector = VectorClass.increment(myProcessId);
                    String vectorClockConstruction = "";
                    for (int g = 0; g < vector.length; g++) {
                        if (g == 0) {
                            vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]);
                        } else {
                            vectorClockConstruction = vectorClockConstruction + ","
                                    + Integer.toString(vector[g]);
                        }
                    }
                    //
                    keyArray[Integer.parseInt(parseMessage[1])] = 0;
                    try {
                        byteBufferToNeighbor.clear();
                        initializeChannels();
                        sctpChannel[Integer.parseInt(parseMessage[1])]
                                .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                        String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-"
                                + lamportClock + "-" + vectorClockConstruction;
                        System.out.println("Message sent is : " + sendMessage);
                        MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                        byteBufferToNeighbor.put(sendMessage.getBytes());
                        byteBufferToNeighbor.flip();
                        sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                messageInfoToNeighbor);
                        totalMessageCount++;
                        sctpChannel[Integer.parseInt(parseMessage[1])].close();
                    } catch (IOException ex) {
                        Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE, null,
                                ex);
                    }
                }
            } else if (receiveMessage.contains("Key")) {
                //receive check condition execute critical section block
                String[] parseMessage = receiveMessage.split("-");
                lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1;
                //vector clock update
                String[] stringNumericalTimestamp = parseMessage[4].split(",");
                int[] numericalTimestamp = new int[stringNumericalTimestamp.length];
                for (int d = 0; d < stringNumericalTimestamp.length; d++) {
                    numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]);
                }
                VectorClass.update(myProcessId, numericalTimestamp);
                //
                keyArray[Integer.parseInt(parseMessage[1])] = 1;
                int countOnes = 0;
                for (int y = 0; y < numberOfProcesses; y++) {
                    if (keyArray[y] == 1) {
                        countOnes = countOnes + 1;
                    }
                }
                if (countOnes == numberOfProcesses) {
                    outstandingRequest = 0;
                    currentRequestBeingServed = 0;
                    enterCriticalSectionExecution();
                    timestamp2 = new Timestamp(System.currentTimeMillis());
                    csExit();
                }
            } else if (receiveMessage.contains("ReverseSend")) {
                String[] parseMessage = receiveMessage.split("-");
                lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1;
                //vector clock update
                String[] stringNumericalTimestamp = parseMessage[4].split(",");
                int[] numericalTimestamp = new int[stringNumericalTimestamp.length];
                for (int d = 0; d < stringNumericalTimestamp.length; d++) {
                    numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]);
                }
                VectorClass.update(myProcessId, numericalTimestamp);
                //
                int requestMade = Integer.parseInt(parseMessage[2]);
                if (outstandingRequest == 1) {
                    if (requestMade < currentRequestBeingServed) {
                        lamportClock++;
                        //Newly inserted for vector timesatmp
                        int[] vector = VectorClass.increment(myProcessId);
                        String vectorClockConstruction = "";
                        for (int g = 0; g < vector.length; g++) {
                            if (g == 0) {
                                vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]);
                            } else {
                                vectorClockConstruction = vectorClockConstruction + ","
                                        + Integer.toString(vector[g]);
                            }
                        }
                        //
                        keyArray[Integer.parseInt(parseMessage[1])] = 0;
                        try {
                            byteBufferToNeighbor.clear();
                            initializeChannels();
                            sctpChannel[Integer.parseInt(parseMessage[1])]
                                    .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                            String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-"
                                    + lamportClock + "-" + vectorClockConstruction;
                            System.out.println("Message sent is : " + sendMessage);
                            MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                            byteBufferToNeighbor.put(sendMessage.getBytes());
                            byteBufferToNeighbor.flip();
                            sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                    messageInfoToNeighbor);
                            totalMessageCount++;
                            sctpChannel[Integer.parseInt(parseMessage[1])].close();
                        } catch (IOException ex) {
                            Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE,
                                    null, ex);
                        }
                        //Include block for reverse request
                        lamportClock++;
                        //Newly inserted for vector timesatmp
                        int[] vector1 = VectorClass.increment(myProcessId);
                        String vectorClockConstruction1 = "";
                        for (int g = 0; g < vector1.length; g++) {
                            if (g == 0) {
                                vectorClockConstruction1 = vectorClockConstruction1
                                        + Integer.toString(vector1[g]);
                            } else {
                                vectorClockConstruction1 = vectorClockConstruction1 + ","
                                        + Integer.toString(vector1[g]);
                            }
                        }
                        //
                        try {
                            byteBufferToNeighbor.clear();
                            initializeChannels();
                            sctpChannel[Integer.parseInt(parseMessage[1])]
                                    .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                            String sendMessage = "ReverseSend from Process-" + myProcessId + "-"
                                    + currentRequestBeingServed + "-" + lamportClock + "-"
                                    + vectorClockConstruction1;
                            System.out.println("Message sent is : " + sendMessage);
                            MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                            byteBufferToNeighbor.put(sendMessage.getBytes());
                            byteBufferToNeighbor.flip();
                            sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                    messageInfoToNeighbor);
                            totalMessageCount++;
                            sctpChannel[Integer.parseInt(parseMessage[1])].close();
                        } catch (IOException ex) {
                            Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE,
                                    null, ex);
                        }
                    } else if (requestMade == currentRequestBeingServed) {
                        if (Integer.parseInt(parseMessage[1]) < myProcessId) {
                            lamportClock++;
                            //Newly inserted for vector timesatmp
                            int[] vector = VectorClass.increment(myProcessId);
                            String vectorClockConstruction = "";
                            for (int g = 0; g < vector.length; g++) {
                                if (g == 0) {
                                    vectorClockConstruction = vectorClockConstruction
                                            + Integer.toString(vector[g]);
                                } else {
                                    vectorClockConstruction = vectorClockConstruction + ","
                                            + Integer.toString(vector[g]);
                                }
                            }
                            //
                            keyArray[Integer.parseInt(parseMessage[1])] = 0;
                            try {
                                byteBufferToNeighbor.clear();
                                initializeChannels();
                                sctpChannel[Integer.parseInt(parseMessage[1])]
                                        .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                                String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-"
                                        + lamportClock + "-" + vectorClockConstruction;
                                System.out.println("Message sent is : " + sendMessage);
                                MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                                byteBufferToNeighbor.put(sendMessage.getBytes());
                                byteBufferToNeighbor.flip();
                                sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                        messageInfoToNeighbor);
                                totalMessageCount++;
                                sctpChannel[Integer.parseInt(parseMessage[1])].close();
                            } catch (IOException ex) {
                                Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName())
                                        .log(Level.SEVERE, null, ex);
                            }
                            //Include block for reverse request
                            lamportClock++;
                            //Newly inserted for vector timesatmp
                            int[] vector1 = VectorClass.increment(myProcessId);
                            String vectorClockConstruction1 = "";
                            for (int g = 0; g < vector1.length; g++) {
                                if (g == 0) {
                                    vectorClockConstruction1 = vectorClockConstruction1
                                            + Integer.toString(vector1[g]);
                                } else {
                                    vectorClockConstruction1 = vectorClockConstruction1 + ","
                                            + Integer.toString(vector1[g]);
                                }
                            }
                            //
                            try {
                                byteBufferToNeighbor.clear();
                                initializeChannels();
                                sctpChannel[Integer.parseInt(parseMessage[1])]
                                        .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                                String sendMessage = "ReverseSend from Process-" + myProcessId + "-"
                                        + currentRequestBeingServed + "-" + lamportClock + "-"
                                        + vectorClockConstruction1;
                                System.out.println("Message sent is : " + sendMessage);
                                MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                                byteBufferToNeighbor.put(sendMessage.getBytes());
                                byteBufferToNeighbor.flip();
                                sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                        messageInfoToNeighbor);
                                totalMessageCount++;
                                sctpChannel[Integer.parseInt(parseMessage[1])].close();
                            } catch (IOException ex) {
                                Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName())
                                        .log(Level.SEVERE, null, ex);
                            }
                        } else if (myProcessId < Integer.parseInt(parseMessage[1])) {
                            queue.add(requestMade);
                        }
                    } else if (requestMade > currentRequestBeingServed) {
                        queue.add(requestMade);
                    }
                } else if (outstandingRequest == 0) {
                    lamportClock++;
                    //Newly inserted for vector timesatmp
                    int[] vector = VectorClass.increment(myProcessId);
                    String vectorClockConstruction = "";
                    for (int g = 0; g < vector.length; g++) {
                        if (g == 0) {
                            vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]);
                        } else {
                            vectorClockConstruction = vectorClockConstruction + ","
                                    + Integer.toString(vector[g]);
                        }
                    }
                    //
                    keyArray[Integer.parseInt(parseMessage[1])] = 0;
                    try {
                        byteBufferToNeighbor.clear();
                        initializeChannels();
                        sctpChannel[Integer.parseInt(parseMessage[1])]
                                .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                        String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-"
                                + lamportClock + "-" + vectorClockConstruction;
                        System.out.println("Message sent is : " + sendMessage);
                        MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                        byteBufferToNeighbor.put(sendMessage.getBytes());
                        byteBufferToNeighbor.flip();
                        sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                messageInfoToNeighbor);
                        totalMessageCount++;
                        sctpChannel[Integer.parseInt(parseMessage[1])].close();
                    } catch (IOException ex) {
                        Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE, null,
                                ex);
                    }
                }
            } else if (receiveMessage.contains("Finish")) {
                String[] parseMessage = receiveMessage.split("-");
                lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1;
                //vector clock update
                String[] stringNumericalTimestamp = parseMessage[4].split(",");
                int[] numericalTimestamp = new int[stringNumericalTimestamp.length];
                for (int d = 0; d < stringNumericalTimestamp.length; d++) {
                    numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]);
                }
                VectorClass.update(myProcessId, numericalTimestamp);
                //
                finishFlagArray[Integer.parseInt(parseMessage[1])] = 1;
                int count = 0;
                for (int v = 0; v < numberOfProcesses; v++) {
                    if (finishFlagArray[v] == 1) {
                        count = count + 1;
                    }
                }
                if (count == numberOfProcesses) {
                    break;
                }
            }
        }
        mutex.release();
    }
}

From source file:DIA_Umpire_Quant.DIA_Umpire_ProtQuant.java

/**
 * @param args the command line arguments
 *//*  ww w  . ja va  2 s. c  o  m*/
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println(
            "DIA-Umpire protein quantitation module (version: " + UmpireInfo.GetInstance().Version + ")");
    if (args.length != 1) {
        System.out.println(
                "command format error, the correct format should be: java -jar -Xmx10G DIA_Umpire_PortQuant.jar diaumpire_module.params");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.INFO);
        ConsoleLogger.SetFileLogger(Level.DEBUG,
                FilenameUtils.getFullPath(args[0]) + "diaumpire_orotquant.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;

    String Combined_Prot = "";
    boolean DefaultProtFiltering = true;

    float Freq = 0f;
    int TopNPep = 6;
    int TopNFrag = 6;
    String FilterWeight = "GW";
    float MinWeight = 0.9f;

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

    boolean ExportSaint = false;
    boolean SAINT_MS1 = false;
    boolean SAINT_MS2 = true;

    HashMap<String, String[]> BaitList = new HashMap<>();
    HashMap<String, String> BaitName = new HashMap<>();
    HashMap<String, String[]> ControlList = new HashMap<>();
    HashMap<String, String> ControlName = 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 "Fasta": {
                tandemPara.FastaPath = value;
                break;
            }
            case "Combined_Prot": {
                Combined_Prot = value;
                break;
            }
            case "DefaultProtFiltering": {
                DefaultProtFiltering = Boolean.parseBoolean(value);
                break;
            }
            case "DecoyPrefix": {
                if (!"".equals(value)) {
                    tandemPara.DecoyPrefix = value;
                }
                break;
            }
            case "ProteinFDR": {
                tandemPara.ProtFDR = Float.parseFloat(value);
                break;
            }
            case "FilterWeight": {
                FilterWeight = value;
                break;
            }
            case "MinWeight": {
                MinWeight = Float.parseFloat(value);
                break;
            }
            case "TopNFrag": {
                TopNFrag = Integer.parseInt(value);
                break;
            }
            case "TopNPep": {
                TopNPep = Integer.parseInt(value);
                break;
            }
            case "Freq": {
                Freq = Float.parseFloat(value);
                break;
            }
            //<editor-fold defaultstate="collapsed" desc="SaintOutput">
            case "ExportSaintInput": {
                ExportSaint = Boolean.parseBoolean(value);
                break;
            }
            case "QuantitationType": {
                switch (value) {
                case "MS1": {
                    SAINT_MS1 = true;
                    SAINT_MS2 = false;
                    break;
                }
                case "MS2": {
                    SAINT_MS1 = false;
                    SAINT_MS2 = true;
                    break;
                }
                case "BOTH": {
                    SAINT_MS1 = true;
                    SAINT_MS2 = true;
                    break;
                }
                }
                break;
            }
            //                    case "BaitInputFile": {
            //                        SaintBaitFile = value;
            //                        break;
            //                    }
            //                    case "PreyInputFile": {
            //                        SaintPreyFile = value;
            //                        break;
            //                    }
            //                    case "InterationInputFile": {
            //                        SaintInteractionFile = value;
            //                        break;
            //                    }
            default: {
                if (type.startsWith("BaitName_")) {
                    BaitName.put(type.substring(9), value);
                }
                if (type.startsWith("BaitFile_")) {
                    BaitList.put(type.substring(9), value.split("\t"));
                }
                if (type.startsWith("ControlName_")) {
                    ControlName.put(type.substring(12), value);
                }
                if (type.startsWith("ControlFile_")) {
                    ControlList.put(type.substring(12), value.split("\t"));
                }
                break;
            }
            //</editor-fold>                    
            }
        }
    }
    //</editor-fold>

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

    //Check if the fasta file can be found
    if (!new File(tandemPara.FastaPath).exists()) {
        Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath
                + " cannot be found, the process will be terminated, please check.");
        System.exit(1);
    }

    //Check if the prot.xml file can be found
    if (!new File(Combined_Prot).exists()) {
        Logger.getRootLogger().info("ProtXML file: " + Combined_Prot
                + " cannot be found, the export protein summary table will be empty.");
    }
    LCMSID protID = null;

    //Parse prot.xml and generate protein master list given an FDR 
    if (Combined_Prot != null && !Combined_Prot.equals("")) {
        protID = LCMSID.ReadLCMSIDSerialization(Combined_Prot);
        if (!"".equals(Combined_Prot) && protID == null) {
            protID = new LCMSID(Combined_Prot, tandemPara.DecoyPrefix, tandemPara.FastaPath);
            ProtXMLParser protxmlparser = new ProtXMLParser(protID, Combined_Prot, 0f);
            //Use DIA-Umpire default protein FDR calculation
            if (DefaultProtFiltering) {
                protID.RemoveLowLocalPWProtein(0.8f);
                protID.RemoveLowMaxIniProbProtein(0.9f);
                protID.FilterByProteinDecoyFDRUsingMaxIniProb(tandemPara.DecoyPrefix, tandemPara.ProtFDR);
            }
            //Get protein FDR calculation without other filtering
            else {
                protID.FilterByProteinDecoyFDRUsingLocalPW(tandemPara.DecoyPrefix, tandemPara.ProtFDR);
            }
            protID.LoadSequence();
            protID.WriteLCMSIDSerialization(Combined_Prot);
        }
        Logger.getRootLogger().info("Protein No.:" + protID.ProteinList.size());
    }
    HashMap<String, HashMap<String, FragmentPeak>> IDSummaryFragments = new HashMap<>();

    //Generate DIA file list
    ArrayList<DIAPack> FileList = new ArrayList<>();
    try {
        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());
        }

        for (File fileEntry : AssignFiles.values()) {
            String mzXMLFile = fileEntry.getAbsolutePath();
            if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) {
                DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs);
                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 + "....");

                //If the serialization file for ID file existed
                if (DiaFile.ReadSerializedLCMSID()) {
                    DiaFile.IDsummary.ReduceMemoryUsage();
                    DiaFile.IDsummary.ClearAssignPeakCluster();
                    FileList.add(DiaFile);
                    HashMap<String, FragmentPeak> FragMap = new HashMap<>();
                    IDSummaryFragments.put(FilenameUtils.getBaseName(mzXMLFile), FragMap);
                }
            }
        }

        //<editor-fold defaultstate="collapsed" desc="Peptide and fragment selection">

        Logger.getRootLogger().info("Peptide and fragment selection across the whole dataset");
        ArrayList<LCMSID> SummaryList = new ArrayList<>();
        for (DIAPack diafile : FileList) {
            if (protID != null) {
                //Generate protein list according to mapping of peptide ions for each DIA file to the master protein list
                diafile.IDsummary.GenerateProteinByRefIDByPepSeq(protID, true);
                diafile.IDsummary.ReMapProPep();
            }
            if ("GW".equals(FilterWeight)) {
                diafile.IDsummary.SetFilterByGroupWeight();
            } else if ("PepW".equals(FilterWeight)) {
                diafile.IDsummary.SetFilterByWeight();
            }
            SummaryList.add(diafile.IDsummary);
        }
        FragmentSelection fragselection = new FragmentSelection(SummaryList);
        fragselection.freqPercent = Freq;
        fragselection.GeneratePepFragScoreMap();
        fragselection.GenerateTopFragMap(TopNFrag);
        fragselection.GenerateProtPepScoreMap(MinWeight);
        fragselection.GenerateTopPepMap(TopNPep);
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Writing general reports">                 
        ExportTable export = new ExportTable(WorkFolder, SummaryList, IDSummaryFragments, protID,
                fragselection);
        export.Export(TopNPep, TopNFrag, Freq);
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="//<editor-fold defaultstate="collapsed" desc="Generate SAINT input files">
        if (ExportSaint && protID != null) {
            HashMap<String, DIAPack> Filemap = new HashMap<>();
            for (DIAPack DIAfile : FileList) {
                Filemap.put(DIAfile.GetBaseName(), DIAfile);
            }

            FileWriter baitfile = new FileWriter(WorkFolder + "SAINT_Bait_" + DateTimeTag.GetTag() + ".txt");
            FileWriter preyfile = new FileWriter(WorkFolder + "SAINT_Prey_" + DateTimeTag.GetTag() + ".txt");
            FileWriter interactionfileMS1 = null;
            FileWriter interactionfileMS2 = null;
            if (SAINT_MS1) {
                interactionfileMS1 = new FileWriter(
                        WorkFolder + "SAINT_Interaction_MS1_" + DateTimeTag.GetTag() + ".txt");
            }
            if (SAINT_MS2) {
                interactionfileMS2 = new FileWriter(
                        WorkFolder + "SAINT_Interaction_MS2_" + DateTimeTag.GetTag() + ".txt");
            }
            HashMap<String, String> PreyID = new HashMap<>();

            for (String samplekey : ControlName.keySet()) {
                String name = ControlName.get(samplekey);
                for (String file : ControlList.get(samplekey)) {
                    baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "C\n");
                    LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary;
                    if (SAINT_MS1) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID,
                                1);
                    }
                    if (SAINT_MS2) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID,
                                2);
                    }
                }
            }
            for (String samplekey : BaitName.keySet()) {
                String name = BaitName.get(samplekey);
                for (String file : BaitList.get(samplekey)) {
                    baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "T\n");
                    LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary;
                    if (SAINT_MS1) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID,
                                1);
                    }
                    if (SAINT_MS2) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID,
                                2);
                    }
                }
            }
            baitfile.close();
            if (SAINT_MS1) {
                interactionfileMS1.close();
            }
            if (SAINT_MS2) {
                interactionfileMS2.close();
            }
            for (String AccNo : PreyID.keySet()) {
                preyfile.write(AccNo + "\t" + PreyID.get(AccNo) + "\n");
            }
            preyfile.close();
        }

        //</editor-fold>

        Logger.getRootLogger().info("Job done");
        Logger.getRootLogger().info(
                "=================================================================================================");

    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        throw e;
    }
}

From source file:javazoom.jlgui.player.amp.Player.java

/**
 * Entry point./*from   w  w  w.  j a  va  2 s  .  com*/
 */
public static void main(String[] args) {
    Player theGUI;
    String currentArg = null;
    String currentValue = null;
    String skin = null;
    for (int i = 0; i < args.length; i++) {
        currentArg = args[i];
        if (currentArg.startsWith("-")) {
            if (currentArg.toLowerCase().equals("-init")) {
                i++;
                if (i >= args.length)
                    usage("init value missing");
                currentValue = args[i];
                if (Config.startWithProtocol(currentValue))
                    initConfig = currentValue;
                else
                    initConfig = currentValue.replace('\\', '/').replace('/', java.io.File.separatorChar);
            } else if (currentArg.toLowerCase().equals("-song")) {
                i++;
                if (i >= args.length)
                    usage("song value missing");
                currentValue = args[i];
                if (Config.startWithProtocol(currentValue))
                    initSong = currentValue;
                else
                    initSong = currentValue.replace('\\', '/').replace('/', java.io.File.separatorChar);
            } else if (currentArg.toLowerCase().equals("-start")) {
                autoRun = true;
            } else if (currentArg.toLowerCase().equals("-showplaylist")) {
                showPlaylist = "true";
            } else if (currentArg.toLowerCase().equals("-showequalizer")) {
                showEqualizer = "true";
            } else if (currentArg.toLowerCase().equals("-skin")) {
                i++;
                if (i >= args.length)
                    usage("skin value missing");
                currentValue = args[i];
                if (Config.startWithProtocol(currentValue))
                    skin = currentValue;
                else
                    skin = currentValue.replace('\\', '/').replace('/', java.io.File.separatorChar);
            } else if (currentArg.toLowerCase().equals("-v")) {
                i++;
                if (i >= args.length)
                    usage("skin version value missing");
                skinVersion = args[i];
            } else
                usage("Unknown parameter : " + currentArg);
        } else {
            usage("Invalid parameter :" + currentArg);
        }
    }
    // Instantiate AWT front-end.      
    theGUI = new Player(skin, new Frame(TITLETEXT));
    // Instantiate low-level player.
    BasicPlayer bplayer = new BasicPlayer();
    // Register the front-end to low-level player events.
    bplayer.addBasicPlayerListener(theGUI);
    // Adds controls for front-end to low-level player.
    theGUI.setController(bplayer);
    // Display.
    theGUI.show();
    if (autoRun == true)
        theGUI.pressStart();
}

From source file:me.gloriouseggroll.quorrabot.Quorrabot.java

public static void main(String[] args) throws IOException {
    String user = "";
    String oauth = "";
    String apioauth = "";
    String channelName = "";
    String webauth = "";
    String webauthro = "";
    String clientid = "";
    String owner = "";
    String hostname = "";
    int baseport = 25300;
    InetAddress ip = InetAddress.getByName("127.0.0.1");
    int port = 0;
    double msglimit30 = 18.75;
    String datastore = "";
    String datastoreconfig = "";
    String youtubekey = "";
    String gamewispauth = "";
    String gamewisprefresh = "";
    String twitchalertstoken = "";
    String lastfmuser = "";
    String tpetoken = "";
    String twittertoken = "";
    String twittertokensecret = "";
    String streamtiptoken = "";
    String streamtipid = "";
    boolean webenable = true;
    boolean musicenable = true;
    boolean usehttps = false;
    String keystorepath = "";
    String keystorepassword = "";
    String timeZone = "";
    String mySqlConn = "";
    String mySqlHost = "";
    String mySqlPort = "";
    String mySqlName = "";
    String mySqlUser = "";
    String mySqlPass = "";
    FollowersCache followersCache;/* w  w w  .jav  a 2  s  .c o  m*/
    ChannelUsersCache channelUsersCache;
    ChannelHostCache hostCache;
    SubscribersCache subscribersCache;
    String discordToken = "";
    String discordMainChannel = "";

    boolean changed = false;

    try {
        if (new File("./botlogin.txt").exists()) {
            String data = FileUtils.readFileToString(new File("./botlogin.txt"));
            String[] lines = data.replaceAll("\\r", "").split("\\n");

            for (String line : lines) {

                if (line.startsWith("logtimezone=") && line.length() >= 15) {
                    timeZone = line.substring(12);
                }
                if (line.startsWith("websocketircab")) {
                    Quorrabot.webSocketIRCAB = true;
                }
                if (line.startsWith("user=") && line.length() > 8) {
                    user = line.substring(5);
                }
                if (line.startsWith("oauth=") && line.length() > 9) {
                    oauth = line.substring(6);
                }
                if (line.startsWith("apioauth=") && line.length() > 12) {
                    apioauth = line.substring(9);
                }
                if (line.startsWith("clientid=") && line.length() > 12) {
                    clientid = line.substring(9);
                }
                if (line.startsWith("channel=") && line.length() > 11) {
                    channelName = line.substring(8);
                }
                if (line.startsWith("owner=") && line.length() > 9) {
                    owner = line.substring(6);
                }
                if (line.startsWith("baseport=") && line.length() > 10) {
                    baseport = Integer.parseInt(line.substring(9));
                }
                if (line.startsWith("ip=") && line.length() > 4) {
                    ip = InetAddress.getByName(line.substring(3));
                }
                if (line.startsWith("hostname=") && line.length() > 10) {
                    hostname = line.substring(9);
                }
                if (line.startsWith("port=") && line.length() > 6) {
                    port = Integer.parseInt(line.substring(5));
                }
                if (line.startsWith("msglimit30=") && line.length() > 12) {
                    msglimit30 = Double.parseDouble(line.substring(11));
                }
                if (line.startsWith("datastore=") && line.length() > 11) {
                    datastore = line.substring(10);
                }
                if (line.startsWith("youtubekey=") && line.length() > 12) {
                    youtubekey = line.substring(11);
                }
                if (line.startsWith("gamewispauth=") && line.length() > 14) {
                    gamewispauth = line.substring(13);
                }
                if (line.startsWith("gamewisprefresh=") && line.length() > 17) {
                    gamewisprefresh = line.substring(16);
                }
                if (line.startsWith("twitchalertstoken=") && line.length() > 19) {
                    twitchalertstoken = line.substring(18);
                }
                if (line.startsWith("lastfmuser=") && line.length() > 12) {
                    lastfmuser = line.substring(11);
                }
                if (line.startsWith("tpetoken=") && line.length() > 10) {
                    tpetoken = line.substring(9);
                }
                if (line.startsWith("twittertoken=") && line.length() > 14) {
                    twittertoken = line.substring(13);
                }
                if (line.startsWith("twittertokensecret=") && line.length() > 20) {
                    twittertokensecret = line.substring(19);
                }
                if (line.startsWith("streamtiptoken=") && line.length() > 16) {
                    streamtiptoken = line.substring(15);
                }
                if (line.startsWith("streamtipid=") && line.length() > 13) {
                    streamtipid = line.substring(12);
                }
                if (line.startsWith("webenable=") && line.length() > 11) {
                    webenable = Boolean.valueOf(line.substring(10));
                }
                if (line.startsWith("musicenable=") && line.length() > 13) {
                    musicenable = Boolean.valueOf(line.substring(12));
                }
                if (line.startsWith("usehttps=") && line.length() > 10) {
                    usehttps = Boolean.valueOf(line.substring(9));
                }
                if (line.startsWith("mysqlhost=") && line.length() > 11) {
                    mySqlHost = line.substring(10);
                }
                if (line.startsWith("mysqlport=") && line.length() > 11) {
                    mySqlPort = line.substring(10);
                }
                if (line.startsWith("mysqlname=") && line.length() > 11) {
                    mySqlName = line.substring(10);
                }
                if (line.startsWith("mysqluser=") && line.length() > 11) {
                    mySqlUser = line.substring(10);
                }
                if (line.startsWith("mysqlpass=") && line.length() > 11) {
                    mySqlPass = line.substring(10);
                }
                if (line.startsWith("keystorepath=") && line.length() > 14) {
                    keystorepath = line.substring(13);
                }
                if (line.startsWith("keystorepassword=") && line.length() > 18) {
                    keystorepassword = line.substring(17);
                }
                if (line.startsWith("webauth=") && line.length() > 9) {
                    webauth = line.substring(8);
                }
                if (line.startsWith("webauthro=") && line.length() > 11) {
                    webauthro = line.substring(10);
                }
                if (line.startsWith("discordtoken=") && line.length() >= 14) {
                    discordToken = line.substring(13);
                }
                if (line.startsWith("discordmainchannel=") && line.length() >= 20) {
                    discordMainChannel = line.substring(19);
                }
            }
        }
    } catch (IOException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }

    /**
     * Check to see if there's a soundboardauth set
     */
    if (webauth.isEmpty()) {
        webauth = generateWebAuth();
        com.gmt2001.Console.debug.println("New webauth key has been generated for botlogin.txt");
        changed = true;
    }
    /**
     * Check to see if there's a soundboardauthread set
     */
    if (webauthro.isEmpty()) {
        webauthro = generateWebAuth();
        com.gmt2001.Console.debug.println("New webauth read-only key has been generated for botlogin.txt");
        changed = true;
    }

    try {
        if (user.isEmpty()) {
            com.gmt2001.Console.out.print("Please enter the bot's twitch username: ");
            user = System.console().readLine().trim().toLowerCase();
            changed = true;
        }
        if (oauth.isEmpty()) {
            com.gmt2001.Console.out.println(
                    "Visit http://quorrabot.com/pages/twitchapi/ to generate oAuth tokens for both the bot and the channel owner accounts (including 'oauth:') & type it below.");
            com.gmt2001.Console.out
                    .println("IMPORTANT: This MUST be done while logged in as the BOT account!" + "\n");
            com.gmt2001.Console.out.println("Please enter the bot's tmi oauth token: ");
            oauth = System.console().readLine().trim();
            changed = true;
        }
        if (channelName.isEmpty()) {
            com.gmt2001.Console.out.print(
                    "Please enter the name of the twitch channel the bot should join (not the url, just the name): ");
            channelName = System.console().readLine().trim().toLowerCase();
            changed = true;
        }
        if (apioauth.isEmpty()) {
            com.gmt2001.Console.out.println(
                    "Visit http://quorrabot.com/pages/twitchapi/ to generate oAuth tokens for both the bot and the channel owner accounts (including 'oauth:') & type it below.");
            com.gmt2001.Console.out.println(
                    "IMPORTANT: This MUST be done while logged in on the CHANNEL OWNER account!" + "\n");
            com.gmt2001.Console.out.println("Please enter the channel owner's tmi oauth token: ");
            apioauth = System.console().readLine().trim();
            changed = true;
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }

    if (owner.isEmpty()) {
        owner = channelName;

        changed = true;
    }

    if (args.length > 0) {
        for (String arg : args) {
            if (arg.equalsIgnoreCase("printlogin")) {
                com.gmt2001.Console.out.println("user='" + user + "'");
                com.gmt2001.Console.out.println("oauth='" + oauth + "'");
                com.gmt2001.Console.out.println("apioauth='" + apioauth + "'");
                com.gmt2001.Console.out.println("clientid='" + clientid + "'");
                com.gmt2001.Console.out.println("channel='" + channelName + "'");
                com.gmt2001.Console.out.println("owner='" + owner + "'");
                com.gmt2001.Console.out.println("baseport='" + baseport + "'");
                com.gmt2001.Console.out.println("ip='" + ip.getHostAddress() + "'");
                com.gmt2001.Console.out.println("hostname='" + hostname + "'");
                com.gmt2001.Console.out.println("port='" + port + "'");
                com.gmt2001.Console.out.println("msglimit30='" + msglimit30 + "'");
                com.gmt2001.Console.out.println("datastore='" + datastore + "'");
                com.gmt2001.Console.out.println("youtubekey='" + youtubekey + "'");
                com.gmt2001.Console.out.println("gamewispauth=" + gamewispauth + "'");
                com.gmt2001.Console.out.println("gamewisprefresh=" + gamewisprefresh + "'");
                com.gmt2001.Console.out.println("twitchalertstoken='" + twitchalertstoken + "'");
                com.gmt2001.Console.out.println("lastfmuser='" + lastfmuser + "'");
                com.gmt2001.Console.out.println("tpetoken='" + tpetoken + "'");
                com.gmt2001.Console.out.println("twittertoken='" + twittertoken + "'");
                com.gmt2001.Console.out.println("twittertokensecret='" + twittertokensecret + "'");
                com.gmt2001.Console.out.println("streamtiptoken='" + streamtiptoken + "'");
                com.gmt2001.Console.out.println("streamtipid='" + streamtipid + "'");
                com.gmt2001.Console.out.println("webenable=" + webenable);
                com.gmt2001.Console.out.println("musicenable=" + musicenable);
                com.gmt2001.Console.out.println("usehttps=" + usehttps);
                com.gmt2001.Console.out.println("keystorepath='" + keystorepath + "'");
                com.gmt2001.Console.out.println("keystorepassword='" + keystorepassword + "'");
                com.gmt2001.Console.out.println("discordtoken='" + discordToken + "'");
                com.gmt2001.Console.out.println("discordmainchannel='" + discordMainChannel + "'");
            }
            if (arg.equalsIgnoreCase("debugon")) {
                Quorrabot.enableDebugging = true;
            }
            if (arg.equalsIgnoreCase("ini2sqlite")) {
                com.gmt2001.Console.out.println("Converting default IniStore to default SqliteStore...");
                ini2sqlite(false);
                com.gmt2001.Console.out.println("Operation complete. The bot will now exit");
                System.exit(0);
                return;
            }
            if (arg.toLowerCase().startsWith("user=") && arg.length() > 8) {
                if (!user.equals(arg.substring(5))) {
                    user = arg.substring(5).toLowerCase();
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("oauth=") && arg.length() > 9) {
                if (!oauth.equals(arg.substring(6))) {
                    oauth = arg.substring(6);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("apioauth=") && arg.length() > 12) {
                if (!apioauth.equals(arg.substring(9))) {
                    apioauth = arg.substring(9);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("mysqlhost=") && arg.length() > 11) {
                if (!mySqlHost.equals(arg.substring(10))) {
                    mySqlHost = arg.substring(10);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("mysqlport=") && arg.length() > 11) {
                if (!mySqlPort.equals(arg.substring(10))) {
                    mySqlPort = arg.substring(10);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("mysqlname=") && arg.length() > 11) {
                if (!mySqlName.equals(arg.substring(10))) {
                    mySqlName = arg.substring(10);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("mysqluser=") && arg.length() > 11) {
                if (!mySqlUser.equals(arg.substring(14))) {
                    mySqlUser = arg.substring(10);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("mysqlpass=") && arg.length() > 11) {
                if (!mySqlPass.equals(arg.substring(10))) {
                    mySqlPass = arg.substring(10);
                    changed = true;
                }
            }

            if (arg.toLowerCase().startsWith("clientid=") && arg.length() > 12) {
                if (!clientid.equals(arg.substring(9))) {
                    clientid = arg.substring(9);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("channel=") && arg.length() > 11) {
                if (!channelName.equals(arg.substring(8))) {
                    channelName = arg.substring(8).toLowerCase();
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("owner=") && arg.length() > 9) {
                if (!owner.equals(arg.substring(6))) {
                    owner = arg.substring(6).toLowerCase();
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("baseport=") && arg.length() > 10) {
                if (baseport != Integer.parseInt(arg.substring(9))) {
                    baseport = Integer.parseInt(arg.substring(9));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("ip=") && arg.length() > 4) {
                if (ip != InetAddress.getByName(arg.substring(3))) {
                    ip = InetAddress.getByName(arg.substring(3));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("hostname=") && arg.length() > 10) {
                if (!hostname.equals(arg.substring(9))) {
                    hostname = arg.substring(9);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("port=") && arg.length() > 6) {
                if (port != Integer.parseInt(arg.substring(5))) {
                    port = Integer.parseInt(arg.substring(5));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("msglimit30=") && arg.length() > 12) {
                if (msglimit30 != Double.parseDouble(arg.substring(11))) {
                    msglimit30 = Double.parseDouble(arg.substring(11));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("datastore=") && arg.length() > 11) {
                if (!datastore.equals(arg.substring(10))) {
                    datastore = arg.substring(10);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("datastoreconfig=") && arg.length() > 17) {
                datastoreconfig = arg.substring(16);
            }
            if (arg.toLowerCase().startsWith("youtubekey=") && arg.length() > 12) {
                if (!youtubekey.equals(arg.substring(11))) {
                    youtubekey = arg.substring(11);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("gamewispauth=") && arg.length() > 14) {
                if (!gamewispauth.equals(arg.substring(13))) {
                    gamewispauth = arg.substring(13);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("gamewisprefresh=") && arg.length() > 17) {
                if (!gamewisprefresh.equals(arg.substring(16))) {
                    gamewisprefresh = arg.substring(16);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("twitchalertstoken=") && arg.length() > 19) {
                if (!twitchalertstoken.equals(arg.substring(18))) {
                    twitchalertstoken = arg.substring(18);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("lastfmuser=") && arg.length() > 12) {
                if (!lastfmuser.equals(arg.substring(11))) {
                    lastfmuser = arg.substring(11);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("tpetoken=") && arg.length() > 10) {
                if (!tpetoken.equals(arg.substring(9))) {
                    tpetoken = arg.substring(9);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("twittertoken=") && arg.length() > 14) {
                if (!twittertoken.equals(arg.substring(13))) {
                    twittertoken = arg.substring(13);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("twittertokensecret=") && arg.length() > 20) {
                if (!twittertokensecret.equals(arg.substring(19))) {
                    twittertokensecret = arg.substring(19);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("streamtiptoken=") && arg.length() > 16) {
                if (!streamtiptoken.equals(arg.substring(15))) {
                    streamtiptoken = arg.substring(15);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("streamtipid=") && arg.length() > 13) {
                if (!streamtipid.equals(arg.substring(12))) {
                    streamtipid = arg.substring(12);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("webenable=") && arg.length() > 11) {
                if (webenable != Boolean.valueOf(arg.substring(10))) {
                    webenable = Boolean.valueOf(arg.substring(10));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("musicenable=") && arg.length() > 13) {
                if (musicenable != Boolean.valueOf(arg.substring(12))) {
                    musicenable = Boolean.valueOf(arg.substring(12));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("usehttps=") && arg.length() > 10) {
                if (usehttps != Boolean.valueOf(arg.substring(9))) {
                    usehttps = Boolean.valueOf(arg.substring(9));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("keystorepath=") && arg.length() > 14) {
                if (!keystorepath.equals(arg.substring(13))) {
                    keystorepath = arg.substring(13);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("keystorepassword=") && arg.length() > 18) {
                if (!keystorepassword.equals(arg.substring(17))) {
                    keystorepassword = arg.substring(17);
                    changed = true;
                }
            }

            if (arg.equalsIgnoreCase("help") || arg.equalsIgnoreCase("--help") || arg.equalsIgnoreCase("-h")
                    || arg.equalsIgnoreCase("-?")) {
                com.gmt2001.Console.out.println(
                        "Usage: java -Dfile.encoding=UTF-8 -jar QuorraBot.jar [printlogin] [user=<bot username>] "
                                + "[oauth=<bot irc oauth>] [apioauth=<editor oauth>] [clientid=<oauth clientid>] [channel=<channel to join>] "
                                + "[owner=<bot owner username>] [baseport=<bot webserver port, music server will be +1>] [ip=<IP address (optional) to bind to>] [hostname=<custom irc server>] "
                                + "[port=<custom irc port>] [msglimit30=<message limit per 30 seconds>] "
                                + "[datastore=<DataStore type, for a list, run java -jar QuorraBot.jar storetypes>] "
                                + "[datastoreconfig=<Optional DataStore config option, different for each DataStore type>] "
                                + "[youtubekey=<youtube api key>] [webenable=<true | false>] [musicenable=<true | false>] "
                                + "[gamewispauth=<gamewisp oauth>] "
                                + "[gamewisprefresh=<gamewisp refresh key>] "
                                + "[twitchalertstoken=<TwitchAlerts access token>] "
                                + "[lastfmuser=<Last.FM username>] " + "[tpetoken=<Tipeeestream access token>] "
                                + "[streamtiptoken=<StreamTip access token>] "
                                + "[streamtipid=<StreamTip Client ID>] "
                                + "[twittertoken=<Twitter access token>] "
                                + "[twittertokensecret=<Twitter access token secret>]");

                return;
            }
            if (arg.equalsIgnoreCase("storetypes")) {
                com.gmt2001.Console.out.println(
                        "DataStore types: IniStore (datastoreconfig parameter is folder name, stores in .ini files), "
                                + "TempStore (Stores in memory, lost on shutdown), "
                                + "SqliteStore (Default, Stores in a SQLite3 database, datastoreconfig parameter is a config file");
                return;
            }
        }
    }

    if (changed) {
        String data = "";
        data += "user=" + user + "\r\n";
        data += "oauth=" + oauth + "\r\n";
        data += "apioauth=" + apioauth + "\r\n";
        data += "clientid=" + clientid + "\r\n";
        data += "webauth=" + webauth + "\r\n";
        data += "webauthro=" + webauthro + "\r\n";
        data += "channel=" + channelName + "\r\n";
        data += "owner=" + owner + "\r\n";
        data += "baseport=" + baseport + "\r\n";
        data += "ip=" + ip.getHostAddress() + "\r\n";
        data += "hostname=" + hostname + "\r\n";
        data += "port=" + port + "\r\n";
        data += "msglimit30=" + msglimit30 + "\r\n";
        data += "datastore=" + datastore + "\r\n";
        data += "youtubekey=" + youtubekey + "\r\n";
        data += "gamewispauth=" + gamewispauth + "\r\n";
        data += "gamewisprefresh=" + gamewisprefresh + "\r\n";
        data += "twitchalertstoken=" + twitchalertstoken + "\r\n";
        data += "lastfmuser=" + lastfmuser + "\r\n";
        data += "tpetoken=" + tpetoken + "\r\n";
        data += "twittertoken=" + twittertoken + "\r\n";
        data += "twittertokensecret=" + twittertokensecret + "\r\n";
        data += "streamtiptoken=" + streamtiptoken + "\r\n";
        data += "streamtipid=" + streamtipid + "\r\n";
        data += "webenable=" + webenable + "\r\n";
        data += "musicenable=" + musicenable + "\r\n";
        data += "usehttps=" + usehttps + "\r\n";
        data += "logtimezone=" + timeZone + "\r\n";
        data += "mysqlhost=" + mySqlHost + "\r\n";
        data += "mysqlport=" + mySqlPort + "\r\n";
        data += "mysqlname=" + mySqlName + "\r\n";
        data += "mysqluser=" + mySqlUser + "\r\n";
        data += "mysqlpass=" + mySqlPass + "\r\n";
        data += "keystorepath=" + keystorepath + "\r\n";
        data += "keystorepassword=" + keystorepassword + "\r\n";
        data += "discordtoken=" + discordToken + "\r\n";
        data += "discordmainchannel=" + discordMainChannel;

        Files.write(Paths.get("./botlogin.txt"), data.getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
    }
    channelUsersCache = ChannelUsersCache.instance(owner);
    followersCache = FollowersCache.instance(owner);
    hostCache = ChannelHostCache.instance(owner);
    subscribersCache = SubscribersCache.instance(owner);

    Quorrabot.instance = new Quorrabot(user, oauth, apioauth, clientid, channelName, owner, baseport, ip,
            hostname, port, msglimit30, datastore, datastoreconfig, youtubekey, gamewispauth, gamewisprefresh,
            twitchalertstoken, lastfmuser, tpetoken, twittertoken, twittertokensecret, streamtiptoken,
            streamtipid, webenable, webauth, webauthro, musicenable, usehttps, timeZone, mySqlHost, mySqlPort,
            mySqlConn, mySqlPass, mySqlUser, mySqlName, keystorepath, followersCache, hostCache,
            channelUsersCache, subscribersCache, discordToken, discordMainChannel);
}