Example usage for java.lang Boolean parseBoolean

List of usage examples for java.lang Boolean parseBoolean

Introduction

In this page you can find the example usage for java.lang Boolean parseBoolean.

Prototype

public static boolean parseBoolean(String s) 

Source Link

Document

Parses the string argument as a boolean.

Usage

From source file:com.hpe.nv.samples.basic.BasicNVTest.java

public static void main(String[] args) {
    try {/* ww w. j ava 2s  .co  m*/
        // program arguments
        Options options = new Options();
        options.addOption("i", "server-ip", true, "[mandatory] NV Test Manager IP");
        options.addOption("o", "server-port", true, "[mandatory] NV Test Manager port");
        options.addOption("u", "username", true, "[mandatory] NV username");
        options.addOption("w", "password", true, "[mandatory] NV password");
        options.addOption("e", "ssl", true, "[optional] Pass true to use SSL. Default: false");
        options.addOption("y", "proxy", true, "[optional] Proxy server host:port");
        options.addOption("b", "browser", true,
                "[optional] The browser for which the Selenium WebDriver is built. Possible values: Chrome and Firefox. Default: Firefox");
        options.addOption("d", "debug", true,
                "[optional] Pass true to view console debug messages during execution. Default: false");
        options.addOption("h", "help", false, "[optional] Generates and prints help information");

        // parse and validate the command line arguments
        CommandLineParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            // print help if help argument is passed
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("BasicNVTest.java", options);
            return;
        }

        if (line.hasOption("server-ip")) {
            serverIp = line.getOptionValue("server-ip");
            if (serverIp.equals("0.0.0.0")) {
                throw new Exception(
                        "Please replace the server IP argument value (0.0.0.0) with your NV Test Manager IP");
            }
        } else {
            throw new Exception("Missing argument -i/--server-ip <serverIp>");
        }

        if (line.hasOption("server-port")) {
            serverPort = Integer.parseInt(line.getOptionValue("server-port"));
        } else {
            throw new Exception("Missing argument -o/--server-port <serverPort>");
        }

        if (line.hasOption("username")) {
            username = line.getOptionValue("username");
        } else {
            throw new Exception("Missing argument -u/--username <username>");
        }

        if (line.hasOption("password")) {
            password = line.getOptionValue("password");
        } else {
            throw new Exception("Missing argument -w/--password <password>");
        }

        if (line.hasOption("ssl")) {
            ssl = Boolean.parseBoolean(line.getOptionValue("ssl"));
        }

        if (line.hasOption("proxy")) {
            proxySetting = line.getOptionValue("proxy");
        }

        if (line.hasOption("browser")) {
            browser = line.getOptionValue("browser");
        } else {
            browser = "Firefox";
        }

        if (line.hasOption("debug")) {
            debug = Boolean.parseBoolean(line.getOptionValue("debug"));
        }

        String newLine = System.getProperty("line.separator");
        String testDescription = "***   This sample demonstrates the use of the most basic NV methods.                               ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   First, the sample creates a TestManager object and initializes it.                           ***"
                + newLine
                + "***   The sample starts an NV test over an emulated \"3G Busy\" network.                             ***"
                + newLine
                + "***   (\"3G Busy\" is one of NV's built-in network profiles. A network profile specifies the         ***"
                + newLine
                + "***   network traffic behavior, including latency, packet loss, and incoming/outgoing bandwidth.   ***"
                + newLine
                + "***   Network profiles are used to emulate traffic over real-world networks.)                      ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   Next, the sample navigates to the home page in the HPE Network Virtualization website        ***"
                + newLine
                + "***   using the Selenium WebDriver.                                                                ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   Finally, the sample stops the NV test.                                                       ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   You can view the actual steps of this sample in the BasicNVTest.java file.                   ***"
                + newLine;

        // print the sample's description
        System.out.println(testDescription);

        // start console spinner
        if (!debug) {
            spinner = new Thread(new Spinner());
            spinner.start();
        }

        // sample execution steps
        /*****    Part 1 - Create a TestManager object and initialize it                                   *****/
        printPartDescription("\b------    Part 1 - Create a TestManager object and initialize it");
        initTestManager();
        printPartSeparator();
        /*****    Part 2 - Start the NV test with the "3G Busy" network scenario                           *****/
        printPartDescription("------    Part 2 - Start the NV test with the \"3G Busy\" network scenario");
        startTest();
        testRunning = true;
        printPartSeparator();
        /*****    Part 3 - Navigate to the HPE Network Virtualization website                              *****/
        printPartDescription("------    Part 3 - Navigate to the HPE Network Virtualization website");
        buildSeleniumWebDriver();
        seleniumNavigateToPage();
        driverCloseAndQuit();
        printPartSeparator();
        /*****    Part 4 - Stop the NV test                                                                *****/
        printPartDescription("------    Part 4 - Stop the NV test");
        stopTest();
        testRunning = false;
        printPartSeparator();
        doneCallback();
    } catch (Exception e) {
        try {
            handleError(e.getMessage());
        } catch (Exception e2) {
            System.out.println("Error occurred: " + e2.getMessage());
        }
    }
}

From source file:DIA_Umpire_SE.DIA_Umpire_SE.java

/**
 * @param args the command line arguments DIA_Umpire parameterfile
 *///from w w w.  j  a va 2  s  .  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:name.wagners.bpp.Bpp.java

public static void main(final String[] args) {

    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();

    options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("generations")
            .withDescription("Number of generations [default: 50]").create("g"));

    options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("mutrate")
            .withDescription("Mutation rate [default: 1]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("double").withLongOpt("mutprop")
            .withDescription("Mutation propability [default: 0.5]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("populationsize")
            .withDescription("Size of population [default: 20]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("a|b").withLongOpt("recombalg")
            .withDescription("Recombination algorithm [default: a]").create());

    // options.addOption(OptionBuilder
    // .hasArg()//from   w w w.java  2s . c o m
    // .withArgName("int")
    // .withLongOpt("recombrate")
    // .withDescription("Recombination rate [default: 1]")
    // .create());

    options.addOption(OptionBuilder.hasArg().withArgName("double").withLongOpt("recombprop")
            .withDescription("Recombination propability [default: 0.8]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("a").withLongOpt("selalg")
            .withDescription("Selection algorithm [default: a]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("selectionpressure")
            .withDescription("Selection pressure [default: 4]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("bool").withLongOpt("elitism")
            .withDescription("Enable Elitism [default: 1]").create("e"));

    options.addOption(OptionBuilder.hasArg().withArgName("filename")
            // .isRequired()
            .withLongOpt("datafile").withDescription("Problem data file [default: \"binpack.txt\"]")
            .create("f"));

    options.addOptionGroup(new OptionGroup()
            .addOption(OptionBuilder.withLongOpt("verbose").withDescription("be extra verbose").create("v"))
            .addOption(OptionBuilder.withLongOpt("quiet").withDescription("be extra quiet").create("q")));

    options.addOption(OptionBuilder.withLongOpt("version")
            .withDescription("print the version information and exit").create("V"));

    options.addOption(OptionBuilder.withLongOpt("help").withDescription("print this message").create("h"));

    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        // validate that block-size has been set
        if (line.hasOption("help")) {
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Bpp", options);

            System.exit(0);
        }

        if (line.hasOption("version")) {
            log.info("Bpp 0.1 (c) 2007 by Daniel Wagner");
        }

        if (line.hasOption("datafile")) {
            fname = line.getOptionValue("datafile");
        }

        if (line.hasOption("elitism")) {
            elitism = Boolean.parseBoolean(line.getOptionValue("elitism"));
        }

        if (line.hasOption("generations")) {
            gen = Integer.parseInt(line.getOptionValue("generations"));
        }

        if (line.hasOption("mutprop")) {
            mp = Double.parseDouble(line.getOptionValue("mutprop"));
        }

        if (line.hasOption("mutrate")) {
            mr = Integer.parseInt(line.getOptionValue("mutrate"));
        }

        if (line.hasOption("populationsize")) {
            ps = Integer.parseInt(line.getOptionValue("populationsize"));
        }

        if (line.hasOption("recombalg")) {
            sel = line.getOptionValue("recombalg").charAt(0);
        }

        if (line.hasOption("recombprop")) {
            rp = Double.parseDouble(line.getOptionValue("recombprop"));
        }

        if (line.hasOption("selalg")) {
            selalg = line.getOptionValue("selalg").charAt(0);
        }

        if (line.hasOption("selectionpressure")) {
            sp = Integer.parseInt(line.getOptionValue("selectionpressure"));
        }

    } catch (ParseException exp) {
        log.info("Unexpected exception:" + exp.getMessage(), exp);

        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Bpp", options);

        System.exit(1);
    }

    // Ausgabe der eingestellten Optionen

    log.info("Configuration");
    log.info("  Datafile:                  " + fname);
    log.info("  Generations:               " + gen);
    log.info("  Population size:           " + ps);
    log.info("  Elitism:                   " + elitism);
    log.info("  Mutation propapility:      " + mp);
    log.info("  Mutation rate:             " + mr);
    log.info("  Recombination algorithm    " + (char) sel);
    log.info("  Recombination propapility: " + rp);
    log.info("  Selection pressure:        " + sp);

    // Daten laden
    instance = new Instance();
    instance.load(fname);

    Evolutionizer e = new Evolutionizer(instance);

    e.run();
}

From source file:com.hpe.nv.samples.basic.BasicAnalyzeNVTest.java

public static void main(String[] args) {
    try {/* w w  w . j  a  v a  2s. c  o m*/
        // program arguments
        Options options = new Options();
        options.addOption("i", "server-ip", true, "[mandatory] NV Test Manager IP");
        options.addOption("o", "server-port", true, "[mandatory] NV Test Manager port");
        options.addOption("u", "username", true, "[mandatory] NV username");
        options.addOption("w", "password", true, "[mandatory] NV password");
        options.addOption("e", "ssl", true, "[optional] Pass true to use SSL. Default: false");
        options.addOption("y", "proxy", true, "[optional] Proxy server host:port");
        options.addOption("z", "zip-result-file-path", true,
                "[optional] File path to store the analysis results as a .zip file");
        options.addOption("k", "analysis-ports", true,
                "[optional] A comma-separated list of ports for test analysis");
        options.addOption("b", "browser", true,
                "[optional] The browser for which the Selenium WebDriver is built. Possible values: Chrome and Firefox. Default: Firefox");
        options.addOption("d", "debug", true,
                "[optional] Pass true to view console debug messages during execution. Default: false");
        options.addOption("h", "help", false, "[optional] Generates and prints help information");

        // parse and validate the command line arguments
        CommandLineParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            // print help if help argument is passed
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("BasicAnalyzeNVTest.java", options);
            return;
        }

        if (line.hasOption("server-ip")) {
            serverIp = line.getOptionValue("server-ip");
            if (serverIp.equals("0.0.0.0")) {
                throw new Exception(
                        "Please replace the server IP argument value (0.0.0.0) with your NV Test Manager IP");
            }
        } else {
            throw new Exception("Missing argument -i/--server-ip <serverIp>");
        }

        if (line.hasOption("server-port")) {
            serverPort = Integer.parseInt(line.getOptionValue("server-port"));
        } else {
            throw new Exception("Missing argument -o/--server-port <serverPort>");
        }

        if (line.hasOption("username")) {
            username = line.getOptionValue("username");
        } else {
            throw new Exception("Missing argument -u/--username <username>");
        }

        if (line.hasOption("password")) {
            password = line.getOptionValue("password");
        } else {
            throw new Exception("Missing argument -w/--password <password>");
        }

        if (line.hasOption("ssl")) {
            ssl = Boolean.parseBoolean(line.getOptionValue("ssl"));
        }

        if (line.hasOption("zip-result-file-path")) {
            zipResultFilePath = line.getOptionValue("zip-result-file-path");
        }

        if (line.hasOption("proxy")) {
            proxySetting = line.getOptionValue("proxy");
        }

        if (line.hasOption("analysis-ports")) {
            String analysisPortsStr = line.getOptionValue("analysis-ports");
            analysisPorts = analysisPortsStr.split(",");
        } else {
            analysisPorts = new String[] { "80", "8080" };
        }

        if (line.hasOption("browser")) {
            browser = line.getOptionValue("browser");
        } else {
            browser = "Firefox";
        }

        if (line.hasOption("debug")) {
            debug = Boolean.parseBoolean(line.getOptionValue("debug"));
        }

        String newLine = System.getProperty("line.separator");
        String testDescription = "***   This sample demonstrates the use of the most basic NV methods.                                                      ***"
                + newLine
                + "***                                                                                                                       ***"
                + newLine
                + "***   First, the sample creates a TestManager object and initializes it.                                                  ***"
                + newLine
                + "***   The sample starts an NV test over an emulated \"3G Busy\" network.                                                    ***"
                + newLine
                + "***                                                                                                                       ***"
                + newLine
                + "***   Next, the sample navigates to the home page in the HPE Network Virtualization website                               ***"
                + newLine
                + "***   using the Selenium WebDriver.                                                                                       ***"
                + newLine
                + "***                                                                                                                       ***"
                + newLine
                + "***   Finally, the sample stops the NV test, analyzes it, and prints the path of the analysis .zip file to the console.   ***"
                + newLine
                + "***                                                                                                                       ***"
                + newLine
                + "***   You can view the actual steps of this sample in the BasicAnalyzeNVTest.java file.                                   ***"
                + newLine;

        // print the sample's description
        System.out.println(testDescription);

        // start console spinner
        if (!debug) {
            spinner = new Thread(new Spinner());
            spinner.start();
        }

        // sample execution steps
        /*****    Part 1 - Create a TestManager object and initialize it                                            *****/
        printPartDescription("\b------    Part 1 - Create a TestManager object and initialize it");
        initTestManager();
        printPartSeparator();
        /*****    Part 2 - Start the NV test with the "3G Busy" network scenario                                    *****/
        printPartDescription("------    Part 2 - Start the NV test with the \"3G Busy\" network scenario");
        startTest();
        testRunning = true;
        printPartSeparator();
        /*****    Part 3 - Navigate to the HPE Network Virtualization website                                       *****/
        printPartDescription("------    Part 3 - Navigate to the HPE Network Virtualization website");
        buildSeleniumWebDriver();
        seleniumNavigateToPage();
        driverCloseAndQuit();
        printPartSeparator();
        /*****    Part 4 - Stop the NV test, analyze it and print the results to the console                        *****/
        printPartDescription(
                "------    Part 4 - Stop the NV test, analyze it and print the results to the console");
        stopTestAndAnalyze();
        testRunning = false;
        printPartSeparator();
        doneCallback();
    } catch (Exception e) {
        try {
            handleError(e.getMessage());
        } catch (Exception e2) {
            System.out.println("Error occurred: " + e2.getMessage());
        }
    }
}

From source file:com.hzih.sslvpn.servlet.TelnetClientExample.java

/**
 * Main for the TelnetClientExample.//from w ww .j  a  v  a  2 s . com
 * *
 */
public static void main(String[] args) throws Exception {
    FileOutputStream fout = null;

    if (args.length < 1) {
        System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]");
        System.exit(1);
    }

    String remoteip = args[0];

    int remoteport;

    if (args.length > 1) {
        remoteport = (new Integer(args[1])).intValue();
    } else {
        remoteport = 23;
    }

    try {
        fout = new FileOutputStream("spy.log", true);
    } catch (IOException e) {
        System.err.println("Exception while opening the spy file: " + e.getMessage());
    }

    tc = new TelnetClient();

    TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
    EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
    SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);

    try {
        tc.addOptionHandler(ttopt);
        tc.addOptionHandler(echoopt);
        tc.addOptionHandler(gaopt);
    } catch (InvalidTelnetOptionException e) {
        System.err.println("Error registering option handlers: " + e.getMessage());
    }

    while (true) {
        boolean end_loop = false;
        try {
            tc.connect(remoteip, remoteport);

            Thread reader = new Thread(new TelnetClientExample());
            tc.registerNotifHandler(new TelnetClientExample());
            System.out.println("TelnetClientExample");
            System.out.println("Type AYT to send an AYT telnet command");
            System.out.println("Type OPT to print a report of status of options (0-24)");
            System.out.println("Type REGISTER to register a new SimpleOptionHandler");
            System.out.println("Type UNREGISTER to unregister an OptionHandler");
            System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
            System.out.println("Type UNSPY to stop spying the connection");

            reader.start();
            OutputStream outstr = tc.getOutputStream();

            byte[] buff = new byte[1024];
            int ret_read = 0;

            do {
                try {
                    ret_read = System.in.read(buff);
                    if (ret_read > 0) {
                        if ((new String(buff, 0, ret_read)).startsWith("AYT")) {
                            try {
                                System.out.println("Sending AYT");

                                System.out.println("AYT response:" + tc.sendAYT(5000));
                            } catch (IOException e) {
                                System.err.println("Exception waiting AYT response: " + e.getMessage());
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("OPT")) {
                            System.out.println("Status of options:");
                            for (int ii = 0; ii < 25; ii++) {
                                System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii)
                                        + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("REGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = Integer.parseInt(st.nextToken());
                                boolean initlocal = Boolean.parseBoolean(st.nextToken());
                                boolean initremote = Boolean.parseBoolean(st.nextToken());
                                boolean acceptlocal = Boolean.parseBoolean(st.nextToken());
                                boolean acceptremote = Boolean.parseBoolean(st.nextToken());
                                SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal,
                                        initremote, acceptlocal, acceptremote);
                                tc.addOptionHandler(opthand);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error registering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid REGISTER command.");
                                    System.err.println(
                                            "Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
                                    System.err.println("(optcode is an integer.)");
                                    System.err.println(
                                            "(initlocal, initremote, acceptlocal, acceptremote are boolean)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNREGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                tc.deleteOptionHandler(opcode);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error unregistering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid UNREGISTER command.");
                                    System.err.println("Use UNREGISTER optcode");
                                    System.err.println("(optcode is an integer)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("SPY")) {
                            tc.registerSpyStream(fout);
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) {
                            tc.stopSpyStream();
                        } else {
                            try {
                                outstr.write(buff, 0, ret_read);
                                outstr.flush();
                            } catch (IOException e) {
                                end_loop = true;
                            }
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Exception while reading keyboard:" + e.getMessage());
                    end_loop = true;
                }
            } while ((ret_read > 0) && (end_loop == false));

            try {
                tc.disconnect();
            } catch (IOException e) {
                System.err.println("Exception while connecting:" + e.getMessage());
            }
        } catch (IOException e) {
            System.err.println("Exception while connecting:" + e.getMessage());
            System.exit(1);
        }
    }
}

From source file:com.groupC1.control.network.TelnetClientExample.java

/***
 * Main for the TelnetClient./* w  w  w.j av  a  2 s .  c  om*/
 ***/
public static void main(String[] args) throws Exception {
    args = new String[] { "169.254.0.10", "10001" };
    FileOutputStream fout = null;
    if (args.length < 1) {
        System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]");
        System.exit(1);
    }
    String remoteip = args[0];
    int remoteport;
    if (args.length > 1) {
        remoteport = (new Integer(args[1])).intValue();
    } else {
        remoteport = 23;
    }
    try {
        fout = new FileOutputStream("spy.log", true);
    } catch (IOException e) {
        System.err.println("Exception while opening the spy file: " + e.getMessage());
    }
    tc = new org.apache.commons.net.telnet.TelnetClient();
    TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
    EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
    SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
    try {
        tc.addOptionHandler(ttopt);
        tc.addOptionHandler(echoopt);
        tc.addOptionHandler(gaopt);
    } catch (InvalidTelnetOptionException e) {
        System.err.println("Error registering option handlers: " + e.getMessage());
    }
    while (true) {
        boolean end_loop = false;
        try {
            tc.connect(remoteip, remoteport);
            Thread reader = new Thread(new TelnetClientExample());
            tc.registerNotifHandler(new TelnetClientExample());
            System.out.println("TelnetClient");
            System.out.println("Type AYT to send an AYT telnet command");
            System.out.println("Type OPT to print a report of status of options (0-24)");
            System.out.println("Type REGISTER to register a new SimpleOptionHandler");
            System.out.println("Type UNREGISTER to unregister an OptionHandler");
            System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
            System.out.println("Type UNSPY to stop spying the connection");

            reader.start();
            OutputStream outstr = tc.getOutputStream();

            byte[] buff = new byte[1024];
            int ret_read = 0;
            do {
                try {
                    ret_read = System.in.read(buff);
                    if (ret_read > 0) {
                        if ((new String(buff, 0, ret_read)).startsWith("AYT")) {
                            try {
                                System.out.println("Sending AYT");
                                System.out.println("AYT response:" + tc.sendAYT(5000));
                            } catch (IOException e) {
                                System.err.println("Exception waiting AYT response: " + e.getMessage());
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("OPT")) {
                            System.out.println("Status of options:");
                            for (int ii = 0; ii < 25; ii++) {
                                System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii)
                                        + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("REGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = Integer.parseInt(st.nextToken());
                                boolean initlocal = Boolean.parseBoolean(st.nextToken());
                                boolean initremote = Boolean.parseBoolean(st.nextToken());
                                boolean acceptlocal = Boolean.parseBoolean(st.nextToken());
                                boolean acceptremote = Boolean.parseBoolean(st.nextToken());
                                SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal,
                                        initremote, acceptlocal, acceptremote);
                                tc.addOptionHandler(opthand);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error registering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid REGISTER command.");
                                    System.err.println(
                                            "Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
                                    System.err.println("(optcode is an integer.)");
                                    System.err.println(
                                            "(initlocal, initremote, acceptlocal, acceptremote are boolean)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNREGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                tc.deleteOptionHandler(opcode);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error unregistering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid UNREGISTER command.");
                                    System.err.println("Use UNREGISTER optcode");
                                    System.err.println("(optcode is an integer)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("SPY")) {
                            tc.registerSpyStream(fout);
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) {
                            tc.stopSpyStream();
                        } else {
                            try {
                                outstr.write(buff, 0, ret_read);
                                outstr.flush();
                            } catch (IOException e) {
                                end_loop = true;
                            }
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Exception while reading keyboard:" + e.getMessage());
                    end_loop = true;
                }
            } while ((ret_read > 0) && (end_loop == false));

            try {
                tc.disconnect();
            } catch (IOException e) {
                System.err.println("Exception while connecting:" + e.getMessage());
            }
        } catch (IOException e) {
            System.err.println("Exception while connecting:" + e.getMessage());
            System.exit(1);
        }
    }
}

From source file:com.cloud.test.stress.StressTestDirectAttach.java

public static void main(String[] args) {
    String host = "http://localhost";
    String port = "8092";
    String devPort = "8080";
    String apiUrl = "/client/api";

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

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

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

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

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

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

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

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

            if (arg.equals("-z")) {
                zoneId = iter.next();
            }

            if (arg.equals("-so")) {
                serviceOfferingId = iter.next();
            }

        }

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

        for (int i = 0; i < numThreads; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    do {
                        String username = null;
                        try {
                            long now = System.currentTimeMillis();
                            Random ran = new Random();
                            username = Math.abs(ran.nextInt()) + "-user";
                            NDC.push(username);

                            s_logger.info("Starting test for the user " + username);
                            int response = executeDeployment(server, developerServer, username);
                            boolean success = false;
                            String reason = null;

                            if (response == 200) {
                                success = true;
                                if (internet) {
                                    s_logger.info("Deploy successful...waiting 5 minute before SSH tests");
                                    Thread.sleep(300000L); // Wait 60
                                    // seconds so
                                    // the windows VM
                                    // can boot up and do a sys prep.

                                    s_logger.info("Begin Linux SSH test for account " + _account.get());
                                    reason = sshTest(_linuxIP.get(), _linuxPassword.get());

                                    if (reason == null) {
                                        s_logger.info(
                                                "Linux SSH test successful for account " + _account.get());
                                    }
                                }
                                if (reason == null) {
                                    if (internet) {
                                        s_logger.info(
                                                "Windows SSH test successful for account " + _account.get());
                                    } else {
                                        s_logger.info("deploy test successful....now cleaning up");
                                        if (cleanUp) {
                                            s_logger.info(
                                                    "Waiting " + sleepTime + " ms before cleaning up vms");
                                            Thread.sleep(sleepTime);
                                        } else {
                                            success = true;
                                        }
                                    }

                                    if (usageIterator >= numThreads) {
                                        int eventsAndBillingResponseCode = executeEventsAndBilling(server,
                                                developerServer);
                                        s_logger.info(
                                                "events and usage records command finished with response code: "
                                                        + eventsAndBillingResponseCode);
                                        usageIterator = 1;

                                    } else {
                                        s_logger.info(
                                                "Skipping events and usage records for this user: usageIterator "
                                                        + usageIterator + " and number of Threads "
                                                        + numThreads);
                                        usageIterator++;
                                    }

                                    if ((users == null) && (accountName == null)) {
                                        s_logger.info("Sending cleanup command");
                                        int cleanupResponseCode = executeCleanup(server, developerServer,
                                                username);
                                        s_logger.info("cleanup command finished with response code: "
                                                + cleanupResponseCode);
                                        success = (cleanupResponseCode == 200);
                                    } else {
                                        s_logger.info("Sending stop DomR / destroy VM command");
                                        int stopResponseCode = executeStop(server, developerServer, username);
                                        s_logger.info("stop(destroy) command finished with response code: "
                                                + stopResponseCode);
                                        success = (stopResponseCode == 200);
                                    }

                                } else {
                                    // Just stop but don't destroy the
                                    // VMs/Routers
                                    s_logger.info("SSH test failed for account " + _account.get()
                                            + "with reason '" + reason + "', stopping VMs");
                                    int stopResponseCode = executeStop(server, developerServer, username);
                                    s_logger.info(
                                            "stop command finished with response code: " + stopResponseCode);
                                    success = false; // since the SSH test
                                    // failed, mark the
                                    // whole test as
                                    // failure
                                }
                            } else {
                                // Just stop but don't destroy the
                                // VMs/Routers
                                s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs");
                                int stopResponseCode = executeStop(server, developerServer, username);
                                s_logger.info("stop command finished with response code: " + stopResponseCode);
                                success = false; // since the deploy test
                                // failed, mark the
                                // whole test as failure
                            }

                            if (success) {
                                s_logger.info("***** Completed test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L) + " seconds");

                            } else {
                                s_logger.info("##### FAILED test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L)
                                        + " seconds with reason : " + reason);
                            }
                            s_logger.info("Sleeping for " + wait + " seconds before starting next iteration");
                            Thread.sleep(wait);
                        } catch (Exception e) {
                            s_logger.warn("Error in thread", e);
                            try {
                                int stopResponseCode = executeStop(server, developerServer, username);
                                s_logger.info("stop response code: " + stopResponseCode);
                            } catch (Exception e1) {
                            }
                        } finally {
                            NDC.clear();
                        }
                    } while (repeat);
                }
            }).start();
        }
    } catch (Exception e) {
        s_logger.error(e);
    }
}

From source file:DIA_Umpire_Quant.DIA_Umpire_ProtQuant.java

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

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

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

    String Combined_Prot = "";
    boolean DefaultProtFiltering = true;

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

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

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

    HashMap<String, String[]> BaitList = new HashMap<>();
    HashMap<String, String> BaitName = new HashMap<>();
    HashMap<String, String[]> ControlList = new HashMap<>();
    HashMap<String, String> ControlName = new HashMap<>();

    //<editor-fold defaultstate="collapsed" desc="Reading parameter file">
    while ((line = reader.readLine()) != null) {
        line = line.trim();
        Logger.getRootLogger().info(line);
        if (!"".equals(line) && !line.startsWith("#")) {
            //System.out.println(line);
            if (line.equals("==File list begin")) {
                do {
                    line = reader.readLine();
                    line = line.trim();
                    if (line.equals("==File list end")) {
                        continue;
                    } else if (!"".equals(line)) {
                        File newfile = new File(line);
                        if (newfile.exists()) {
                            AssignFiles.put(newfile.getAbsolutePath(), newfile);
                        } else {
                            Logger.getRootLogger().info("File: " + newfile + " does not exist.");
                        }
                    }
                } while (!line.equals("==File list end"));
            }
            if (line.split("=").length < 2) {
                continue;
            }
            String type = line.split("=")[0].trim();
            String value = line.split("=")[1].trim();
            switch (type) {
            case "Path": {
                WorkFolder = value;
                break;
            }
            case "path": {
                WorkFolder = value;
                break;
            }
            case "Thread": {
                NoCPUs = Integer.parseInt(value);
                break;
            }
            case "Fasta": {
                tandemPara.FastaPath = value;
                break;
            }
            case "Combined_Prot": {
                Combined_Prot = value;
                break;
            }
            case "DefaultProtFiltering": {
                DefaultProtFiltering = Boolean.parseBoolean(value);
                break;
            }
            case "DecoyPrefix": {
                if (!"".equals(value)) {
                    tandemPara.DecoyPrefix = value;
                }
                break;
            }
            case "ProteinFDR": {
                tandemPara.ProtFDR = Float.parseFloat(value);
                break;
            }
            case "FilterWeight": {
                FilterWeight = value;
                break;
            }
            case "MinWeight": {
                MinWeight = Float.parseFloat(value);
                break;
            }
            case "TopNFrag": {
                TopNFrag = Integer.parseInt(value);
                break;
            }
            case "TopNPep": {
                TopNPep = Integer.parseInt(value);
                break;
            }
            case "Freq": {
                Freq = Float.parseFloat(value);
                break;
            }
            //<editor-fold defaultstate="collapsed" desc="SaintOutput">
            case "ExportSaintInput": {
                ExportSaint = Boolean.parseBoolean(value);
                break;
            }
            case "QuantitationType": {
                switch (value) {
                case "MS1": {
                    SAINT_MS1 = true;
                    SAINT_MS2 = false;
                    break;
                }
                case "MS2": {
                    SAINT_MS1 = false;
                    SAINT_MS2 = true;
                    break;
                }
                case "BOTH": {
                    SAINT_MS1 = true;
                    SAINT_MS2 = true;
                    break;
                }
                }
                break;
            }
            //                    case "BaitInputFile": {
            //                        SaintBaitFile = value;
            //                        break;
            //                    }
            //                    case "PreyInputFile": {
            //                        SaintPreyFile = value;
            //                        break;
            //                    }
            //                    case "InterationInputFile": {
            //                        SaintInteractionFile = value;
            //                        break;
            //                    }
            default: {
                if (type.startsWith("BaitName_")) {
                    BaitName.put(type.substring(9), value);
                }
                if (type.startsWith("BaitFile_")) {
                    BaitList.put(type.substring(9), value.split("\t"));
                }
                if (type.startsWith("ControlName_")) {
                    ControlName.put(type.substring(12), value);
                }
                if (type.startsWith("ControlFile_")) {
                    ControlList.put(type.substring(12), value.split("\t"));
                }
                break;
            }
            //</editor-fold>                    
            }
        }
    }
    //</editor-fold>

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

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

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

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

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

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

        for (File fileEntry : AssignFiles.values()) {
            String mzXMLFile = fileEntry.getAbsolutePath();
            if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) {
                DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs);
                Logger.getRootLogger().info(
                        "=================================================================================================");
                Logger.getRootLogger().info("Processing " + mzXMLFile);
                if (!DiaFile.LoadDIASetting()) {
                    Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete");
                    System.exit(1);
                }
                if (!DiaFile.LoadParams()) {
                    Logger.getRootLogger().info("Loading parameters failed, job is incomplete");
                    System.exit(1);
                }
                Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "....");

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

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

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

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

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

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

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

        //</editor-fold>

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

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

From source file:eu.fbk.utils.lsa.util.Anvur.java

public static void main(String[] args) throws Exception {
    String logConfig = System.getProperty("log-config");
    if (logConfig == null) {
        logConfig = "log-config.txt";
    }//from w  w  w .jav a 2  s  .co  m

    PropertyConfigurator.configure(logConfig);
    /*
    if (args.length != 2)
    {
    log.println("Usage: java -mx512M eu.fbk.utils.lsa.util.Anvur in-file out-dir");
    System.exit(1);
    }
            
    File l = new File(args[1]);
    if (!l.exists())
    {
    l.mkdir();
    }
    List<String[]> list = readText(new File(args[0]));
    String oldCategory = "";
    for (int i=0;i<list.size();i++)
    {
    String[] s = list.get(i);
    if (!oldCategory.equals(s[0]))
    {
    File f = new File(args[1] + File.separator + s[0]);
    boolean b = f.mkdir();
    logger.debug(f + " created " + b);
    }
            
    File g = new File(args[1] + File.separator + s[0] + File.separator + s[1] + ".txt");
    logger.debug("writing " + g + "...");
    PrintWriter pw = new PrintWriter(new FileWriter(g));
    //pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2]));
    if (s.length == 5)
    {
    pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2] + " " + s[4].replace('_', ' ')));
    }
    else
    {
    pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2]));
    }
    pw.flush();
    pw.close();
            
    } // end for i
    */

    if (args.length != 7) {
        System.out.println(args.length);
        System.out.println(
                "Usage: java -mx2G eu.fbk.utils.lsa.util.Anvur input threshold size dim idf in-file-csv fields\n\n");
        System.exit(1);
    }

    //
    DecimalFormat dec = new DecimalFormat("#.00");

    File Ut = new File(args[0] + "-Ut");
    File Sk = new File(args[0] + "-S");
    File r = new File(args[0] + "-row");
    File c = new File(args[0] + "-col");
    File df = new File(args[0] + "-df");
    double threshold = Double.parseDouble(args[1]);
    int size = Integer.parseInt(args[2]);
    int dim = Integer.parseInt(args[3]);
    boolean rescaleIdf = Boolean.parseBoolean(args[4]);

    //"author_check"0,   "authors"1,   "title"2,   "year"3,   "pubtype"4,   "publisher"5,   "journal"6,   "volume"7,   "number"8,   "pages"9,   "abstract"10,   "nauthors",   "citedby"
    String[] labels = { "author_check", "authors", "title", "year", "pubtype", "publisher", "journal", "volume",
            "number", "pages", "abstract", "nauthors", "citedby"
            //author_id   authors   title   year   pubtype   publisher   journal   volume   number   pages   abstract   nauthors   citedby

    };
    String name = buildName(labels, args[6]);

    File bwf = new File(args[5] + name + "-bow.txt");
    PrintWriter bw = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bwf), "UTF-8")));
    File bdf = new File(args[5] + name + "-bow.csv");
    PrintWriter bd = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bdf), "UTF-8")));
    File lwf = new File(args[5] + name + "-ls.txt");
    PrintWriter lw = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(lwf), "UTF-8")));
    File ldf = new File(args[5] + name + "-ls.csv");
    PrintWriter ld = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ldf), "UTF-8")));
    File blwf = new File(args[5] + name + "-bow+ls.txt");
    PrintWriter blw = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(blwf), "UTF-8")));
    File bldf = new File(args[5] + name + "-bow+ls.csv");
    PrintWriter bld = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bldf), "UTF-8")));
    File logf = new File(args[5] + name + ".log");
    PrintWriter log = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logf), "UTF-8")));

    //System.exit(0);
    LSM lsm = new LSM(Ut, Sk, r, c, df, dim, rescaleIdf);
    LSSimilarity lss = new LSSimilarity(lsm, size);

    List<String[]> list = readText(new File(args[5]));

    // author_check   authors   title   year   pubtype   publisher   journal   volume   number   pages   abstract   nauthors   citedby

    //header
    for (int i = 0; i < list.size(); i++) {
        String[] s1 = list.get(i);
        String t1 = s1[0].toLowerCase();
        bw.print("\t");
        lw.print("\t");
        blw.print("\t");
        bw.print(i + "(" + s1[0] + ")");
        lw.print(i + "(" + s1[0] + ")");
        blw.print(i + "(" + s1[0] + ")");
    } // end for i

    bw.print("\n");
    lw.print("\n");
    blw.print("\n");
    for (int i = 0; i < list.size(); i++) {
        logger.info(i + "\t");
        String[] s1 = list.get(i);
        String t1 = buildText(s1, args[6]);
        BOW bow1 = new BOW(t1);
        logger.info(bow1);

        Vector d1 = lsm.mapDocument(bow1);
        d1.normalize();
        log.println("d1:" + d1);

        Vector pd1 = lsm.mapPseudoDocument(d1);
        pd1.normalize();
        log.println("pd1:" + pd1);

        Vector m1 = merge(pd1, d1);
        log.println("m1:" + m1);

        // write the orginal line
        for (int j = 0; j < s1.length; j++) {
            bd.print(s1[j]);
            bd.print("\t");
            ld.print(s1[j]);
            ld.print("\t");
            bld.print(s1[j]);
            bld.print("\t");

        }
        // write the bow, ls, and bow+ls vectors
        bd.println(d1);
        ld.println(pd1);
        bld.println(m1);

        bw.print(i + "(" + s1[0] + ")");
        lw.print(i + "(" + s1[0] + ")");
        blw.print(i + "(" + s1[0] + ")");
        for (int j = 0; j < i + 1; j++) {
            bw.print("\t");
            lw.print("\t");
            blw.print("\t");
        } // end for j

        for (int j = i + 1; j < list.size(); j++) {
            logger.info(i + "\t" + j);
            String[] s2 = list.get(j);

            String t2 = buildText(s2, args[6]);
            BOW bow2 = new BOW(t2);

            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") t1:" + t1);
            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") t2:" + t2);
            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow1:" + bow1);
            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow2:" + bow2);

            Vector d2 = lsm.mapDocument(bow2);
            d2.normalize();
            log.println("d2:" + d2);

            Vector pd2 = lsm.mapPseudoDocument(d2);
            pd2.normalize();
            log.println("pd2:" + pd2);

            Vector m2 = merge(pd2, d2);
            log.println("m2:" + m2);

            float cosVSM = d1.dotProduct(d2) / (float) Math.sqrt(d1.dotProduct(d1) * d2.dotProduct(d2));
            float cosLSM = pd1.dotProduct(pd2) / (float) Math.sqrt(pd1.dotProduct(pd1) * pd2.dotProduct(pd2));
            float cosBOWLSM = m1.dotProduct(m2) / (float) Math.sqrt(m1.dotProduct(m1) * m2.dotProduct(m2));
            bw.print("\t");
            bw.print(dec.format(cosVSM));
            lw.print("\t");
            lw.print(dec.format(cosLSM));
            blw.print("\t");
            blw.print(dec.format(cosBOWLSM));

            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow\t" + cosVSM);
            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") ls:\t" + cosLSM);
            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow+ls:\t" + cosBOWLSM);
        }
        bw.print("\n");
        lw.print("\n");
        blw.print("\n");
    } // end for i

    logger.info("wrote " + bwf);
    logger.info("wrote " + bwf);
    logger.info("wrote " + bdf);
    logger.info("wrote " + lwf);
    logger.info("wrote " + ldf);
    logger.info("wrote " + blwf);
    logger.info("wrote " + bldf);
    logger.info("wrote " + logf);

    ld.close();
    bd.close();
    bld.close();
    bw.close();
    lw.close();
    blw.close();

    log.close();

}

From source file:puma.central.pdp.CentralPUMAPDP.java

public static void main(String[] args) {
    // initialize log4j
    BasicConfigurator.configure();/*from  w w w .ja  va2 s.  c om*/

    CommandLineParser parser = new BasicParser();
    Options options = new Options();
    options.addOption("ph", "policy-home", true,
            "The folder where to find the policy file given with the given policy id. "
                    + "For default operation, this folder should contain the central PUMA policy (called "
                    + CENTRAL_PUMA_POLICY_FILENAME + ")");
    options.addOption("pid", "policy-id", true,
            "The id of the policy to be evaluated on decision requests. Default value: " + GLOBAL_PUMA_POLICY_ID
                    + ")");
    options.addOption("s", "log-disabled", true, "Verbose mode (true/false)");
    String policyHome = "";
    String policyId = "";

    // read command line
    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Simple PDP Test", options);
            return;
        }
        if (line.hasOption("policy-home")) {
            policyHome = line.getOptionValue("policy-home");
        } else {
            logger.log(Level.WARNING, "Incorrect arguments given.");
            return;
        }
        if (line.hasOption("log-disabled") && Boolean.parseBoolean(line.getOptionValue("log-disabled"))) {
            logger.log(Level.INFO, "Now switching to silent mode");
            LogManager.getLogManager().getLogger("").setLevel(Level.WARNING);
            //LogManager.getLogManager().reset();
        }
        if (line.hasOption("policy-id")) {
            policyId = line.getOptionValue("policy-id");
        } else {
            logger.log(Level.INFO, "Using default policy id: " + GLOBAL_PUMA_POLICY_ID);
            policyId = GLOBAL_PUMA_POLICY_ID;
        }
    } catch (ParseException e) {
        logger.log(Level.WARNING, "Incorrect arguments given.", e);
        return;
    }

    //
    // STARTUP THE RMI SERVER
    //      
    // if (System.getSecurityManager() == null) {
    // System.setSecurityManager(new SecurityManager());
    // }
    final CentralPUMAPDP pdp;
    try {
        pdp = new CentralPUMAPDP(policyHome, policyId);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "FAILED to set up the CentralPUMAPDP. Quitting.", e);
        return;
    }

    try {
        Registry registry;
        try {
            registry = LocateRegistry.createRegistry(RMI_REGISITRY_PORT);
            logger.info("Created new RMI registry");
        } catch (RemoteException e) {
            // MDC: I hope this means the registry already existed.
            registry = LocateRegistry.getRegistry(RMI_REGISITRY_PORT);
            logger.info("Reusing existing RMI registry");
        }
        CentralPUMAPDPRemote stub = (CentralPUMAPDPRemote) UnicastRemoteObject.exportObject(pdp, 0);
        registry.bind(CENTRAL_PUMA_PDP_RMI_NAME, stub);
        logger.info(
                "Central PUMA PDP up and running (available using RMI with name \"central-puma-pdp\" on RMI registry port "
                        + RMI_REGISITRY_PORT + ")");
        Thread.sleep(100); // MDC: vroeger eindigde de Thread om n of andere reden, dit lijkt te werken...
    } catch (Exception e) {
        logger.log(Level.SEVERE, "FAILED to set up PDP as RMI server", e);
    }

    //
    // STARTUP THE THRIFT PEP SERVER
    //
    //logger.log(Level.INFO, "Not setting up the Thrift server");

    // set up server
    //      PEPServer handler = new PEPServer(new CentralPUMAPEP(pdp));
    //      RemotePEPService.Processor<PEPServer> processor = new RemotePEPService.Processor<PEPServer>(handler);
    //      TServerTransport serverTransport;
    //      try {
    //         serverTransport = new TServerSocket(THRIFT_PEP_PORT);
    //      } catch (TTransportException e) {
    //         e.printStackTrace();
    //         return;
    //      }
    //      TServer server = new TSimpleServer(new TServer.Args(serverTransport).processor(processor));
    //      System.out.println("Setting up the Thrift PEP server on port " + THRIFT_PEP_PORT);
    //      server.serve();
    //
    // STARTUP THE THRIFT PEP SERVER
    //
    //logger.log(Level.INFO, "Not setting up the Thrift server");

    // set up server
    // do this in another thread not to block the main thread
    new Thread(new Runnable() {
        @Override
        public void run() {
            RemotePDPService.Processor<CentralPUMAPDP> pdpProcessor = new RemotePDPService.Processor<CentralPUMAPDP>(
                    pdp);
            TServerTransport pdpServerTransport;
            try {
                pdpServerTransport = new TServerSocket(THRIFT_PDP_PORT);
            } catch (TTransportException e) {
                e.printStackTrace();
                return;
            }
            TServer pdpServer = new TThreadPoolServer(
                    new TThreadPoolServer.Args(pdpServerTransport).processor(pdpProcessor));
            logger.info("Setting up the Thrift PDP server on port " + THRIFT_PDP_PORT);
            pdpServer.serve();
        }
    }).start();
}