Example usage for java.lang Boolean valueOf

List of usage examples for java.lang Boolean valueOf

Introduction

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

Prototype

public static Boolean valueOf(String s) 

Source Link

Document

Returns a Boolean with a value represented by the specified string.

Usage

From source file:net.ontopia.topicmaps.db2tm.Execute.java

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

    // Initialize logging
    CmdlineUtils.initializeLogging();//from   w w w  . java  2 s.c o  m

    // Register logging options
    CmdlineOptions options = new CmdlineOptions("Execute", argv);
    CmdlineUtils.registerLoggingOptions(options);
    OptionsListener ohandler = new OptionsListener();
    options.addLong(ohandler, "tm", 't', true);
    options.addLong(ohandler, "baseuri", 'b', true);
    options.addLong(ohandler, "out", 'o', true);
    options.addLong(ohandler, "relations", 'r', true);
    options.addLong(ohandler, "force-rescan", 'f', true);

    // Parse command line options
    try {
        options.parse();
    } catch (CmdlineOptions.OptionsException e) {
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
    }

    // Get command line arguments
    String[] args = options.getArguments();

    if (args.length < 2) {
        usage();
        System.exit(3);
    }

    // Arguments
    String operation = args[0];
    String cfgfile = args[1];

    if (!"add".equals(operation) && !"sync".equals(operation) && !"remove".equals(operation)) {
        usage();
        System.err.println("Operation '" + operation + "' not supported.");
        System.exit(3);
    }

    try {
        // Read mapping file
        log.debug("Reading relation mapping file {}", cfgfile);
        RelationMapping mapping = RelationMapping.read(new File(cfgfile));

        // open topic map
        String tmurl = ohandler.tm;
        log.debug("Opening topic map {}", tmurl);
        TopicMapIF topicmap;
        if (tmurl == null || "tm:in-memory:new".equals(tmurl))
            topicmap = new InMemoryTopicMapStore().getTopicMap();
        else if ("tm:rdbms:new".equals(tmurl))
            topicmap = new RDBMSTopicMapStore().getTopicMap();
        else {
            TopicMapReaderIF reader = ImportExportUtils.getReader(tmurl);
            topicmap = reader.read();
        }
        TopicMapStoreIF store = topicmap.getStore();

        // base locator
        String outfile = ohandler.out;
        LocatorIF baseloc = (outfile == null ? store.getBaseAddress() : new URILocator(new File(outfile)));
        if (baseloc == null && tmurl != null)
            baseloc = (ohandler.baseuri == null ? new URILocator(tmurl) : new URILocator(ohandler.baseuri));

        // figure out which relations to actually process
        Collection<String> relations = null;
        if (ohandler.relations != null) {
            String[] relnames = StringUtils.split(ohandler.relations, ",");
            if (relnames.length > 0) {
                relations = new HashSet<String>(relnames.length);
                relations.addAll(Arrays.asList(relnames));
            }
        }

        try {
            // Process data sources in mapping
            if ("add".equals(operation))
                Processor.addRelations(mapping, relations, topicmap, baseloc);
            else if ("sync".equals(operation)) {
                boolean rescan = ohandler.forceRescan != null
                        && Boolean.valueOf(ohandler.forceRescan).booleanValue();
                Processor.synchronizeRelations(mapping, relations, topicmap, baseloc, rescan);
            } else if ("remove".equals(operation))
                Processor.removeRelations(mapping, relations, topicmap, baseloc);
            else
                throw new UnsupportedOperationException("Unsupported operation: " + operation);

            // export topicmap
            if (outfile != null) {
                log.debug("Exporting topic map to {}", outfile);
                TopicMapWriterIF writer = ImportExportUtils.getWriter(new File(outfile));
                writer.write(topicmap);
            }

            // commit transaction
            store.commit();
            log.debug("Transaction committed.");
        } catch (Exception t) {
            log.error("Error occurred while running operation '" + operation + "'", t);
            // abort transaction
            store.abort();
            log.debug("Transaction aborted.");
            throw t;
        } finally {
            if (store.isOpen())
                store.close();
        }

    } catch (Exception e) {
        Throwable cause = e.getCause();
        if (cause instanceof DB2TMException)
            System.err.println("Error: " + e.getMessage());
        else
            throw e;
    }
}

From source file:com.hp.test.framework.Reporting.Utlis.java

public static void main(String ar[]) throws IOException {

    ArrayList<String> runs_list = new ArrayList<String>();
    String basepath = replacelogs();
    String path = basepath + "ATU Reports\\Results";
    File directory = new File(path);
    File[] subdirs = directory.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY);
    String htmlReport = basepath + "HTML_Design_Files\\CSS\\HtmlReport.html";
    for (File dir : subdirs) {

        runs_list.add(dir.getName());// ww w . ja v  a 2s .co  m
    }
    String Reports_path = basepath + "ATU Reports\\";
    int LatestRun = Utlis.getLastRun(Reports_path);
    String Last_run_path = Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "\\";

    HtmlParse.replaceMainTable(false, new File(Last_run_path + "/CurrentRun.html"));
    HtmlParse.replaceCountsinJSFile(new File("HTML_Design_Files/JS/3dChart.js"), Last_run_path);
    UpdateTestCaseDesciption.basepath = Last_run_path;
    UpdateTestCaseDesciption.getTestCaseHtmlPath(Last_run_path + "/CurrentRun.html");
    UpdateTestCaseDesciption.replaceDetailsTable(Last_run_path + "/CurrentRun.html");
    //   GenerateFailReport.genarateFailureReport(new File(htmlReport), Reports_path + "Results\\Run_" + String.valueOf(LatestRun));
    genarateFailureReport(new File(htmlReport), Reports_path + "Results\\");
    Map<String, List<String>> runCounts = GetCountsrunsWise(runs_list, path);

    int success = replaceCounts(runCounts, path);

    if (success == 0) {
        File SourceFile = new File(path + "\\lineChart_temp.js");
        File RenameFile = new File(path + "\\lineChart.js");

        renameOriginalFile(SourceFile, RenameFile);

        File SourceFile1 = new File(path + "\\barChart_temp.js");
        File RenameFile1 = new File(path + "\\barChart.js");

        renameOriginalFile(SourceFile1, RenameFile1);

        Utlis.getpaths(Reports_path + "\\Results\\Run_" + String.valueOf(LatestRun));
        try {
            Utlis.replaceMainTable(false, new File(Reports_path + "index.html"));
            Utlis.replaceMainTable(true, new File(Reports_path + "results\\" + "ConsolidatedPage.html"));
            Utlis.replaceMainTable(true,
                    new File(Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "CurrentRun.html"));

            fileList.add(
                    new File(Reports_path + "\\Results\\Run_" + String.valueOf(LatestRun) + "CurrentRun.html"));
            for (File f : fileList) {
                Utlis.replaceMainTable(true, f);
            }

        } catch (Exception ex) {
            log.info("Error in updating Report format" + ex.getMessage());
        }

        Last_run_path = Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "\\";

        //   HtmlParse.replaceMainTable(false, new File(Last_run_path + "/CurrentRun.html"));
        //   HtmlParse.replaceCountsinJSFile(new File("../HTML_Design_Files/JS/3dChart.js"), Last_run_path);
        ArrayList<String> to_list = new ArrayList<String>();
        ReportingProperties reportingproperties = new ReportingProperties();
        String temp_eml = reportingproperties.getProperty("TOLIST");
        String JenkinsURL = reportingproperties.getProperty("JENKINSURL");

        String ScreenShotsDir = reportingproperties.getProperty("ScreenShotsDirectory");
        Boolean cleanScreenshotsDir = Boolean.valueOf(reportingproperties.getProperty("CleanPreScreenShots"));
        Boolean generatescreenshots = Boolean.valueOf(reportingproperties.getProperty("GenerateScreenShots"));
        String HtmlreportFilePrefix = reportingproperties.getProperty("HtmlreportFilePrefix");

        if (cleanScreenshotsDir) {
            if (!CleanFilesinDir(ScreenShotsDir)) {
                log.error("Not able to Clean the Previous Run Details in the paht" + ScreenShotsDir);
            } else {
                log.info("Cleaning Previous Run Details in the paht" + ScreenShotsDir + "Sucess");
            }
        }
        List<String> scr_fileList;
        List<String> html_fileList;
        if (generatescreenshots) {
            scr_fileList = GetFileListinDir(ScreenShotsDir, "png");

            int len = scr_fileList.size();
            len = len + 1;

            screenshot.generatescreenshot(Last_run_path + "CurrentRun.html",
                    ScreenShotsDir + "screenshot_" + len + ".png");
            File source = new File(Reports_path + "Results\\HtmlReport.html");
            File dest = new File(ScreenShotsDir + HtmlreportFilePrefix + "_HtmlReport.html");
            //  Files.copy(f.toPath(), (new File((ScreenShotsDir+HtmlreportFilePrefix+"_HtmlReport.html").toPath(),StandardCopyOption.REPLACE_EXISTING);
            FileUtils.copyFile(source, dest);
            scr_fileList.clear();

        }

        scr_fileList = GetFileListinDir(ScreenShotsDir, "png");
        html_fileList = GetFileListinDir(ScreenShotsDir, "html");

        if (temp_eml.length() > 1) {
            String[] to_list_temp = temp_eml.split(",");

            if (to_list_temp.length > 0) {
                for (String to_list_temp1 : to_list_temp) {
                    to_list.add(to_list_temp1);
                }
            }
            if (to_list.size() > 0) {
                screenshot.generatescreenshot(Last_run_path + "CurrentRun.html",
                        Last_run_path + "screenshot.png");

                //    cleanTempDir.cleanandCreate(Reports_path, LatestRun);
                // ZipUtils.ZipFolder(Reports_path + "temp", Reports_path + "ISTF_Reports.zip");
                if (generatescreenshots) {
                    SendingEmail.sendmail(to_list, JenkinsURL, scr_fileList, html_fileList);
                } else {
                    SendingEmail.sendmail(to_list, JenkinsURL, Reports_path + "/Results/HtmlReport.html",
                            Last_run_path + "screenshot.png");
                }

                //  FileUtils.deleteQuietly(new File(Reports_path + "ISTF_Reports.zip"));
                // FileUtils.deleteDirectory(new File(Reports_path + "temp"));
            }
        }
    }
}

From source file:com.alibaba.jstorm.daemon.supervisor.SandBoxMaker.java

public static void main(String[] args) {
    Map<Object, Object> conf = Utils.readStormConfig();

    conf.put("java.sandbox.enable", Boolean.valueOf(true));

    SandBoxMaker maker = new SandBoxMaker(conf);

    try {/* w ww. j  ava  2  s  .c o m*/
        System.out.println("sandboxPolicy:" + maker.sandboxPolicy("simple", new HashMap<String, String>()));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.sludev.mssqlapplylog.MSSQLApplyLogMain.java

public static void main(String[] args) {
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();

    // Most of the following defaults should be changed in
    // the --conf or "conf.properties" file
    String sqlURL = null;/*from w ww.j a va 2s .c  o  m*/
    String sqlUser = null;
    String sqlPass = null;
    String sqlDb = null;
    String sqlHost = "127.0.0.1";
    String backupDirStr = null;
    String laterThanStr = "";
    String fullBackupPathStr = null;
    String fullBackupPatternStr = "(?:[\\w_-]+?)(\\d+)\\.bak";
    String fullBackupDatePatternStr = "yyyyMMddHHmm";
    String sqlProcessUser = null;
    String logBackupPatternStr = "(.*)\\.trn";
    String logBackupDatePatternStr = "yyyyMMddHHmmss";

    boolean doFullRestore = false;
    Boolean useLogFileLastMode = null;
    Boolean monitorLogBackupDir = null;

    options.addOption(Option.builder().longOpt("conf").desc("Configuration file.").hasArg().build());

    options.addOption(Option.builder().longOpt("laterthan").desc("'Later Than' file filter.").hasArg().build());

    options.addOption(Option.builder().longOpt("restore-full")
            .desc("Restore the full backup before continuing.").build());

    options.addOption(Option.builder().longOpt("use-lastmod")
            .desc("Sort/filter the log backups using their File-System 'Last Modified' date.").build());

    options.addOption(Option.builder().longOpt("monitor-backup-dir")
            .desc("Monitor the backup directory for new log backups, and apply them.").build());

    CommandLine line = null;
    try {
        try {
            line = parser.parse(options, args);
        } catch (ParseException ex) {
            throw new MSSQLApplyLogException(String.format("Error parsing command line.'%s'", ex.getMessage()),
                    ex);
        }

        String confFile = null;

        // Process the command line arguments
        Iterator cmdI = line.iterator();
        while (cmdI.hasNext()) {
            Option currOpt = (Option) cmdI.next();
            String currOptName = currOpt.getLongOpt();

            switch (currOptName) {
            case "conf":
                // Parse the configuration file
                confFile = currOpt.getValue();
                break;

            case "laterthan":
                // "Later Than" file date filter
                laterThanStr = currOpt.getValue();
                break;

            case "restore-full":
                // Do a full backup restore before restoring logs
                doFullRestore = true;
                break;

            case "monitor-backup-dir":
                // Monitor the backup directory for new logs
                monitorLogBackupDir = true;
                break;

            case "use-lastmod":
                // Use the last-modified date on Log Backup files for sorting/filtering
                useLogFileLastMode = true;
                break;
            }
        }

        Properties confProperties = null;

        if (StringUtils.isBlank(confFile) || Files.isReadable(Paths.get(confFile)) == false) {
            throw new MSSQLApplyLogException(
                    "Missing or unreadable configuration file.  Please specify --conf");
        } else {
            // Process the conf.properties file
            confProperties = new Properties();
            try {
                confProperties.load(Files.newBufferedReader(Paths.get(confFile)));
            } catch (IOException ex) {
                throw new MSSQLApplyLogException("Error loading properties file", ex);
            }

            sqlURL = confProperties.getProperty("sqlURL", "");
            sqlUser = confProperties.getProperty("sqlUser", "");
            sqlPass = confProperties.getProperty("sqlPass", "");
            sqlDb = confProperties.getProperty("sqlDb", "");
            sqlHost = confProperties.getProperty("sqlHost", "");
            backupDirStr = confProperties.getProperty("backupDir", "");

            if (StringUtils.isBlank(laterThanStr)) {
                laterThanStr = confProperties.getProperty("laterThan", "");
            }

            fullBackupPathStr = confProperties.getProperty("fullBackupPath", fullBackupPathStr);
            fullBackupPatternStr = confProperties.getProperty("fullBackupPattern", fullBackupPatternStr);
            fullBackupDatePatternStr = confProperties.getProperty("fullBackupDatePattern",
                    fullBackupDatePatternStr);
            sqlProcessUser = confProperties.getProperty("sqlProcessUser", "");

            logBackupPatternStr = confProperties.getProperty("logBackupPattern", logBackupPatternStr);
            logBackupDatePatternStr = confProperties.getProperty("logBackupDatePattern",
                    logBackupDatePatternStr);

            if (useLogFileLastMode == null) {
                String useLogFileLastModeStr = confProperties.getProperty("useLogFileLastMode", "false");
                useLogFileLastMode = Boolean
                        .valueOf(StringUtils.lowerCase(StringUtils.trim(useLogFileLastModeStr)));
            }

            if (monitorLogBackupDir == null) {
                String monitorBackupDirStr = confProperties.getProperty("monitorBackupDir", "false");
                monitorLogBackupDir = Boolean
                        .valueOf(StringUtils.lowerCase(StringUtils.trim(monitorBackupDirStr)));
            }
        }
    } catch (MSSQLApplyLogException ex) {
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
            pw.append(String.format("Error : '%s'\n\n", ex.getMessage()));

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(pw, 80, "\njava -jar mssqlapplylog.jar ",
                    "\nThe MSSQLApplyLog application can be used in a variety of options and modes.\n", options,
                    0, 2, " All Rights Reserved.", true);

            System.out.println(sw.toString());
        } catch (IOException iex) {
            LOGGER.debug("Error processing usage", iex);
        }

        System.exit(1);
    }

    MSSQLApplyLogConfig config = MSSQLApplyLogConfig.from(backupDirStr, fullBackupPathStr,
            fullBackupDatePatternStr, laterThanStr, fullBackupPatternStr, logBackupPatternStr,
            logBackupDatePatternStr, sqlHost, sqlDb, sqlUser, sqlPass, sqlURL, sqlProcessUser,
            useLogFileLastMode, doFullRestore, monitorLogBackupDir);

    MSSQLApplyLog logProc = MSSQLApplyLog.from(config);

    BasicThreadFactory thFactory = new BasicThreadFactory.Builder().namingPattern("restoreThread-%d").build();

    ExecutorService mainThreadExe = Executors.newSingleThreadExecutor(thFactory);

    Future<Integer> currRunTask = mainThreadExe.submit(logProc);

    mainThreadExe.shutdown();

    Integer resp = 0;
    try {
        resp = currRunTask.get();
    } catch (InterruptedException ex) {
        LOGGER.error("Application 'main' thread was interrupted", ex);
    } catch (ExecutionException ex) {
        LOGGER.error("Application 'main' thread execution error", ex);
    } finally {
        // If main leaves for any reason, shutdown all threads
        mainThreadExe.shutdownNow();
    }

    System.exit(resp);
}

From source file:benchmarkio.controlcenter.LaunchRocket.java

public static void main(final String[] args) throws Exception {
    // create the parser
    final CommandLineParser parser = new BasicParser();

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

    if (cmd.hasOption("u")) {
        displayHelp();/*from w ww .  j a va 2s  .com*/
    }

    final String host = cmd.getOptionValue("host");
    final int port = Integer.parseInt(cmd.getOptionValue("port"));
    final BrokerType brokerType = BrokerType.valueOf(cmd.getOptionValue("broker-type"));
    final int numConsumers = Integer.parseInt(cmd.getOptionValue("num-consumers"));
    final int numProducers = Integer.parseInt(cmd.getOptionValue("num-producers"));
    final int totalNumberOfMessages = Integer.parseInt(cmd.getOptionValue("total-number-of-messages"));
    final double msgSizeInKB = Double.parseDouble(cmd.getOptionValue("msg-size-in-kb"));

    // Optional options
    final Optional<String> optionalBenchmarkType = Optional.fromNullable(cmd.getOptionValue("benchmark-type"));
    final Optional<String> optionalDurable = Optional.fromNullable(cmd.getOptionValue("durable"));
    // Kafka Specific
    final Optional<String> optionalZookeeper = Optional.fromNullable(cmd.getOptionValue("zookeeper"));
    Optional<String> optionalKafkaProducerType = Optional
            .fromNullable(cmd.getOptionValue("kafka-producer-type"));

    BenchmarkType benchmarkType;
    if (optionalBenchmarkType.isPresent()) {
        benchmarkType = BenchmarkType.valueOf(optionalBenchmarkType.get());
    } else {
        log.info("Benchmark type was not specified, defaulting to: {}", BenchmarkType.PRODUCER_AND_CONSUMER);

        benchmarkType = BenchmarkType.PRODUCER_AND_CONSUMER;
    }

    boolean durable = false;
    if (optionalDurable.isPresent()) {
        durable = Boolean.valueOf(optionalDurable.get());
    } else {
        log.info("Durable parameter was not specified, defaulting to: FALSE");
    }

    if (brokerType == BrokerType.KAFKA) {
        if (!optionalZookeeper.isPresent()) {
            log.error("zookeeper is missing, it is a required property for KAFKA broker");

            System.exit(0);
        }

        if (!optionalKafkaProducerType.isPresent()) {
            log.info("kafka-producer-type is not specified, defaulting to sync");

            optionalKafkaProducerType = Optional.of("sync");
        } else if (!optionalKafkaProducerType.get().equals("sync")
                && !optionalKafkaProducerType.get().equals("async")) {
            log.warn("kafka-producer-type is not one of the accepted sync | async values, defaulting to sync");

            optionalKafkaProducerType = Optional.of("sync");
        }
    }

    log.info("destination (topic or queue): {}", Consts.DESTINATION_NAME);
    log.info("host: {}", host);
    log.info("port: {}", port);
    log.info("broker-type: {}", brokerType);
    log.info("benchmark-type: {}", benchmarkType);
    log.info("durable: {}", durable);
    log.info("num-consumers: {}", numConsumers);
    log.info("num-producers: {}", numProducers);
    log.info("total-number-of-messages: {}", totalNumberOfMessages);
    log.info("msg-size-in-kb: {}", msgSizeInKB);

    if (brokerType == BrokerType.KAFKA) {
        log.info("zookeeper: {}", optionalZookeeper.get());
        log.info("kafka-producer-type: {}", optionalKafkaProducerType.get());
    }

    LaunchRocket.start(brokerType, benchmarkType, durable, host, port, numConsumers, numProducers,
            totalNumberOfMessages, msgSizeInKB, optionalZookeeper, optionalKafkaProducerType);

    System.exit(0);
}

From source file:ms1quant.MS1Quant.java

/**
 * @param args the command line arguments MS1Quant parameterfile
 *///  w  ww  . jav a  2 s.com
public static void main(String[] args) throws Exception {

    BufferedReader reader = null;
    try {
        System.out.println(
                "=================================================================================================");
        System.out.println("Umpire MS1 quantification and feature detection analysis (version: "
                + UmpireInfo.GetInstance().Version + ")");
        if (args.length < 3 || !args[1].startsWith("-mode")) {
            System.out
                    .println("command : java -jar -Xmx10G MS1Quant.jar ms1quant.params -mode[1 or 2] [Option]");
            System.out.println("\n-mode");
            System.out.println("\t1:Single file mode--> mzXML_file PepXML_file");
            System.out.println("\t\tEx: -mode1 file1.mzXML file1.pep.xml");
            System.out.println(
                    "\t2:Folder mode--> mzXML_Folder PepXML_Folder, all generated csv tables will be merged into a single csv file");
            System.out.println("\t\tEx: -mode2 /data/mzxml/ /data/pepxml/");
            System.out.println("\nOptions");
            System.out.println(
                    "\t-C\tNo of concurrent files to be processed (only for folder mode), Ex. -C5, default:1");
            System.out.println("\t-p\tMinimum probability, Ex. -p0.9, default:0.9");
            System.out.println("\t-ID\tDetect identified feature only");
            System.out.println("\t-O\toutput folder, Ex. -O/data/");
            return;
        }
        ConsoleLogger consoleLogger = new ConsoleLogger();
        consoleLogger.SetConsoleLogger(Level.DEBUG);
        consoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "ms1quant_debug.log");
        Logger logger = Logger.getRootLogger();
        logger.debug("Command: " + Arrays.toString(args));
        logger.info("MS1Quant version: " + UmpireInfo.GetInstance().Version);

        String parameterfile = args[0];
        logger.info("Parameter file: " + parameterfile);
        File paramfile = new File(parameterfile);
        if (!paramfile.exists()) {
            logger.error("Parameter file " + paramfile.getAbsolutePath()
                    + " cannot be found. The program will exit.");
        }

        reader = new BufferedReader(new FileReader(paramfile.getAbsolutePath()));
        String line = "";
        InstrumentParameter param = new InstrumentParameter(InstrumentParameter.InstrumentType.TOF5600);
        int NoCPUs = 2;
        int NoFile = 1;
        param.DetermineBGByID = false;
        param.EstimateBG = true;

        //<editor-fold defaultstate="collapsed" desc="Read parameter file">
        while ((line = reader.readLine()) != null) {
            if (!"".equals(line) && !line.startsWith("#")) {
                logger.info(line);
                //System.out.println(line);
                if (line.split("=").length < 2) {
                    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;
                }
                //<editor-fold defaultstate="collapsed" desc="instrument parameters">

                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);
                }
                case "SE.EndRT": {
                    param.endRT = Float.valueOf(value);
                }

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

        int mode = 1;
        if (args[1].equals("-mode2")) {
            mode = 2;
        } else if (args[1].equals("-mode1")) {
            mode = 1;
        } else {
            logger.error("-mode number not recongized. The program will exit.");
        }

        String mzXML = "";
        String pepXML = "";
        String mzXMLPath = "";
        String pepXMLPath = "";
        File mzXMLfile = null;
        File pepXMLfile = null;
        File mzXMLfolder = null;
        File pepXMLfolder = null;
        int idx = 0;
        if (mode == 1) {
            mzXML = args[2];
            logger.info("Mode1 mzXML file: " + mzXML);
            mzXMLfile = new File(mzXML);
            if (!mzXMLfile.exists()) {
                logger.error("Mode1 mzXML file " + mzXMLfile.getAbsolutePath()
                        + " cannot be found. The program will exit.");
                return;
            }
            pepXML = args[3];
            logger.info("Mode1 pepXML file: " + pepXML);
            pepXMLfile = new File(pepXML);
            if (!pepXMLfile.exists()) {
                logger.error("Mode1 pepXML file " + pepXMLfile.getAbsolutePath()
                        + " cannot be found. The program will exit.");
                return;
            }
            idx = 4;
        } else if (mode == 2) {
            mzXMLPath = args[2];
            logger.info("Mode2 mzXML folder: " + mzXMLPath);
            mzXMLfolder = new File(mzXMLPath);
            if (!mzXMLfolder.exists()) {
                logger.error("Mode2 mzXML folder " + mzXMLfolder.getAbsolutePath()
                        + " does not exist. The program will exit.");
                return;
            }
            pepXMLPath = args[3];
            logger.info("Mode2 pepXML folder: " + pepXMLPath);
            pepXMLfolder = new File(pepXMLPath);
            if (!pepXMLfolder.exists()) {
                logger.error("Mode2 pepXML folder " + pepXMLfolder.getAbsolutePath()
                        + " does not exist. The program will exit.");
                return;
            }
            idx = 4;
        }

        String outputfolder = "";
        float MinProb = 0f;
        for (int i = idx; i < args.length; i++) {
            if (args[i].startsWith("-")) {
                if (args[i].equals("-ID")) {
                    param.TargetIDOnly = true;
                    logger.info("Detect ID feature only: true");
                }
                if (args[i].startsWith("-O")) {
                    outputfolder = args[i].substring(2);
                    logger.info("Output folder: " + outputfolder);

                    File outputfile = new File(outputfolder);
                    if (!outputfolder.endsWith("\\") | outputfolder.endsWith("/")) {
                        outputfolder += "/";
                    }
                    if (!outputfile.exists()) {
                        outputfile.mkdir();
                    }
                }
                if (args[i].startsWith("-C")) {
                    try {
                        NoFile = Integer.parseInt(args[i].substring(2));
                        logger.info("No of concurrent files: " + NoFile);
                    } catch (Exception ex) {
                        logger.error(args[i]
                                + " is not a correct integer format, will process only one file at a time.");
                    }
                }
                if (args[i].startsWith("-p")) {
                    try {
                        MinProb = Float.parseFloat(args[i].substring(2));
                        logger.info("probability threshold: " + MinProb);
                    } catch (Exception ex) {
                        logger.error(args[i] + " is not a correct format, will use 0 as threshold instead.");
                    }
                }
            }
        }

        reader.close();
        TandemParam tandemparam = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
        PTMManager.GetInstance();

        if (param.TargetIDOnly) {
            param.EstimateBG = false;
            param.ApexDelta = 1.5f;
            param.NoMissedScan = 10;
            param.MiniOverlapP = 0.2f;
            param.RemoveGroupedPeaks = false;
            param.CheckMonoIsotopicApex = false;
            param.DetectByCWT = false;
            param.FillGapByBK = false;
            param.IsoCorrThreshold = -1f;
            param.SmoothFactor = 3;
        }

        if (mode == 1) {
            logger.info("Processing " + mzXMLfile.getAbsolutePath() + "....");
            long time = System.currentTimeMillis();
            LCMSPeakMS1 LCMS1 = new LCMSPeakMS1(mzXMLfile.getAbsolutePath(), NoCPUs);
            LCMS1.SetParameter(param);

            LCMS1.Resume = false;
            if (!param.TargetIDOnly) {
                LCMS1.CreatePeakFolder();
            }
            LCMS1.ExportPeakClusterTable = true;

            if (pepXMLfile.exists()) {
                tandemparam.InteractPepXMLPath = pepXMLfile.getAbsolutePath();
                LCMS1.ParsePepXML(tandemparam, MinProb);
                logger.info("No. of PSMs included: " + LCMS1.IDsummary.PSMList.size());
                logger.info("No. of Peptide ions included: " + LCMS1.IDsummary.GetPepIonList().size());
            }

            if (param.TargetIDOnly) {
                LCMS1.SaveSerializationFile = false;
            }

            if (param.TargetIDOnly || !LCMS1.ReadPeakCluster()) {
                LCMS1.PeakClusterDetection();
            }

            if (pepXMLfile.exists()) {
                LCMS1.AssignQuant(false);
                LCMS1.IDsummary.ExportPepID(outputfolder);
            }
            time = System.currentTimeMillis() - time;
            logger.info(LCMS1.ParentmzXMLName + " 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))));
            LCMS1.BaseClearAllPeaks();
            LCMS1.SetSpectrumParser(null);
            LCMS1.IDsummary = null;
            LCMS1 = null;
            System.gc();
        } else if (mode == 2) {

            LCMSID IDsummary = new LCMSID("", "", "");
            logger.info("Parsing all pepXML files in " + pepXMLPath + "....");
            for (File file : pepXMLfolder.listFiles()) {
                if (file.getName().toLowerCase().endsWith("pep.xml")
                        || file.getName().toLowerCase().endsWith("pepxml")) {
                    PepXMLParser pepXMLParser = new PepXMLParser(IDsummary, file.getAbsolutePath(), MinProb);
                }
            }
            HashMap<String, LCMSID> LCMSIDMap = IDsummary.GetLCMSIDFileMap();

            ExecutorService executorPool = null;
            executorPool = Executors.newFixedThreadPool(NoFile);

            logger.info("Processing all mzXML files in " + mzXMLPath + "....");
            for (File file : mzXMLfolder.listFiles()) {
                if (file.getName().toLowerCase().endsWith("mzxml")) {
                    LCMSID id = LCMSIDMap.get(FilenameUtils.getBaseName(file.getName()));
                    if (id == null || id.PSMList == null) {
                        logger.warn("No IDs found in :" + FilenameUtils.getBaseName(file.getName())
                                + ". Quantification for this file is skipped");
                        continue;
                    }
                    if (!id.PSMList.isEmpty()) {
                        MS1TargetQuantThread thread = new MS1TargetQuantThread(file, id, NoCPUs, outputfolder,
                                param);
                        executorPool.execute(thread);
                    }
                }
            }
            LCMSIDMap.clear();
            LCMSIDMap = null;
            IDsummary = null;
            executorPool.shutdown();
            try {
                executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
            } catch (InterruptedException e) {
                logger.info("interrupted..");
            }

            if (outputfolder == null | outputfolder.equals("")) {
                outputfolder = mzXMLPath;
            }

            logger.info("Merging PSM files..");
            File output = new File(outputfolder);
            FileWriter writer = new FileWriter(output.getAbsolutePath() + "/PSM_merge.csv");
            boolean header = false;
            for (File csvfile : output.listFiles()) {
                if (csvfile.getName().toLowerCase().endsWith("_psms.csv")) {
                    BufferedReader outreader = new BufferedReader(new FileReader(csvfile));
                    String outline = outreader.readLine();
                    if (!header) {
                        writer.write(outline + "\n");
                        header = true;
                    }
                    while ((outline = outreader.readLine()) != null) {
                        writer.write(outline + "\n");
                    }
                    outreader.close();
                    csvfile.delete();
                }
            }
            writer.close();
        }
        logger.info("MS1 quant module is complete.");
    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        throw e;
    }
}

From source file:net.bican.wordpress.Main.java

/**
 * @param args execute with "-?" for an explanation of args
 * @throws ParseException When the command line options cannot be parsed
 *//*from  w  w w  . j av  a 2s. c o  m*/
public static void main(String[] args) throws ParseException {
    try {
        Options options = new Options();
        options.addOption("?", "help", false, "Print usage information");
        options.addOption("h", "url", true, "Specify the url to xmlrpc.php");
        options.addOption("u", "user", true, "User name");
        options.addOption("p", "pass", true, "Password");
        options.addOption("a", "authors", false, "Get author list");
        options.addOption("s", "slug", true, "Slug for categories");
        options.addOption("pi", "parentid", true, "Parent id for categories");
        options.addOption("oi", "postid", true, "Post id for pages and posts");
        options.addOption("c", "categories", false, "Get category list");
        options.addOption("cn", "newcategory", true, "New category (uses --slug and --parentid)");
        options.addOption("pg", "pages", false, "Get page list (full)");
        options.addOption("pl", "pagelist", false, "Get page list");
        options.addOption("ps", "page", true, "Get page");
        options.addOption("pn", "newpage", true, "New page from file <arg> (needs --publish)");
        options.addOption("pe", "editpage", true, "Edit page (needs --postid and --publish");
        options.addOption("pd", "deletepage", true, "Delete page (needs --publish)");
        options.addOption("l", "publish", true, "Publish status for \"new\" options");
        options.addOption("us", "userinfo", false, "Get user information");
        options.addOption("or", "recentposts", true, "Get recent posts");
        options.addOption("os", "getpost", true, "Get post");
        options.addOption("on", "newpost", true, "New post from file <arg> (needs --publish)");
        options.addOption("oe", "editpost", true, "Edit post (needs --postid and --publish");
        options.addOption("od", "deletepost", true, "Delete post (needs --publish)");
        options.addOption("sm", "supportedmethods", false, "List supported methods");
        options.addOption("st", "supportedfilters", false, "List supported text filters");
        options.addOption("mn", "newmedia", true, "New media file (uses --overwrite)");
        options.addOption("ov", "overwrite", false, "Allow overwrite in uploading new media");
        options.addOption("so", "supportedstatus", false, "Print supported page and post status values");
        options.addOption("cs", "commentstatus", false, "Print comment status names for the blog");
        options.addOption("cc", "commentcount", true, "Get comment count for a post (-1 for all posts)");
        options.addOption("ca", "newcomment", true, "New comment from file");
        options.addOption("cd", "deletecomment", true, "Delete comment");
        options.addOption("ce", "editcomment", true, "Edit comment from file");
        options.addOption("cg", "getcomment", true, "Get comment");
        options.addOption("ct", "getcomments", true, "Get comments for the post");
        options.addOption("cs", "commentstatus", true, "Comment status (for --getcomments)");
        options.addOption("co", "commentoffset", true, "Comment offset # (for --getcomments)");
        options.addOption("cm", "commentnumber", true, "Comment # (for --getcomments)");
        try {
            WpCliConfiguration config = new WpCliConfiguration(args, options, Main.class);
            if (config.hasOption("help")) {
                showHelp(options);
            } else if ((!config.hasOption("url")) || (!config.hasOption("user"))
                    || (!config.hasOption("pass"))) {
                System.err.println("Specify --user, --pass and --url");
            } else {
                try {
                    Wordpress wp = new Wordpress(config.getOptionValue("user"), config.getOptionValue("pass"),
                            config.getOptionValue("url"));
                    if (config.hasOption("authors")) {
                        printList(wp.getAuthors(), Author.class, true);
                    } else if (config.hasOption("categories")) {
                        printList(wp.getCategories(), Category.class, true);
                    } else if (config.hasOption("newcategory")) {
                        String slug = config.getOptionValue("slug");
                        Integer parentId = getInteger("parentid", config);
                        if (slug == null)
                            slug = "";
                        if (parentId == null)
                            parentId = 0;
                        System.out
                                .println(wp.newCategory(config.getOptionValue("newcategory"), slug, parentId));
                    } else if (config.hasOption("pages")) {
                        printList(wp.getPages(), Page.class, false);
                    } else if (config.hasOption("pagelist")) {
                        printList(wp.getPageList(), PageDefinition.class, false);
                    } else if (config.hasOption("page")) {
                        printItem(wp.getPage(getInteger("page", config)), Page.class);
                    } else if (config.hasOption("userinfo")) {
                        printItem(wp.getUserInfo(), User.class);
                    } else if (config.hasOption("recentposts")) {
                        printList(wp.getRecentPosts(getInteger("recentposts", config)), Page.class, false);
                    } else if (config.hasOption("getpost")) {
                        printItem(wp.getPost(getInteger("getpost", config)), Page.class);
                    } else if (config.hasOption("supportedmethods")) {
                        printList(wp.supportedMethods(), String.class, false);
                    } else if (config.hasOption("supportedfilters")) {
                        printList(wp.supportedTextFilters(), String.class, false);
                    } else if (config.hasOption("newpage")) {
                        if (!config.hasOption("publish")) {
                            showHelp(options);
                        } else {
                            System.out.println(
                                    wp.newPage(Page.fromFile(new File(config.getOptionValue("newpage"))),
                                            config.getOptionValue("publish")));
                        }
                    } else if (config.hasOption("editpage")) {
                        edit(options, config, wp, "editpage", true);
                    } else if (config.hasOption("editpost")) {
                        edit(options, config, wp, "editpost", false);
                    } else if (config.hasOption("deletepage")) {
                        delete(options, config, wp, "deletepage", true);
                    } else if (config.hasOption("deletepost")) {
                        delete(options, config, wp, "deletepost", false);
                    } else if (config.hasOption("newpost")) {
                        if (!config.hasOption("publish")) {
                            showHelp(options);
                        } else {
                            System.out.println(
                                    wp.newPost(Page.fromFile(new File(config.getOptionValue("newpost"))),
                                            Boolean.valueOf(config.getOptionValue("publish"))));
                        }
                    } else if (config.hasOption("newmedia")) {
                        String fileName = config.getOptionValue("newmedia");
                        File file = new File(fileName);
                        String mimeType = new MimetypesFileTypeMap().getContentType(file);
                        Boolean overwrite = Boolean.FALSE;
                        if (config.hasOption("overwrite"))
                            overwrite = Boolean.TRUE;
                        MediaObject result = wp.newMediaObject(mimeType, file, overwrite);
                        if (result != null) {
                            System.out.println(result);
                        }
                    } else if (config.hasOption("supportedstatus")) {
                        System.out.println("Recognized status values for posts:");
                        printList(wp.getPostStatusList(), PostAndPageStatus.class, true);
                        System.out.println("\nRecognized status values for pages:");
                        printList(wp.getPageStatusList(), PostAndPageStatus.class, true);
                    } else if (config.hasOption("commentstatus")) {
                        showCommentStatus(wp);
                    } else if (config.hasOption("commentcount")) {
                        showCommentCount(config, wp);
                    } else if (config.hasOption("newcomment")) {
                        editComment(wp, config.getOptionValue("newcomment"), "newcomment");
                    } else if (config.hasOption("editcomment")) {
                        editComment(wp, config.getOptionValue("editcomment"), "editcomment");
                    } else if (config.hasOption("deletecomment")) {
                        System.err.println(Integer.valueOf(config.getOptionValue("deletecomment")));
                        deleteComment(wp, Integer.valueOf(config.getOptionValue("deletecomment")));
                    } else if (config.hasOption("getcomment")) {
                        printComment(wp, Integer.valueOf(config.getOptionValue("getcomment")));
                    } else if (config.hasOption("getcomments")) {
                        Integer postID = Integer.valueOf(config.getOptionValue("getcomments"));
                        String commentStatus = config.getOptionValue("commentstatus");
                        Integer commentOffset;
                        try {
                            commentOffset = Integer.valueOf(config.getOptionValue("commentoffset"));
                        } catch (NumberFormatException e) {
                            commentOffset = null;
                        }
                        Integer commentNumber;
                        try {
                            commentNumber = Integer.valueOf(config.getOptionValue("commentnumber"));
                        } catch (Exception e) {
                            commentNumber = null;
                        }
                        printComments(wp, postID, commentStatus, commentOffset, commentNumber);
                    } else {
                        showHelp(options);
                    }
                } catch (MalformedURLException e) {
                    System.err.println("URL \"" + config.getOptionValue("url") + "\" is invalid, reason is: "
                            + e.getLocalizedMessage());
                } catch (IOException e) {
                    System.err.println("Can't read from file, reason is: " + e.getLocalizedMessage());
                } catch (InvalidPostFormatException e) {
                    System.err.println("Input format is invalid.");
                }
            }
        } catch (ParseException e) {
            System.err.println("Can't process command line arguments, reason is: " + e.getLocalizedMessage());
        }
    } catch (XmlRpcFault e) {
        String reason = e.getLocalizedMessage();
        System.err.println("Operation failed, reason is: " + reason);
    }
}

From source file:Main.java

public static final boolean objectToBoolean(Object o) {
    return o != null ? Boolean.valueOf(o.toString()).booleanValue() : false;
}

From source file:Main.java

private static boolean transformToBoolean(String v) {
    return Boolean.valueOf(v);
}

From source file:Main.java

public static boolean getBooleanValue(Object o, boolean defaultVal) {
    if (o == null)
        return Boolean.valueOf(defaultVal);
    if (o.toString().trim().length() == 0)
        return Boolean.valueOf(defaultVal);
    if (o instanceof Boolean)
        return (Boolean) o;
    if (o instanceof String)
        return Boolean.parseBoolean((String) o);

    return Boolean.valueOf(defaultVal);
}