Example usage for java.io File exists

List of usage examples for java.io File exists

Introduction

In this page you can find the example usage for java.io File exists.

Prototype

public boolean exists() 

Source Link

Document

Tests whether the file or directory denoted by this abstract pathname exists.

Usage

From source file:de.prozesskraft.ptest.Compare.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try/*from   w ww  . j av  a  2 s  .c  o m*/
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Compare.class) + "/" + "../etc/ptest-compare.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option oref = OptionBuilder.withArgName("PATH").hasArg()
            .withDescription("[mandatory] directory or fingerprint, that the --exam will be checked against")
            //            .isRequired()
            .create("ref");

    Option oexam = OptionBuilder.withArgName("PATH").hasArg().withDescription(
            "[optional; default: parent directory of -ref] directory or fingerprint, that will be checked against --ref")
            //            .isRequired()
            .create("exam");

    Option oresult = OptionBuilder.withArgName("FILE").hasArg().withDescription(
            "[mandatory; default: result.txt] the result (success|failed) of the comparison will be printed to this file")
            //            .isRequired()
            .create("result");

    Option osummary = OptionBuilder.withArgName("all|error|debug").hasArg().withDescription(
            "[optional] 'error' prints a summary reduced to failed matches. 'all' prints a full summary. 'debug' is like 'all' plus debug statements")
            //            .isRequired()
            .create("summary");

    Option omd5 = OptionBuilder.withArgName("no|yes").hasArg()
            .withDescription("[optional; default: yes] to ignore md5 information in comparison use -md5=no")
            //            .isRequired()
            .create("md5");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(oref);
    options.addOption(oexam);
    options.addOption(oresult);
    options.addOption(osummary);
    options.addOption(omd5);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);

    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("compare", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.err.println("web:     " + web);
        System.err.println("author: " + author);
        System.err.println("version:" + version);
        System.err.println("date:     " + date);
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    boolean error = false;
    String result = "";
    boolean md5 = false;
    String ref = null;
    String exam = null;

    if (!(commandline.hasOption("ref"))) {
        System.err.println("option -ref is mandatory");
        error = true;
    } else {
        ref = commandline.getOptionValue("ref");
    }

    if (!(commandline.hasOption("exam"))) {
        java.io.File refFile = new java.io.File(ref).getCanonicalFile();
        java.io.File examFile = refFile.getParentFile();
        exam = examFile.getCanonicalPath();

        System.err.println("setting default: -exam=" + exam);
    } else {
        exam = commandline.getOptionValue("exam");
    }

    if (error) {
        exiter();
    }

    if (!(commandline.hasOption("result"))) {
        System.err.println("setting default: -result=result.txt");
        result = "result.txt";
    }

    if (!(commandline.hasOption("md5"))) {
        System.err.println("setting default: -md5=yes");
        md5 = true;
    } else if (commandline.getOptionValue("md5").equals("no")) {
        md5 = false;
    } else if (commandline.getOptionValue("md5").equals("yes")) {
        md5 = true;
    } else {
        System.err.println("use only values no|yes for -md5");
        System.exit(1);
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    // einlesen der referenzdaten
    java.io.File refPath = new java.io.File(ref);

    Dir refDir = new Dir();

    // wenn es ein directory ist, muss der fingerprint erzeugt werden
    if (refPath.exists() && refPath.isDirectory()) {
        refDir.setBasepath(refPath.getCanonicalPath());
        refDir.genFingerprint(0f, true, new ArrayList<String>());
        refDir.setRespectMd5Recursive(md5);
        System.err.println("-ref is a directory");
    }
    // wenn es ein fingerprint ist, muss er eingelesen werden
    else if (refPath.exists()) {
        refDir.setInfilexml(refPath.getCanonicalPath());
        System.err.println("-ref is a fingerprint");
        try {
            refDir.readXml();
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        refDir.setRespectMd5Recursive(md5);
    } else if (!refPath.exists()) {
        System.err.println("-ref does not exist! " + refPath.getAbsolutePath());
        exiter();
    }

    // einlesen der prueflingsdaten
    java.io.File examPath = new java.io.File(exam);

    Dir examDir = new Dir();

    // wenn es ein directory ist, muss der fingerprint erzeugt werden
    if (examPath.exists() && examPath.isDirectory()) {
        examDir.setBasepath(examPath.getCanonicalPath());
        examDir.genFingerprint(0f, true, new ArrayList<String>());
        examDir.setRespectMd5Recursive(md5);
        System.err.println("-exam is a directory");
    }
    // wenn es ein fingerprint ist, muss er eingelesen werden
    else if (examPath.exists()) {
        examDir.setInfilexml(examPath.getCanonicalPath());
        System.err.println("-exam is a fingerprint");
        try {
            examDir.readXml();
        } catch (JAXBException e) {
            System.err.println("error while reading xml");
            e.printStackTrace();
        }
        examDir.setRespectMd5Recursive(md5);
    } else if (!examPath.exists()) {
        System.err.println("-exam does not exist! " + examPath.getAbsolutePath());
        exiter();
    }

    // durchfuehren des vergleichs
    refDir.runCheck(examDir);

    //      if(examDir.isMatchSuccessfullRecursive() && refDir.isMatchSuccessfullRecursive())
    if (refDir.isMatchSuccessfullRecursive()) {
        System.out.println("SUCCESS");
    } else {
        System.out.println("FAILED");
    }

    // printen der csv-ergebnis-tabelle
    if (commandline.hasOption("summary")) {
        if (commandline.getOptionValue("summary").equals("error")) {
            System.err.println("the results of the reference are crucial for result FAILED|SUCCESS");
            System.err.println(refDir.sprintSummaryAsCsv("error"));
            System.err.println(examDir.sprintSummaryAsCsv("error"));
        } else if (commandline.getOptionValue("summary").equals("all")) {
            System.err.println(refDir.sprintSummaryAsCsv("all"));
            System.err.println(examDir.sprintSummaryAsCsv("all"));
        } else if (commandline.getOptionValue("summary").equals("debug")) {
            System.err.println(refDir.sprintSummaryAsCsv("all"));
            System.err.println(examDir.sprintSummaryAsCsv("all"));
            // printen des loggings
            System.err.println("------ logging of reference --------");
            System.err.println(refDir.getLogAsStringRecursive());
            System.err.println("------ logging of examinee --------");
            System.err.println(examDir.getLogAsStringRecursive());
        } else {
            System.err.println("for option -summary you only may use all|error");
            exiter();
        }
    }

}

From source file:ffx.Main.java

/**
 * Create an instance of Force Field X/*from w  w  w.  ja  va  2  s . co m*/
 *
 * @param args an array of {@link java.lang.String} objects.
 * @throws java.lang.Exception if any.
 */
public static void main(String[] args) throws Exception {
    /**
     * Process any "-D" command line flags.
     */
    args = processProperties(args);

    /**
     * Configure our logging.
     */
    startLogging();

    /**
     * Print out help for the command line interface.
     */
    if (GraphicsEnvironment.isHeadless() && args.length < 2) {
        commandLineInterfaceHelp();
    }

    /**
     * Determine host name and process ID.
     */
    environment();

    /**
     * Start up the Parallel Java communication layer.
     */
    startParallelJava(args);

    /**
     * Run the pKa input GUI if requested. Halts execution until GUI exits.
     */
    /**
     * if (System.getProperty("pKaCalc") != null) { if
     * (System.getProperty("pKaCalc").equals("true")) { ffx.pka.pKaRun
     * runnable = new ffx.pka.pKaRun(); Thread t = new Thread(runnable,"pKa
     * Thread"); t.start(); t.join(); final int NUM_PKA_ARGS = 25; String[]
     * newArgs = new String[NUM_PKA_ARGS]; int currentArg = 0; for (int i=0;
     * i < newArgs.length; i++) { newArgs[currentArg] = runnable.getArg(i);
     * if (runnable.getArg(i) == null) { String temp = runnable.getArg(i -
     * 1); if (temp.startsWith("-s") || temp.startsWith("-f")) {
     * currentArg--; } } else { currentArg++; } } args = newArgs; } }
     */
    // Print the header.
    // Moved this here so I could see the args being supplied by pKaRun.
    header(args);

    /**
     * Parse the specified command or structure file.
     */
    File commandLineFile = null;
    int nArgs = args.length;
    if (nArgs > 0) {
        commandLineFile = new File(args[0]);
        // Resolve a relavtive path
        if (commandLineFile.exists()) {
            commandLineFile = new File(FilenameUtils.normalize(commandLineFile.getAbsolutePath()));
        }
    }

    /**
     * Convert the args to a List<String>.
     */
    List<String> argList = new ArrayList<>(nArgs);
    if (nArgs > 1) {
        for (int i = 1; i < nArgs; i++) {
            argList.add(args[i]);
        }
    }

    /**
     * Start up the GUI or CLI version of Force Field X.
     */
    if (!GraphicsEnvironment.isHeadless()) {
        startGraphicalUserInterface(commandLineFile, argList);
    } else {
        startCommandLineInterface(commandLineFile, argList);
    }
}

From source file:com.zimbra.cs.util.SpamExtract.java

public static void main(String[] args) throws ServiceException, HttpException, SoapFaultException, IOException {
    CommandLine cl = parseArgs(args);//from  w  w  w.j a  va2  s.c om

    if (cl.hasOption('D')) {
        CliUtil.toolSetup("DEBUG");
    } else {
        CliUtil.toolSetup("INFO");
    }
    if (cl.hasOption('v')) {
        verbose = true;
    }

    boolean optDelete = cl.hasOption('d');

    if (!cl.hasOption('o')) {
        usage("must specify directory to extract messages to");
    }
    String optDirectory = cl.getOptionValue('o');
    File outputDirectory = new File(optDirectory);
    if (!outputDirectory.exists()) {
        LOG.info("Creating directory: " + optDirectory);
        outputDirectory.mkdirs();
        if (!outputDirectory.exists()) {
            LOG.error("could not create directory " + optDirectory);
            System.exit(2);
        }
    }

    String optAdminUser;
    if (cl.hasOption('a')) {
        optAdminUser = cl.getOptionValue('a');
    } else {
        optAdminUser = LC.zimbra_ldap_user.value();
    }

    String optAdminPassword;
    if (cl.hasOption('p')) {
        optAdminPassword = cl.getOptionValue('p');
    } else {
        optAdminPassword = LC.zimbra_ldap_password.value();
    }

    String optQuery = "in:inbox";
    if (cl.hasOption('q')) {
        optQuery = cl.getOptionValue('q');
    }

    Account account = getAccount(cl);
    if (account == null) {
        System.exit(1);
    }

    boolean optRaw = cl.hasOption('r');

    if (verbose) {
        LOG.info("Extracting from account " + account.getName());
    }

    Server server = Provisioning.getInstance().getServer(account);

    String optAdminURL;
    if (cl.hasOption('u')) {
        optAdminURL = cl.getOptionValue('u');
    } else {
        optAdminURL = getSoapURL(server, true);
    }
    String adminAuthToken = getAdminAuthToken(optAdminURL, optAdminUser, optAdminPassword);
    String authToken = getDelegateAuthToken(optAdminURL, account, adminAuthToken);
    BATCH_SIZE = Provisioning.getInstance().getLocalServer().getAntispamExtractionBatchSize();
    SLEEP_TIME = Provisioning.getInstance().getLocalServer().getAntispamExtractionBatchDelay();
    extract(authToken, account, server, optQuery, outputDirectory, optDelete, optRaw);
}

From source file:edu.ucdenver.ccp.nlp.ae.dict_util.OboToDictionary.java

public static void main(String args[]) {

        BasicConfigurator.configure();//from  w w w.  j  av a2  s .  co  m

        if (args.length < 2) {
            usage();
        } else {
            try {
                File oboFile = new File(args[0]);
                File outputFile = new File(args[1]);
                String namespaceName = "";
                if (args.length > 2) {
                    namespaceName = args[2];
                }
                if (!oboFile.canRead()) {
                    System.out.println("can't read input file;" + oboFile.getAbsolutePath());
                    usage();
                    System.exit(-2);
                }
                if (outputFile.exists() && !outputFile.canWrite()) {
                    System.out.println("can't write output file;" + outputFile.getAbsolutePath());
                    usage();
                    System.exit(-3);
                }

                logger.warn("running with: " + oboFile.getAbsolutePath());
                OboToDictionary converter = null;
                if (namespaceName != null && namespaceName.length() > 0) {
                    Set<String> namespaceSet = new TreeSet<String>();
                    namespaceSet.add(namespaceName);
                    converter = new OboToDictionary(true, SynonymType.EXACT_ONLY, namespaceSet);
                } else {
                    converter = new OboToDictionary();
                }
                converter.convert(oboFile, outputFile);
            } catch (Exception e) {
                System.out.println("error:" + e);
                e.printStackTrace();
                System.exit(-1);
            }
        }
    }

From source file:DIA_Umpire_SE.DIA_Umpire_SE.java

/**
 * @param args the command line arguments DIA_Umpire parameterfile
 *//*from  w  w w.  j av  a2s .  c o  m*/
public static void main(String[] args) throws InterruptedException, FileNotFoundException, ExecutionException,
        IOException, ParserConfigurationException, DataFormatException, SAXException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println(
            "DIA-Umpire singal extraction analysis  (version: " + UmpireInfo.GetInstance().Version + ")");
    if (args.length < 2 || args.length > 3) {
        System.out.println(
                "command format error, the correct format is: java -jar -Xmx8G DIA_Umpire_SE.jar mzMXL_file diaumpire_se.params");
        System.out.println(
                "To fix DIA setting, use : java -jar -Xmx8G DIA_Umpire_SE.jar mzMXL_file diaumpire_se.params -f");
        return;
    }
    try {
        //Define logger level for console
        ConsoleLogger.SetConsoleLogger(Level.INFO);
        //Define logger level and file path for text log file
        ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_se.log");
    } catch (Exception e) {
    }

    boolean Fix = false;
    boolean Resume = false;

    if (args.length == 3 && args[2].equals("-f")) {
        Fix = true;
    }
    String parameterfile = args[1];
    String MSFilePath = args[0];
    Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version);
    Logger.getRootLogger().info("Parameter file:" + parameterfile);
    Logger.getRootLogger().info("Spectra file:" + MSFilePath);
    BufferedReader reader = new BufferedReader(new FileReader(parameterfile));

    String line = "";
    InstrumentParameter param = new InstrumentParameter(InstrumentParameter.InstrumentType.TOF5600);
    param.DetermineBGByID = false;
    param.EstimateBG = true;
    int NoCPUs = 2;

    SpectralDataType.DataType dataType = SpectralDataType.DataType.DIA_F_Window;
    String WindowType = "";
    int WindowSize = 25;

    ArrayList<XYData> WindowList = new ArrayList<>();

    boolean ExportPrecursorPeak = false;
    boolean ExportFragmentPeak = false;

    //<editor-fold defaultstate="collapsed" desc="Read parameter file">
    while ((line = reader.readLine()) != null) {
        Logger.getRootLogger().info(line);
        if (!"".equals(line) && !line.startsWith("#")) {
            //System.out.println(line);
            if (line.equals("==window setting begin")) {
                while (!(line = reader.readLine()).equals("==window setting end")) {
                    if (!"".equals(line)) {
                        WindowList.add(new XYData(Float.parseFloat(line.split("\t")[0]),
                                Float.parseFloat(line.split("\t")[1])));
                    }
                }
                continue;
            }
            if (line.split("=").length < 2) {
                continue;
            }
            String type = line.split("=")[0].trim();
            if (type.startsWith("para.")) {
                type = type.replace("para.", "SE.");
            }
            String value = line.split("=")[1].trim();
            switch (type) {
            case "Thread": {
                NoCPUs = Integer.parseInt(value);
                break;
            }
            case "ExportPrecursorPeak": {
                ExportPrecursorPeak = Boolean.parseBoolean(value);
                break;
            }
            case "ExportFragmentPeak": {
                ExportFragmentPeak = Boolean.parseBoolean(value);
                break;
            }

            //<editor-fold defaultstate="collapsed" desc="instrument parameters">
            case "RPmax": {
                param.PrecursorRank = Integer.parseInt(value);
                break;
            }
            case "RFmax": {
                param.FragmentRank = Integer.parseInt(value);
                break;
            }
            case "CorrThreshold": {
                param.CorrThreshold = Float.parseFloat(value);
                break;
            }
            case "DeltaApex": {
                param.ApexDelta = Float.parseFloat(value);
                break;
            }
            case "RTOverlap": {
                param.RTOverlapThreshold = Float.parseFloat(value);
                break;
            }
            case "BoostComplementaryIon": {
                param.BoostComplementaryIon = Boolean.parseBoolean(value);
                break;
            }
            case "AdjustFragIntensity": {
                param.AdjustFragIntensity = Boolean.parseBoolean(value);
                break;
            }
            case "SE.MS1PPM": {
                param.MS1PPM = Float.parseFloat(value);
                break;
            }
            case "SE.MS2PPM": {
                param.MS2PPM = Float.parseFloat(value);
                break;
            }
            case "SE.SN": {
                param.SNThreshold = Float.parseFloat(value);
                break;
            }
            case "SE.MS2SN": {
                param.MS2SNThreshold = Float.parseFloat(value);
                break;
            }
            case "SE.MinMSIntensity": {
                param.MinMSIntensity = Float.parseFloat(value);
                break;
            }
            case "SE.MinMSMSIntensity": {
                param.MinMSMSIntensity = Float.parseFloat(value);
                break;
            }
            case "SE.MinRTRange": {
                param.MinRTRange = Float.parseFloat(value);
                break;
            }
            case "SE.MaxNoPeakCluster": {
                param.MaxNoPeakCluster = Integer.parseInt(value);
                param.MaxMS2NoPeakCluster = Integer.parseInt(value);
                break;
            }
            case "SE.MinNoPeakCluster": {
                param.MinNoPeakCluster = Integer.parseInt(value);
                param.MinMS2NoPeakCluster = Integer.parseInt(value);
                break;
            }
            case "SE.MinMS2NoPeakCluster": {
                param.MinMS2NoPeakCluster = Integer.parseInt(value);
                break;
            }
            case "SE.MaxCurveRTRange": {
                param.MaxCurveRTRange = Float.parseFloat(value);
                break;
            }
            case "SE.Resolution": {
                param.Resolution = Integer.parseInt(value);
                break;
            }
            case "SE.RTtol": {
                param.RTtol = Float.parseFloat(value);
                break;
            }
            case "SE.NoPeakPerMin": {
                param.NoPeakPerMin = Integer.parseInt(value);
                break;
            }
            case "SE.StartCharge": {
                param.StartCharge = Integer.parseInt(value);
                break;
            }
            case "SE.EndCharge": {
                param.EndCharge = Integer.parseInt(value);
                break;
            }
            case "SE.MS2StartCharge": {
                param.MS2StartCharge = Integer.parseInt(value);
                break;
            }
            case "SE.MS2EndCharge": {
                param.MS2EndCharge = Integer.parseInt(value);
                break;
            }
            case "SE.NoMissedScan": {
                param.NoMissedScan = Integer.parseInt(value);
                break;
            }
            case "SE.Denoise": {
                param.Denoise = Boolean.valueOf(value);
                break;
            }
            case "SE.EstimateBG": {
                param.EstimateBG = Boolean.valueOf(value);
                break;
            }
            case "SE.RemoveGroupedPeaks": {
                param.RemoveGroupedPeaks = Boolean.valueOf(value);
                break;
            }
            case "SE.MinFrag": {
                param.MinFrag = Integer.parseInt(value);
                break;
            }
            case "SE.IsoPattern": {
                param.IsoPattern = Float.valueOf(value);
                break;
            }
            case "SE.StartRT": {
                param.startRT = Float.valueOf(value);
                break;
            }
            case "SE.EndRT": {
                param.endRT = Float.valueOf(value);
                break;
            }
            case "SE.RemoveGroupedPeaksRTOverlap": {
                param.RemoveGroupedPeaksRTOverlap = Float.valueOf(value);
                break;
            }
            case "SE.RemoveGroupedPeaksCorr": {
                param.RemoveGroupedPeaksCorr = Float.valueOf(value);
                break;
            }
            case "SE.MinMZ": {
                param.MinMZ = Float.valueOf(value);
                break;
            }
            case "SE.MinPrecursorMass": {
                param.MinPrecursorMass = Float.valueOf(value);
                break;
            }
            case "SE.MaxPrecursorMass": {
                param.MaxPrecursorMass = Float.valueOf(value);
                break;
            }
            case "SE.IsoCorrThreshold": {
                param.IsoCorrThreshold = Float.valueOf(value);
                break;
            }
            case "SE.MassDefectFilter": {
                param.MassDefectFilter = Boolean.parseBoolean(value);
                break;
            }
            case "SE.MassDefectOffset": {
                param.MassDefectOffset = Float.valueOf(value);
                break;
            }

            //</editor-fold>//</editor-fold>

            case "WindowType": {
                WindowType = value;
                switch (WindowType) {
                case "SWATH": {
                    dataType = SpectralDataType.DataType.DIA_F_Window;
                    break;
                }
                case "V_SWATH": {
                    dataType = SpectralDataType.DataType.DIA_V_Window;
                    break;
                }
                case "MSX": {
                    dataType = SpectralDataType.DataType.MSX;
                    break;
                }
                case "MSE": {
                    dataType = SpectralDataType.DataType.MSe;
                    break;
                }
                }
                break;
            }
            case "WindowSize": {
                WindowSize = Integer.parseInt(value);
                break;
            }
            }
        }
    }
    //</editor-fold>

    try {
        File MSFile = new File(MSFilePath);
        if (MSFile.exists()) {
            long time = System.currentTimeMillis();
            Logger.getRootLogger().info(
                    "=================================================================================================");
            Logger.getRootLogger().info("Processing " + MSFilePath + "....");

            //Initialize a DIA file data structure                
            DIAPack DiaFile = new DIAPack(MSFile.getAbsolutePath(), NoCPUs);
            DiaFile.Resume = Resume;
            DiaFile.SetDataType(dataType);
            DiaFile.SetParameter(param);

            //Set DIA isolation window setting
            if (dataType == SpectralDataType.DataType.DIA_F_Window) {
                DiaFile.SetWindowSize(WindowSize);
            } else if (dataType == SpectralDataType.DataType.DIA_V_Window) {
                for (XYData window : WindowList) {
                    DiaFile.AddVariableWindow(window);
                }
            }
            DiaFile.SaveDIASetting();
            DiaFile.SaveParams();

            if (Fix) {
                DiaFile.FixScanidx();
                return;
            }
            DiaFile.ExportPrecursorPeak = ExportPrecursorPeak;
            DiaFile.ExportFragmentPeak = ExportFragmentPeak;
            Logger.getRootLogger().info("Module A: Signal extraction");
            //Start DIA signal extraction process to generate pseudo MS/MS files
            DiaFile.process();
            time = System.currentTimeMillis() - time;
            Logger.getRootLogger().info(MSFilePath + " 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))));
        } else {
            throw new RuntimeException("file: " + MSFile + "? does not exist!");
        }
        Logger.getRootLogger().info("Job complete");
        Logger.getRootLogger().info(
                "=================================================================================================");

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

From source file:eu.project.ttc.tools.cli.TermSuiteTerminoCLI.java

/**
 * Application entry point/*ww  w .j  a v a 2 s . c om*/
 * 
 * @param args
 *            Command line arguments
  * @throws UnsupportedEncodingException 
 */
public static void main(String[] args) throws Exception {
    String logPath = Paths
            .get("logs", "termsuite-" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) + ".log")
            .toAbsolutePath().toString();
    TermSuiteCLIUtils.logToFile(logPath);
    File logDir = new File("logs");
    if (!logDir.exists())
        logDir.mkdir();
    LOGGER.info("Logging to {}", logPath);
    TermSuiteTerminoCLI cli = new TermSuiteTerminoCLI();
    cli.run(args);
}

From source file:de.prozesskraft.pkraft.Merge.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    /*----------------------------
      get options from ini-file/*from  w  w w  .  j  a v a2 s  .co m*/
    ----------------------------*/
    java.io.File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Merge.class) + "/" + "../etc/pkraft-merge.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option oinstance = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] instance you want to merge another instance into.")
            //            .isRequired()
            .create("instance");

    Option oguest = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] this instance will be merged into -instance.")
            //            .isRequired()
            .create("guest");

    Option obasedir = OptionBuilder.withArgName("DIR").hasArg().withDescription(
            "[optional] in this base-directory the result instance (merge of -instance and -guest) will be placed. this directory has to exist. omit to use the base-directory of -instance.")
            //            .isRequired()
            .create("basedir");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(oinstance);
    options.addOption(oguest);
    options.addOption(obasedir);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    commandline = parser.parse(options, args);

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("merge", options);
        System.exit(0);
    }

    if (commandline.hasOption("v")) {
        System.out.println("author:  alexander.vogel@caegroup.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }
    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("instance"))) {
        System.err.println("option -instance is mandatory");
        exiter();
    }
    if (!(commandline.hasOption("guest"))) {
        System.err.println("at least one option -guest is mandatory");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/
    String pathToInstance = commandline.getOptionValue("instance");
    java.io.File fileInstance = new java.io.File(pathToInstance);

    String[] pathToGuest = commandline.getOptionValues("guest");

    String baseDir = null;
    if (commandline.hasOption("basedir")) {
        java.io.File fileBaseDir = new java.io.File(commandline.getOptionValue("basedir"));
        if (!fileBaseDir.exists()) {
            System.err.println("basedir does not exist: " + fileBaseDir.getAbsolutePath());
            exiter();
        } else if (!fileBaseDir.isDirectory()) {
            System.err.println("basedir is not a directory: " + fileBaseDir.getAbsolutePath());
            exiter();
        }
        baseDir = commandline.getOptionValue("basedir");
    }

    // ueberpruefen ob die process.pmb files vorhanden sind
    // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen
    if (!fileInstance.exists()) {
        System.err.println("instance file does not exist: " + fileInstance.getAbsolutePath());
        exiter();
    }
    for (String pathGuest : pathToGuest) {
        java.io.File fileGuest = new java.io.File(pathGuest);

        // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen
        if (!fileGuest.exists()) {
            System.err.println("guest file does not exist: " + fileGuest.getAbsolutePath());
            exiter();
        }
    }

    // base - instance einlesen
    Process p1 = new Process();
    p1.setInfilebinary(pathToInstance);
    p1.setOutfilebinary(pathToInstance);
    Process p2 = p1.readBinary();

    // alle guests einlesen
    ArrayList<Process> alleGuests = new ArrayList<Process>();
    for (String actPathGuest : pathToGuest) {
        Process p30 = new Process();
        p30.setInfilebinary(actPathGuest);
        Process pGuest = p30.readBinary();

        // testen ob base-instanz und aktuelle guestinstanz vom gleichen typ sind
        if (!p2.getName().equals(pGuest.getName())) {
            System.err.println("error: instances are not from the same type (-instance=" + p2.getName()
                    + " != -guest=" + pGuest.getName());
            exiter();
        }

        // testen ob base-instanz und aktuelle guestinstanz von gleicher version sind
        if (!p2.getVersion().equals(pGuest.getVersion())) {
            System.err.println("error: instances are not from the same version (" + p2.getVersion() + "!="
                    + pGuest.getVersion());
            exiter();
        }

        alleGuests.add(pGuest);
    }

    // den main-prozess trotzdem nochmal einlesen um subprozesse extrahieren zu koennen
    Process p3 = new Process();
    p3.setInfilebinary(pathToInstance);
    Process process = p3.readBinary();

    // den main-prozess ueber die static function klonen
    // das anmelden bei pradar erfolgt erst ganz zum schluss, denn beim clonen werden nachfolgende steps resettet, die zu diesem zeitpunkt noch intakt sind
    Process clonedProcess = cloneProcess(process, null);

    // alle steps durchgehen und falls subprocesses existieren auch fuer diese ein cloning durchfuehren
    for (Step actStep : process.getStep()) {
        if (actStep.getSubprocess() != null) {
            Process pDummy = new Process();
            pDummy.setInfilebinary(actStep.getAbsdir() + "/process.pmb");
            Process processInSubprocess = pDummy.readBinary();
            //            System.err.println("info: reading process freshly from file: " + actStep.getAbsdir() + "/process.pmb");
            if (processInSubprocess != null) {
                Process clonedSubprocess = cloneProcess(processInSubprocess, clonedProcess);
                // den prozess in pradar anmelden durch aufruf des tools: pradar-attend
                String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedSubprocess.getRootdir()
                        + "/process.pmb";
                System.err.println("info: calling: " + call2);

                try {
                    java.lang.Process sysproc = Runtime.getRuntime().exec(call2);
                } catch (IOException e) {
                    System.err.println("error: " + e.getMessage());
                }
            }
        }
    }

    // alle dependent steps der zielinstanz einsammeln
    // dies wird zum resetten benoetigt, damit steps nicht doppelt resettet werden
    Map<Step, String> dependentSteps = new HashMap<Step, String>();

    // alle guest prozesse merge durchfuehren
    for (Process actGuestProcess : alleGuests) {
        System.err.println("info: merging guest process " + actGuestProcess.getInfilebinary());

        // alle fanned steps (ehemalige multisteps) des zu mergenden prozesses in die fanned multisteps des bestehenden prozesses integrieren
        for (Step actStep : actGuestProcess.getStep()) {
            if (actStep.isAFannedMultistep()) {
                System.err.println("info: merging from guest instance step " + actStep.getName());
                Step clonedStepForIntegrationInClonedProcess = actStep.clone();
                if (clonedProcess.integrateStep(clonedStepForIntegrationInClonedProcess)) {
                    System.err.println("info: merging step successfully.");
                    // die downstream steps vom merge-punkt merken
                    for (Step actStepToResetBecauseOfDependency : clonedProcess
                            .getStepDependent(actStep.getName())) {
                        dependentSteps.put(actStepToResetBecauseOfDependency, "dummy");
                    }

                    // der step einen subprocess enthaelt muss der subprocess nach der integration bei pradar gemeldet werden
                    // den prozess in pradar anmelden durch aufruf des tools: pradar-attend
                    if (clonedStepForIntegrationInClonedProcess.getSubprocess() != null
                            && clonedStepForIntegrationInClonedProcess.getSubprocess().getProcess() != null) {
                        String call5 = ini.get("apps", "pradar-attend") + " -instance "
                                + clonedStepForIntegrationInClonedProcess.getAbsdir() + "/process.pmb";
                        System.err.println("info: calling: " + call5);
                        try {
                            java.lang.Process sysproc = Runtime.getRuntime().exec(call5);
                        } catch (IOException e) {
                            System.err.println("error: " + e.getMessage());
                        }
                    }
                } else {
                    System.err.println("error: merging step failed.");
                }
            } else {
                System.err.println("debug: because it's not a multistep, ignoring from guest instance step "
                        + actStep.getName());
            }
        }
    }

    // alle steps downstream der merge-positionen resetten
    for (Step actStep : dependentSteps.keySet()) {
        actStep.resetBecauseOfDependency();
    }

    // speichern der ergebnis instanz
    clonedProcess.writeBinary();

    // den prozess in pradar anmelden durch aufruf des tools: pradar-attend
    String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedProcess.getRootdir()
            + "/process.pmb";
    System.err.println("info: calling: " + call2);

    try {
        java.lang.Process sysproc = Runtime.getRuntime().exec(call2);
    } catch (IOException e) {
        System.err.println("error: " + e.getMessage());
    }

}

From source file:net.antidot.semantic.rdf.rdb2rdf.main.Db2triples.java

public static void main(String[] args) {
    // Get all options
    Options options = new Options();
    Options r2rmlOptions = new Options();
    Options dmOptions = new Options();
    options.addOption(modeOpt);//from  w w w . jav  a2  s  .c  om
    options.addOption(userNameOpt);
    r2rmlOptions.addOption(userNameOpt);
    dmOptions.addOption(userNameOpt);
    options.addOption(passwordOpt);
    r2rmlOptions.addOption(passwordOpt);
    dmOptions.addOption(passwordOpt);
    options.addOption(URLOpt);
    r2rmlOptions.addOption(URLOpt);
    dmOptions.addOption(URLOpt);
    options.addOption(driverOpt);
    r2rmlOptions.addOption(driverOpt);
    dmOptions.addOption(driverOpt);
    options.addOption(dbOpt);
    r2rmlOptions.addOption(dbOpt);
    dmOptions.addOption(dbOpt);
    options.addOption(baseURIOpt);
    r2rmlOptions.addOption(baseURIOpt);
    dmOptions.addOption(baseURIOpt);
    options.addOption(forceOpt);
    r2rmlOptions.addOption(forceOpt);
    dmOptions.addOption(forceOpt);
    options.addOption(nativeOpt);
    r2rmlOptions.addOption(nativeOpt);
    dmOptions.addOption(nativeOpt);
    options.addOption(nativeStoreNameOpt);
    r2rmlOptions.addOption(nativeStoreNameOpt);
    dmOptions.addOption(nativeStoreNameOpt);
    options.addOption(outputOpt);
    r2rmlOptions.addOption(outputOpt);
    dmOptions.addOption(outputOpt);
    options.addOption(transformSPARQLFile);
    dmOptions.addOption(transformSPARQLFile);
    options.addOption(transformOutputFile);
    dmOptions.addOption(transformOutputFile);
    options.addOption(rdfFormat);
    r2rmlOptions.addOption(rdfFormat);
    dmOptions.addOption(rdfFormat);
    options.addOption(versionOpt);
    dmOptions.addOption(versionOpt);
    options.addOption(r2rmlFileOpt);
    r2rmlOptions.addOption(r2rmlFileOpt);

    // Init parameters
    String mode = null;
    String userName = null;
    String password = null;
    String url = null;
    DriverType driver = null;
    String dbName = null;
    String baseURI = null;
    boolean useNativeStore = false;
    boolean forceExistingRep = false;
    String nativeOutput = null;
    String output = null;
    String sparql = null;
    String sparqlOutput = null;
    String format = null;
    String r2rmlFile = null;
    int int_version = 1;

    // RDF Format output
    RDFFormat rdfFormat = RDFFormat.TURTLE; // Turtle by default
    // Norm version
    Version version = Version.WD_20120529;

    // Option parsing
    // Create the parser
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        // Database settings
        // Mode
        if (!line.hasOption("mode")) {
            // automatically generate the help statement
            log.error("Mode is required. Use -m option to set it.");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(projectName, options);
            System.exit(-1);
        } else {
            mode = line.getOptionValue("mode");
            if (!mode.equals("r2rml") && !mode.equals("dm")) {
                log.error("Unkonw mode. Please select 'r2rml' or 'dm' mode.");
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp(projectName, options);
                System.exit(-1);
            }
        }
        // user name
        if (!line.hasOption("user")) {
            // automatically generate the help statement
            log.error("User name is required. Use -u option to set it.");
            HelpFormatter formatter = new HelpFormatter();
            if (mode.equals("r2rml")) {
                formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
            } else {
                formatter.printHelp(projectNameDirectMappingMode, dmOptions);
            }
            System.exit(-1);
        } else {
            userName = line.getOptionValue("user");
        }
        // password
        if (!line.hasOption("pass")) {
            // automatically generate the help statement
            log.error("Password is required. Use -p option to set it.");
            HelpFormatter formatter = new HelpFormatter();
            if (mode.equals("r2rml")) {
                formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
            } else {
                formatter.printHelp(projectNameDirectMappingMode, dmOptions);
            }
            System.exit(-1);
        } else {
            password = line.getOptionValue("pass");
        }
        // Database URL
        url = line.getOptionValue("url", "jdbc:mysql://localhost/");
        // driver
        driver = new DriverType(line.getOptionValue("driver", defaultDriver.getDriverName()));
        // Database name
        if (!line.hasOption("database")) {
            // automatically generate the help statement
            log.error("Database name is required. Use -b option to set it.");
            HelpFormatter formatter = new HelpFormatter();
            if (mode.equals("r2rml")) {
                formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
            } else {
                formatter.printHelp(projectNameDirectMappingMode, dmOptions);
            }
            System.exit(-1);
        } else {
            dbName = line.getOptionValue("database");
        }
        // Base URI
        baseURI = line.getOptionValue("base_uri", "http://foo.example/DB/");
        // Use of native store ?
        useNativeStore = line.hasOption("n");
        // Name of native store
        if (useNativeStore && !line.hasOption("native_output")) {
            // automatically generate the help statement
            log.error("Native triplestore path is required. Use -n option to set it.");
            HelpFormatter formatter = new HelpFormatter();
            if (mode.equals("r2rml")) {
                formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
            } else {
                formatter.printHelp(projectNameDirectMappingMode, dmOptions);
            }
            System.exit(-1);
        } else {
            nativeOutput = line.getOptionValue("native_output");
        }
        // Force loading of repository
        forceExistingRep = line.hasOption("f");
        // Output
        output = line.getOptionValue("output", "output.ttl");
        // SPARQL transformation
        if (line.hasOption("sparql")) {
            if (!mode.equals("dm")) {
                log.warn("sparql option is required only for 'dm' mode : it will be ignored...");
            } else {
                sparql = line.getOptionValue("sparql");
                sparqlOutput = line.getOptionValue("sparql_output", "output_sparql.ttl");
            }
        }
        // RDF Format
        if (line.hasOption("format")) {
            format = line.getOptionValue("format");
            if (format.equals("TURTLE"))
                rdfFormat = RDFFormat.TURTLE;
            else if (format.equals("RDFXML"))
                rdfFormat = RDFFormat.RDFXML;
            else if (format.equals("NTRIPLES"))
                rdfFormat = RDFFormat.NTRIPLES;
            else if (!format.equals("N3")) {
                log.error("Unknown RDF format. Please use RDFXML, TURTLE, N3 or NTRIPLES.");
                HelpFormatter formatter = new HelpFormatter();
                if (mode.equals("r2rml")) {
                    formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
                } else {
                    formatter.printHelp(projectNameDirectMappingMode, dmOptions);
                }
                System.exit(-1);
            }
        }
        // Norm version
        if (line.hasOption("version")) {
            if (!mode.equals("dm")) {
                log.warn("version option is required only for 'dm' mode : it will be ignored...");
            }
            switch (int_version) {
            case 1:
                version = Version.WD_20120529;
                break;
            case 2:
                version = Version.WD_20110324;
                // Check DB compatibilities
                if (!(driver.equals(DriverType.MysqlDriver) || driver.equals(DriverType.PostgreSQL))) {
                    log.error(
                            "Db2triples in Direct Mapping mode does'nt support this driver for the Working Draft"
                                    + " of 23 March 2011 (only MySQL and PostGreSQL for this time). "
                                    + "You can set the version option to select Working Draft of 20 September 2011.");
                    System.exit(-1);
                }
                break;
            default:
                break;
            }
        }
        // r2rml instance
        if (mode.equals("r2rml")) {
            if (!line.hasOption("r2rml_file")) {
                log.error("R2RML config file is required. Use -r option to set it.");
                // automatically generate the help statement
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
                System.exit(-1);
            } else {
                r2rmlFile = line.getOptionValue("r2rml_file");
                File r2rmlFileTest = new File(r2rmlFile);
                if (!r2rmlFileTest.exists()) {
                    log.error("R2RML file does not exists.");
                    System.exit(-1);
                }
            }
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        log.error("Parsing failed. Reason : " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(projectName, options);
        System.exit(-1);
    }

    // Open test database
    Connection conn = null;
    try {
        // Connect database
        conn = SQLConnector.connect(userName, password, url + dbName, driver);

        // Generate RDF graph
        SesameDataSet g = null;
        // Check nature of storage (memory by default)
        if (useNativeStore) {
            File pathToNativeOutputDir = new File(nativeOutput);
            if (pathToNativeOutputDir.exists() && !forceExistingRep) {
                log.error("Directory " + pathToNativeOutputDir
                        + "  already exists. Use -f option to force loading of existing repository.");
                System.exit(-1);
            }
            // Extract database model according to convert mode
            if (mode.equals("r2rml")) {
                g = R2RMLProcessor.convertDatabase(conn, r2rmlFile, baseURI, nativeOutput, driver);
            } else {
                g = DirectMapper.generateDirectMapping(conn, version, driver, baseURI, null, nativeOutput);
            }
        } else {
            File outputFile = new File(output);
            if (outputFile.exists() && !forceExistingRep) {
                log.error("Output file " + outputFile.getAbsolutePath()
                        + " already exists. Please remove it or modify ouput name option.");
                System.exit(-1);
            }
            // Extract database model
            if (mode.equals("r2rml")) {
                g = R2RMLProcessor.convertDatabase(conn, r2rmlFile, baseURI, driver);
            } else {
                g = DirectMapper.generateDirectMapping(conn, version, driver, baseURI, null, null);
            }
            // Dump graph
            log.info("Serialize RDF graph...");
            g.dumpRDF(output, rdfFormat);
            log.info("RDF graph serialized into " + outputFile.getAbsolutePath());
        }
        if (sparql != null && mode.equals("dm")) {
            log.info("Execute SPARQL transformation...");
            Long start = System.currentTimeMillis();
            String result = g.runSPARQLFromFile(sparql, rdfFormat);
            SesameDataSet gResult = new SesameDataSet();
            gResult.addString(result, rdfFormat);
            gResult.dumpRDF(sparqlOutput, rdfFormat);

            Float stop = Float.valueOf(System.currentTimeMillis() - start) / 1000;
            log.info("Direct Mapping SPARQL query executed in " + stop + " seconds.");
            log.info("[DirectMapping:main] Number of triples after transformation : " + gResult.getSize());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            // Close db connection
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.cc.apptroy.baksmali.main.java

/**
 * Run!//  w  w  w. jav  a2  s  . c  om
 */
public static void main(String[] args) throws IOException {
    Locale locale = new Locale("en", "US");
    Locale.setDefault(locale);

    CommandLineParser parser = new PosixParser();
    CommandLine commandLine;

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        usage();
        return;
    }

    baksmaliOptions options = new baksmaliOptions();

    boolean disassemble = true;
    boolean doDump = false;
    String dumpFileName = null;
    boolean setBootClassPath = false;

    String[] remainingArgs = commandLine.getArgs();
    Option[] clOptions = commandLine.getOptions();

    for (int i = 0; i < clOptions.length; i++) {
        Option option = clOptions[i];
        String opt = option.getOpt();

        switch (opt.charAt(0)) {
        case 'v':
            version();
            return;
        case '?':
            while (++i < clOptions.length) {
                if (clOptions[i].getOpt().charAt(0) == '?') {
                    usage(true);
                    return;
                }
            }
            usage(false);
            return;
        case 'o':
            options.outputDirectory = commandLine.getOptionValue("o");
            break;
        case 'p':
            options.noParameterRegisters = true;
            break;
        case 'l':
            options.useLocalsDirective = true;
            break;
        case 's':
            options.useSequentialLabels = true;
            break;
        case 'b':
            options.outputDebugInfo = false;
            break;
        case 'd':
            options.bootClassPathDirs.add(option.getValue());
            break;
        case 'f':
            options.addCodeOffsets = true;
            break;
        case 'r':
            String[] values = commandLine.getOptionValues('r');
            int registerInfo = 0;

            if (values == null || values.length == 0) {
                registerInfo = baksmaliOptions.ARGS | baksmaliOptions.DEST;
            } else {
                for (String value : values) {
                    if (value.equalsIgnoreCase("ALL")) {
                        registerInfo |= baksmaliOptions.ALL;
                    } else if (value.equalsIgnoreCase("ALLPRE")) {
                        registerInfo |= baksmaliOptions.ALLPRE;
                    } else if (value.equalsIgnoreCase("ALLPOST")) {
                        registerInfo |= baksmaliOptions.ALLPOST;
                    } else if (value.equalsIgnoreCase("ARGS")) {
                        registerInfo |= baksmaliOptions.ARGS;
                    } else if (value.equalsIgnoreCase("DEST")) {
                        registerInfo |= baksmaliOptions.DEST;
                    } else if (value.equalsIgnoreCase("MERGE")) {
                        registerInfo |= baksmaliOptions.MERGE;
                    } else if (value.equalsIgnoreCase("FULLMERGE")) {
                        registerInfo |= baksmaliOptions.FULLMERGE;
                    } else {
                        usage();
                        return;
                    }
                }

                if ((registerInfo & baksmaliOptions.FULLMERGE) != 0) {
                    registerInfo &= ~baksmaliOptions.MERGE;
                }
            }
            options.registerInfo = registerInfo;
            break;
        case 'c':
            String bcp = commandLine.getOptionValue("c");
            if (bcp != null && bcp.charAt(0) == ':') {
                options.addExtraClassPath(bcp);
            } else {
                setBootClassPath = true;
                options.setBootClassPath(bcp);
            }
            break;
        case 'x':
            options.deodex = true;
            break;
        case 'X':
            options.experimental = true;
            break;
        case 'm':
            options.noAccessorComments = true;
            break;
        case 'a':
            options.apiLevel = Integer.parseInt(commandLine.getOptionValue("a"));
            break;
        case 'j':
            options.jobs = Integer.parseInt(commandLine.getOptionValue("j"));
            break;
        case 'i':
            String rif = commandLine.getOptionValue("i");
            options.setResourceIdFiles(rif);
            break;
        case 't':
            options.useImplicitReferences = true;
            break;
        case 'e':
            options.dexEntry = commandLine.getOptionValue("e");
            break;
        case 'k':
            options.checkPackagePrivateAccess = true;
            break;
        case 'N':
            disassemble = false;
            break;
        case 'D':
            doDump = true;
            dumpFileName = commandLine.getOptionValue("D");
            break;
        case 'I':
            options.ignoreErrors = true;
            break;
        case 'T':
            options.customInlineDefinitions = new File(commandLine.getOptionValue("T"));
            break;
        default:
            assert false;
        }
    }

    if (remainingArgs.length != 1) {
        usage();
        return;
    }

    if (options.jobs <= 0) {
        options.jobs = Runtime.getRuntime().availableProcessors();
        if (options.jobs > 6) {
            options.jobs = 6;
        }
    }

    String inputDexFileName = remainingArgs[0];

    File dexFileFile = new File(inputDexFileName);
    if (!dexFileFile.exists()) {
        System.err.println("Can't find the file " + inputDexFileName);
        System.exit(1);
    }

    //Read in and parse the dex file
    DexBackedDexFile dexFile = DexFileFactory.loadDexFile(dexFileFile, options.dexEntry, options.apiLevel,
            options.experimental);

    if (dexFile.isOdexFile()) {
        if (!options.deodex) {
            System.err.println("Warning: You are disassembling an odex file without deodexing it. You");
            System.err.println("won't be able to re-assemble the results unless you deodex it with the -x");
            System.err.println("option");
            options.allowOdex = true;
        }
    } else {
        options.deodex = false;
    }

    if (!setBootClassPath && (options.deodex || options.registerInfo != 0)) {
        if (dexFile instanceof DexBackedOdexFile) {
            options.bootClassPathEntries = ((DexBackedOdexFile) dexFile).getDependencies();
        } else {
            options.bootClassPathEntries = getDefaultBootClassPathForApi(options.apiLevel,
                    options.experimental);
        }
    }

    if (options.customInlineDefinitions == null && dexFile instanceof DexBackedOdexFile) {
        options.inlineResolver = InlineMethodResolver
                .createInlineMethodResolver(((DexBackedOdexFile) dexFile).getOdexVersion());
    }

    boolean errorOccurred = false;
    if (disassemble) {
        errorOccurred = !baksmali.disassembleDexFile(dexFile, options);
    }

    if (doDump) {
        if (dumpFileName == null) {
            dumpFileName = commandLine.getOptionValue(inputDexFileName + ".dump");
        }
        dump.dump(dexFile, dumpFileName, options.apiLevel, options.experimental);
    }

    if (errorOccurred) {
        System.exit(1);
    }
}

From source file:com.blackducksoftware.tools.nrt.NoticeReportTool.java

/**
 * @param args/*from w ww .j a v a2 s.  co  m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    System.out.println("Notice Report Tool for Black Duck Suite");
    CommandLineParser parser = new DefaultParser();

    options.addOption("h", "help", false, "show help.");

    Option applicationOption = new Option(NRTConstants.CL_APPLICATION_TYPE, true,
            "Application type [PROTEX|CODECENTER] (required)");
    applicationOption.setRequired(true);
    options.addOption(applicationOption);

    Option configFileOption = new Option(NRTConstants.CL_CONFIG_FILE, true,
            "Location of configuration file (required)");
    configFileOption.setRequired(true);
    options.addOption(configFileOption);

    Option projectNameOption = new Option(NRTConstants.CL_PROJECT_NAME, true,
            "Name of Protex project (will override configuration file)");
    projectNameOption.setRequired(false);
    options.addOption(projectNameOption);

    File configFile = null;
    APPLICATION applicationType = null;
    String projectName = null;

    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            help();
        }

        // Config File
        if (cmd.hasOption(NRTConstants.CL_CONFIG_FILE)) {
            String configFilePath = cmd.getOptionValue(NRTConstants.CL_CONFIG_FILE);
            log.info("Config file location: " + configFilePath);
            configFile = new File(configFilePath);
            if (!configFile.exists()) {
                log.error("Configuration file does not exist at location: " + configFile);
                System.exit(-1);
            }
        } else {
            log.error("Must specify configuration file!");
            help();
        }

        if (cmd.hasOption(NRTConstants.CL_APPLICATION_TYPE)) {
            String bdsApplicationType = cmd.getOptionValue(NRTConstants.CL_APPLICATION_TYPE);

            try {
                applicationType = APPLICATION.valueOf(bdsApplicationType);
            } catch (IllegalArgumentException e) {
                log.error("No such application type recognized: " + bdsApplicationType);
                help();
            }

        } else {
            help();
        }

        if (cmd.hasOption(NRTConstants.CL_PROJECT_NAME)) {
            projectName = cmd.getOptionValue(NRTConstants.CL_PROJECT_NAME);
            log.info("User specified project name: " + projectName);
        }

        NoticeReportProcessor processor = new NoticeReportProcessor(configFile.getAbsolutePath(),
                applicationType, projectName);
        try {
            processor.connect();
        } catch (Exception e) {
            log.error("Connection problems: " + e.getMessage());
            throw new Exception(e);
        }
        processor.processReport();

    } catch (Exception e) {
        log.error("Error: " + e.getMessage());
        help();
    }
}