Example usage for java.lang String equals

List of usage examples for java.lang String equals

Introduction

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

Prototype

public boolean equals(Object anObject) 

Source Link

Document

Compares this string to the specified object.

Usage

From source file:Main.java

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

    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);//w  w w. ja v  a  2  s .  c  om

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);

    try {
        connection.createStatement().execute("select wrong");
    } catch (SQLException e) {
        while (e != null) {
            String message = e.getMessage();

            String sqlState = e.getSQLState();

            int errorCode = e.getErrorCode();

            driverName = connection.getMetaData().getDriverName();
            if (driverName.equals("Oracle JDBC Driver") && errorCode == 123) {
            }

            e = e.getNextException();
        }
    }

}

From source file:TypeInfoWriter.java

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

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

    // variables
    XMLReader parser = null;
    Vector schemas = null;
    Vector instances = null;
    String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;

    // 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("l")) {
                // get schema language name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -l option.");
                } else {
                    schemaLanguage = argv[i];
                }
                continue;
            }
            if (option.equals("p")) {
                // get parser name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -p option.");
                    continue;
                }
                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);
                        System.exit(1);
                    }
                }
                continue;
            }
            if (arg.equals("-a")) {
                // process -a: schema documents
                if (schemas == null) {
                    schemas = new Vector();
                }
                while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
                    schemas.add(arg);
                    ++i;
                }
                continue;
            }
            if (arg.equals("-i")) {
                // process -i: instance documents
                if (instances == null) {
                    instances = new Vector();
                }
                while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
                    instances.add(arg);
                    ++i;
                }
                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.equals("h")) {
                printUsage();
                continue;
            }
            System.err.println("error: unknown option (" + option + ").");
            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);
            System.exit(1);
        }
    }

    try {
        // Create writer
        TypeInfoWriter writer = new TypeInfoWriter();
        writer.setOutput(System.out, "UTF8");

        // Create SchemaFactory and configure
        SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage);
        factory.setErrorHandler(writer);

        try {
            factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Build Schema from sources
        Schema schema;
        if (schemas != null && schemas.size() > 0) {
            final int length = schemas.size();
            StreamSource[] sources = new StreamSource[length];
            for (int j = 0; j < length; ++j) {
                sources[j] = new StreamSource((String) schemas.elementAt(j));
            }
            schema = factory.newSchema(sources);
        } else {
            schema = factory.newSchema();
        }

        // Setup validator and parser
        ValidatorHandler validator = schema.newValidatorHandler();
        parser.setContentHandler(validator);
        if (validator instanceof DTDHandler) {
            parser.setDTDHandler((DTDHandler) validator);
        }
        parser.setErrorHandler(writer);
        validator.setContentHandler(writer);
        validator.setErrorHandler(writer);
        writer.setTypeInfoProvider(validator.getTypeInfoProvider());

        try {
            validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err
                    .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Validator does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Validate instance documents and print type information
        if (instances != null && instances.size() > 0) {
            final int length = instances.size();
            for (int j = 0; j < length; ++j) {
                parser.parse((String) instances.elementAt(j));
            }
        }
    } 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:HexFormat.java

public static void main(String[] args) {
    String result;
    HexFormat format = new HexFormat();

    // byte/*  ww  w . j  a  va 2 s .co  m*/
    byte bNumber = 0x33;
    result = format.format(bNumber);
    if (result.equals("33")) {
        System.out.print("Success => ");
    } else {
        System.out.print("FAILURE => ");
    }
    System.out.println("Byte: " + bNumber + " (0x" + result + ")");

    bNumber = (byte) 0x85;
    result = format.format(bNumber);
    if (result.equals("85")) {
        System.out.print("Success => ");
    } else {
        System.out.print("FAILURE => ");
    }
    System.out.println("Byte: " + bNumber + " (0x" + result + ")");

    bNumber = (byte) 0x0f;
    result = format.format(bNumber);
    if (result.equals("0f")) {
        System.out.print("Success => ");
    } else {
        System.out.print("FAILURE => ");
    }
    System.out.println("Byte: " + bNumber + " (0x" + result + ")");

    short sNumber = (short) 0xa2b6;
    result = format.format(sNumber);
    if (result.equals("a2b6")) {
        System.out.print("Success => ");
    } else {
        System.out.print("FAILURE => ");
    }
    System.out.println("Byte: " + bNumber + " (0x" + result + ")");

    format.setUpperCase(true);

    int iNumber = (int) 0x4321fedc;
    result = format.format(iNumber);
    if (result.equals("4321FEDC")) {
        System.out.print("Success => ");
    } else {
        System.out.print("FAILURE => ");
    }
    System.out.println("Byte: " + bNumber + " (0x" + result + ")");

    long lNumber = (long) 0x4321fedc4321fedcL;
    result = format.format(lNumber);
    if (result.equals("4321FEDC4321FEDC")) {
        System.out.print("Success => ");
    } else {
        System.out.print("FAILURE => ");
    }
    System.out.println("Byte: " + bNumber + " (0x" + result + ")");

    String num = "0xfe";
    Number number = null;
    Byte bExpect = new Byte((byte) 0xfe);
    try {
        number = format.parse(num);
    } catch (ParseException e) {
        System.out.println(e);
        e.printStackTrace();
    }
    if ((number instanceof Byte) && (number.equals(bExpect))) {
        System.out.print("Success => ");
    } else {
        System.out.print("FAILURE => ");
    }
    System.out.println("Byte: " + bExpect + " result: " + number);

    num = "0xf";
    number = null;
    bExpect = new Byte((byte) 0xf);
    try {
        number = format.parse(num);
    } catch (ParseException e) {
        System.out.println(e);
        e.printStackTrace();
    }
    if ((number instanceof Byte) && (number.equals(bExpect))) {
        System.out.print("Success => ");
    } else {
        System.out.print("FAILURE => ");
    }
    System.out.println("Byte: " + bExpect + " result: " + number);

    num = "0xf0f0";
    number = null;
    Short sExpect = new Short((short) 0xf0f0);
    try {
        number = format.parse(num);
    } catch (ParseException e) {
        System.out.println(e);
        e.printStackTrace();
    }
    if ((number instanceof Short) && (number.equals(sExpect))) {
        System.out.print("Success => ");
    } else {
        System.out.print("FAILURE => ");
    }
    System.out.println("Short: " + sExpect + " result: " + number);

    num = "0xdEAdbEEf";
    number = null;
    Integer iExpect = new Integer((int) 0xdEAdbEEf);
    try {
        number = format.parse(num);
    } catch (ParseException e) {
        System.out.println(e);
        e.printStackTrace();
    }
    if ((number instanceof Integer) && (number.equals(iExpect))) {
        System.out.print("Success => ");
    } else {
        System.out.print("FAILURE => ");
    }
    System.out.println("Integer: " + iExpect + " result: " + number);
}

From source file:at.tuwien.ifs.somtoolbox.apps.helper.VectorSimilarityWriter.java

public static void main(String[] args) throws ClassNotFoundException, InstantiationException,
        IllegalAccessException, IOException, SOMToolboxException {
    JSAPResult config = OptionFactory.parseResults(args, OptionFactory.OPTIONS_INPUT_SIMILARITY_COMPUTER);
    String inputVectorDistanceMatrix = config.getString("inputVectorDistanceMatrix");
    String inputVectorFileName = config.getString("inputVectorFile");
    int numNeighbours = config.getInt("numberNeighbours");
    String outputFormat = config.getString("outputFormat");

    InputVectorDistanceMatrix matrix = null;
    InputData data = new SOMLibSparseInputData(inputVectorFileName);

    if (StringUtils.isNotBlank(inputVectorDistanceMatrix)) {
        matrix = InputVectorDistanceMatrix.initFromFile(inputVectorDistanceMatrix);
    } else {/*from w ww .ja  v a 2s. c  o  m*/
        String metricName = config.getString("metric");
        DistanceMetric metric = AbstractMetric.instantiate(metricName);
        matrix = new LeightWeightMemoryInputVectorDistanceMatrix(data, metric);
    }

    String outputFileName = config.getString("output");
    PrintWriter w = FileUtils.openFileForWriting("Similarity File", outputFileName);

    if (outputFormat.equals("SAT-DB")) {
        // find feature type
        String type = "";
        if (inputVectorFileName.endsWith(".rh") || inputVectorFileName.endsWith(".rp")
                || inputVectorFileName.endsWith(".ssd")) {
            type = "_" + inputVectorFileName.substring(inputVectorFileName.lastIndexOf(".") + 1);
        }
        w.println("INSERT INTO `sat_track_similarity_ifs" + type
                + "` (`TRACKID`, `SIMILARITYCOUNT`, `SIMILARITYIDS`) VALUES ");
    }

    int numVectors = matrix.numVectors();
    // numVectors = 10; // for testing
    StdErrProgressWriter progress = new StdErrProgressWriter(numVectors, "Writing similarities for vector ", 1);
    for (int i = 0; i < numVectors; i++) {
        int[] nearest = matrix.getNNearest(i, numNeighbours);
        if (outputFormat.equals("SAT-DB")) {
            w.print("  (" + i + " , NULL, '");
            for (int j = 0; j < nearest.length; j++) {
                String label = data.getLabel(nearest[j]);
                w.print(label.replace(".mp3", "")); // strip ending
                if (j + 1 < nearest.length) {
                    w.print(",");
                } else {
                    w.print("')");
                }
            }
            if (i + 1 < numVectors) {
                w.print(",");
            }
        } else {
            w.print(data.getLabel(i) + ",");
            for (int j = 0; j < nearest.length; j++) {
                w.print(data.getLabel(nearest[j]));
                if (j + 1 < nearest.length) {
                    w.print(",");
                }
            }
        }
        w.println();
        w.flush();
        progress.progress();
    }
    if (outputFormat.equals("SAT-DB")) {
        w.print(";");
    }
    w.flush();
    w.close();
}

From source file:fr.ens.biologie.genomique.eoulsan.Main.java

/**
 * Main method of the program.//from   w w  w  .j ava2  s. c  o m
 * @param args command line arguments
 */
public static void main(final String[] args) {

    if (main != null) {
        throw new IllegalAccessError("Main method cannot be run twice.");
    }

    // Set the default local for all the application
    Globals.setDefaultLocale();

    // Check Java version
    if (getJavaVersion() < MINIMAL_JAVA_VERSION_REQUIRED) {
        Common.showErrorMessageAndExit(Globals.WELCOME_MSG + "\nError: " + Globals.APP_NAME + " requires Java "
                + MINIMAL_JAVA_VERSION_REQUIRED + ".");
    }

    // Select the application execution mode
    final String eoulsanMode = System.getProperty(Globals.LAUNCH_MODE_PROPERTY);

    if (eoulsanMode != null && eoulsanMode.equals("local")) {
        main = new MainCLI(args);
    } else {
        main = new MainHadoop(args);
    }

    // Get the action to execute
    final Action action = main.getAction();

    // Get the Eoulsan settings
    final Settings settings = EoulsanRuntime.getSettings();

    // Test if action can be executed with current platform
    if (!settings.isBypassPlatformChecking() && !action.isCurrentArchCompatible()) {
        Common.showErrorMessageAndExit(Globals.WELCOME_MSG + "\nError: The " + action.getName() + " of "
                + Globals.APP_NAME + " is not available for your platform. Required platforms: "
                + availableArchsToString() + ".");

    }

    try {

        getLogger().info("Start " + action.getName() + " action");

        // Run action
        action.action(main.getActionArgs());

        getLogger().info("End of " + action.getName() + " action");

    } catch (Throwable e) {
        Common.errorExit(e, e.getMessage());
    }

    // Flush logs
    main.flushLog();
}

From source file:DIA_Umpire_Quant.DIA_Umpire_LCMSIDGen.java

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:com.google.testing.pogen.PageObjectGenerator.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    if (args.length == 0) {
        printUsage(System.out);//from   w ww. ja v  a2s  .  co m
        return;
    }

    String commandName = args[0];
    // @formatter:off
    Options options = new Options()
            .addOption(OptionBuilder.withDescription(
                    "Attribute name to be assigned in tagas containing template variables (default is 'id').")
                    .hasArg().withLongOpt("attr").create('a'))
            .addOption(OptionBuilder.withDescription("Print help for this command.").withLongOpt("help")
                    .create('h'))
            .addOption(OptionBuilder.withDescription("Print processed files verbosely.").withLongOpt("verbose")
                    .create('v'));
    // @formatter:on

    String helpMessage = null;
    if (commandName.equals(GENERATE_COMMAND)) {
        // @formatter:off
        options.addOption(OptionBuilder.withDescription("Package name of generating skeleton test code.")
                .hasArg().isRequired().withLongOpt("package").create('p'))
                .addOption(OptionBuilder.withDescription("Output directory of generating skeleton test code.")
                        .hasArg().isRequired().withLongOpt("out").create('o'))
                .addOption(OptionBuilder.withDescription(
                        "Root input directory of html template files for analyzing the suffixes of the package name.")
                        .hasArg().isRequired().withLongOpt("in").create('i'))
                .addOption(OptionBuilder.withDescription("Regex for finding html template files.").hasArg()
                        .withLongOpt("regex").create('e'))
                .addOption(OptionBuilder.withDescription("Option for finding html template files recursively.")
                        .withLongOpt("recursive").create('r'));
        // @formatter:on
        helpMessage = "java PageObjectGenerator generate -o <test_out_dir> -p <package_name> -i <root_directory> "
                + " [OPTIONS] <template_file1> <template_file2> ...\n"
                + "e.g. java PageObjectGenerator generate -a class -o PageObjectGeneratorTest/src/test/java/com/google/testing/pogen/pages"
                + " -i PageObjectGeneratorTest/src/main/resources -p com.google.testing.pogen.pages -e (.*)\\.html -v";
    } else if (commandName.equals(MEASURE_COMMAND)) {
        helpMessage = "java PageObjectGenerator measure [OPTIONS] <template_file1> <template_file2> ...";
    } else if (commandName.equals(LIST_COMMAND)) {
        helpMessage = "java PageObjectGenerator list <template_file1> <template_file2> ...";
    } else {
        System.err.format("'%s' is not a PageObjectGenerator command.", commandName);
        printUsage(System.err);
        System.exit(-1);
    }

    BasicParser cmdParser = new BasicParser();
    HelpFormatter f = new HelpFormatter();
    try {
        CommandLine cl = cmdParser.parse(options, Arrays.copyOfRange(args, 1, args.length));
        if (cl.hasOption('h')) {
            f.printHelp(helpMessage, options);
            return;
        }

        Command command = null;
        String[] templatePaths = cl.getArgs();
        String attributeName = cl.getOptionValue('a');
        attributeName = attributeName != null ? attributeName : "id";
        if (commandName.equals(GENERATE_COMMAND)) {
            String rootDirectoryPath = cl.getOptionValue('i');
            String templateFilePattern = cl.getOptionValue('e');
            boolean isRecusive = cl.hasOption('r');
            command = new GenerateCommand(templatePaths, cl.getOptionValue('o'), cl.getOptionValue('p'),
                    attributeName, cl.hasOption('v'), rootDirectoryPath, templateFilePattern, isRecusive);
        } else if (commandName.equals(MEASURE_COMMAND)) {
            command = new MeasureCommand(templatePaths, attributeName, cl.hasOption('v'));
        } else if (commandName.equals(LIST_COMMAND)) {
            command = new ListCommand(templatePaths, attributeName);
        }
        try {
            command.execute();
            return;
        } catch (FileProcessException e) {
            System.err.println(e.getMessage());
        } catch (IOException e) {
            System.err.println("Errors occur in processing files.");
            System.err.println(e.getMessage());
        }
    } catch (ParseException e) {
        System.err.println("Errors occur in parsing the command arguments.");
        System.err.println(e.getMessage());
        f.printHelp(helpMessage, options);
    }
    System.exit(-1);
}

From source file:net.frontlinesms.DesktopLauncher.java

/**
 * Main class for launching the FrontlineSMS project.
 * @param args//from   ww w.j a v a 2 s.c  o m
 */
public static void main(String[] args) {
    FrontlineSMS frontline = null;
    try {
        AppProperties appProperties = AppProperties.getInstance();
        final String VERSION = BuildProperties.getInstance().getVersion();
        LOG.info("FrontlineSMS version [" + VERSION + "]");
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        String lastVersion = appProperties.getLastRunVersion();
        InputStream defaultResourceArchive = ResourceUtils.class.getResourceAsStream("/resources.zip");
        if (defaultResourceArchive == null) {
            LOG.fatal("Default resources archive could not be found!");
            throw new Exception("Default resources archive could not be found!");
        }

        ResourceUtils.unzip(defaultResourceArchive, new File(ResourceUtils.getConfigDirectoryPath()),
                !VERSION.equals(lastVersion));

        // This should always get the English bundle, as other languages are only included in
        // resources.zip rather than in the resources/languages directory
        LanguageBundle englishBundle = InternationalisationUtils.getDefaultLanguageBundle();
        Thinlet.DEFAULT_ENGLISH_BUNDLE = englishBundle.getProperties();

        // If the user has currently no User ID defined
        // We generate one
        if (appProperties.getUserId() == null) {
            appProperties.setUserId(generateUserId());
        }

        boolean showWizard = appProperties.isShowWizard();
        appProperties.setLastRunVersion(VERSION);
        appProperties.saveToDisk();

        frontline = initFrontline();
        if (showWizard) {
            new FirstTimeWizard(frontline);
        } else {
            // Auto-detect phones.
            new UiGeneratorController(frontline, true);
        }
    } catch (Throwable t) {
        if (frontline != null)
            frontline.destroy();

        // Rather than swallowing the error, we now display it to the user
        // so that they can give us some feedback :)
        ErrorUtils.showErrorDialog("Fatal error starting FrontlineSMS!",
                "A problem ocurred during FrontlineSMS startup.", t, true);
    }
}

From source file:org.spring.springxdcloudInstaller.MainApp.java

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

    if (args.length < PARAMETERS)
        throw new IllegalArgumentException(INVALID_SYNTAX);

    // Args//from  w  w  w .j a v  a  2  s . c  om
    String accesskeyid = args[0];
    String secretkey = args[1];
    String command = args[2];
    String name = args[3];
    String type = args[4];
    DeployType deployType = getTypeByString(type);
    if (deployType == null) {
        throw new IllegalArgumentException(INVALID_TYPE);
    }
    // Init
    RestContext<EC2Client, EC2AsyncClient> context = ContextBuilder.newBuilder("aws-ec2")
            .credentials(accesskeyid, secretkey).build();

    // Get a synchronous client
    EC2Client client = context.getApi();
    CloudCommand cloudCommand = new CloudCommand(accesskeyid, secretkey);
    try {
        if (command.equals("create")) {
            //            cloudCommand.runCommand("mkdir -p /home/ubuntu/org/spring/springxdcloudInstaller/util", "us-east-1/i-e16ae686");
            //            cloudCommand.sshCopy("/Users/renfrg/projects/xd-cloud-installer/target/classes/org/spring/springxdcloudInstaller/util/ConfigureSystem.class",
            //                  "ec2-50-16-90-175.compute-1.amazonaws.com","us-east-1/i-e16ae686");
            //            cloudCommand.runCommand("java -cp /home/ubuntu org.spring.springxdcloudInstaller.util.ConfigureSystem ", "us-east-1/i-e16ae686");

            execute(client, name, getTypeByString(type), cloudCommand);
            System.out.println(getLatestBuild());

        } else if (command.equals("destroy")) {
            destroySecurityGroupKeyPairAndInstance(client, name);
        } else {
            throw new IllegalArgumentException(INVALID_SYNTAX);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        // Close connection
        context.close();
        System.exit(0);
    }

}

From source file:com.rabbitmq.examples.FileConsumer.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption(new Option("h", "uri", true, "AMQP URI"));
    options.addOption(new Option("q", "queue", true, "queue name"));
    options.addOption(new Option("t", "type", true, "exchange type"));
    options.addOption(new Option("e", "exchange", true, "exchange name"));
    options.addOption(new Option("k", "routing-key", true, "routing key"));
    options.addOption(new Option("d", "directory", true, "output directory"));

    CommandLineParser parser = new GnuParser();

    try {/*from w w w. j ava  2s.c om*/
        CommandLine cmd = parser.parse(options, args);

        String uri = strArg(cmd, 'h', "amqp://localhost");
        String requestedQueueName = strArg(cmd, 'q', "");
        String exchangeType = strArg(cmd, 't', "direct");
        String exchange = strArg(cmd, 'e', null);
        String routingKey = strArg(cmd, 'k', null);
        String outputDirName = strArg(cmd, 'd', ".");

        File outputDir = new File(outputDirName);
        if (!outputDir.exists() || !outputDir.isDirectory()) {
            System.err.println("Output directory must exist, and must be a directory.");
            System.exit(2);
        }

        ConnectionFactory connFactory = new ConnectionFactory();
        connFactory.setUri(uri);
        Connection conn = connFactory.newConnection();

        final Channel ch = conn.createChannel();

        String queueName = (requestedQueueName.equals("") ? ch.queueDeclare()
                : ch.queueDeclare(requestedQueueName, false, false, false, null)).getQueue();

        if (exchange != null || routingKey != null) {
            if (exchange == null) {
                System.err.println("Please supply exchange name to bind to (-e)");
                System.exit(2);
            }
            if (routingKey == null) {
                System.err.println("Please supply routing key pattern to bind to (-k)");
                System.exit(2);
            }
            ch.exchangeDeclare(exchange, exchangeType);
            ch.queueBind(queueName, exchange, routingKey);
        }

        QueueingConsumer consumer = new QueueingConsumer(ch);
        ch.basicConsume(queueName, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            Map<String, Object> headers = delivery.getProperties().getHeaders();
            byte[] body = delivery.getBody();
            Object headerFilenameO = headers.get("filename");
            String headerFilename = (headerFilenameO == null) ? UUID.randomUUID().toString()
                    : headerFilenameO.toString();
            File givenName = new File(headerFilename);
            if (givenName.getName().equals("")) {
                System.out.println("Skipping file with empty name: " + givenName);
            } else {
                File f = new File(outputDir, givenName.getName());
                System.out.print("Writing " + f + " ...");
                FileOutputStream o = new FileOutputStream(f);
                o.write(body);
                o.close();
                System.out.println(" done.");
            }
            ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
    } catch (Exception ex) {
        System.err.println("Main thread caught exception: " + ex);
        ex.printStackTrace();
        System.exit(1);
    }
}