Example usage for java.lang String trim

List of usage examples for java.lang String trim

Introduction

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

Prototype

public String trim() 

Source Link

Document

Returns a string whose value is this string, with all leading and trailing space removed, where space is defined as any character whose codepoint is less than or equal to 'U+0020' (the space character).

Usage

From source file:com.google.gdocsfs.GoogleDocsFS.java

public static void main(String[] args) {
    ResourceBundle properties = ResourceBundle.getBundle("gdocsfs");

    String username = properties.getString("username");
    String password = properties.getString("password");
    if (password == null || password.trim().length() == 0) {
        //         char[] pass = System.console().readPassword("Google account password(%s): ", username);
        //         password = new String(pass);
        throw new UnsupportedOperationException();
    }//from  w w  w  .j av a 2s  . co m

    String mountPoint = args[0];
    String[] fuseArgs = new String[] { "-f", "-s", "-ofsname=gdocsfs", "-ouse_ino", mountPoint };
    GoogleDocs googleDocs;
    try {
        googleDocs = new GoogleDocs(username, password);
        GoogleDocsFS gdocsfs = new GoogleDocsFS(googleDocs);
        FuseMount.mount(fuseArgs, gdocsfs, log);

    } catch (AuthenticationException e) {
        error(1, e, "Unable to connect. Ckeck your username and/or password.");

    } catch (ServiceException e) {
        error(2, e, "Ckeck your Internet connection: " + e.getMessage());

    } catch (IOException e) {
        error(3, e, "Ckeck your Internet connection: " + e.getMessage());

    } catch (Exception e) {
        error(4, e, "Unable to mount at " + mountPoint, "Error: " + e.getMessage());
    }
}

From source file:com.zarkonnen.longan.Main.java

public static void main(String[] args) throws IOException {
    // Use Apache Commons CLI (packaged into the Jar) to parse command line options.
    Options options = new Options();
    Option helpO = OptionBuilder.withDescription("print help").create("h");
    Option versionO = OptionBuilder.withDescription("print version").create("v");
    Option outputO = OptionBuilder.withDescription("output file").withLongOpt("out").hasArg()
            .withArgName("file").create("o");
    Option formatO = OptionBuilder
            .withDescription("output format: one of plaintext (default) and visualize (debug output in png)")
            .hasArg().withArgName("format").withLongOpt("format").create();
    Option serverO = OptionBuilder.withDescription("launches server mode: Server mode reads "
            + "command line strings one per line exactly as above. If no output file is "
            + "specified, returns a line containing the number of output lines before the "
            + "output. If there is an error, returns a single line with the error message. "
            + "Shut down server by sending \"quit\".").withLongOpt("server").create();
    Option openCLO = OptionBuilder
            .withDescription(/*  w ww. j a v a2s  . c  o m*/
                    "enables use of the graphics card to " + "support the OCR system. Defaults to true.")
            .withLongOpt("enable-opencl").hasArg().withArgName("enabled").create();
    options.addOption(helpO);
    options.addOption(versionO);
    options.addOption(outputO);
    options.addOption(formatO);
    options.addOption(serverO);
    options.addOption(openCLO);
    CommandLineParser clp = new GnuParser();
    try {
        CommandLine line = clp.parse(options, args);
        if (line.hasOption("h")) {
            new HelpFormatter().printHelp(INVOCATION, options);
            System.exit(0);
        }
        if (line.hasOption("v")) {
            System.out.println(Longan.VERSION);
            System.exit(0);
        }
        boolean enableOpenCL = true;
        if (line.hasOption("enable-opencl")) {
            enableOpenCL = line.getOptionValue("enable-opencl").toLowerCase().equals("true")
                    || line.getOptionValue("enable-opencl").equals("1");
        }
        if (line.hasOption("server")) {
            Longan longan = Longan.getDefaultImplementation(enableOpenCL);
            BufferedReader inputR = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String input = inputR.readLine();
                if (input.trim().equals("quit")) {
                    return;
                }
                String[] args2 = splitInput(input);
                Options o2 = new Options();
                o2.addOption(outputO);
                o2.addOption(formatO);
                try {
                    line = clp.parse(o2, args2);

                    File outFile = null;
                    if (line.hasOption("o")) {
                        outFile = new File(line.getOptionValue("o"));
                    }

                    ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext"));
                    if (format != DEFAULT_FORMAT && outFile == null) {
                        System.out.println("You must specify an output file for non-plaintext output.");
                        continue;
                    }

                    if (line.getArgList().isEmpty()) {
                        System.out.println("Please specify an input image.");
                        continue;
                    }
                    if (line.getArgList().size() > 1) {
                        System.err.println("Please specify one input image at a time");
                        continue;
                    }

                    File inFile = new File((String) line.getArgList().get(0));

                    if (!inFile.exists()) {
                        System.out.println("The input image does not exist.");
                        continue;
                    }

                    try {
                        Result result = longan.process(ImageIO.read(inFile));
                        if (outFile == null) {
                            String txt = DEFAULT_FORMAT.convert(result);
                            System.out.println(numNewlines(txt) + 1);
                            System.out.print(txt);
                        } else {
                            if (outFile.getAbsoluteFile().getParentFile() != null
                                    && !outFile.getAbsoluteFile().getParentFile().exists()) {
                                outFile.getParentFile().mkdirs();
                            }
                            FileOutputStream fos = new FileOutputStream(outFile);
                            try {
                                format.write(result, fos);
                            } finally {
                                fos.close();
                            }
                        }
                    } catch (Exception e) {
                        System.out.println("Processing error: " + exception(e));
                    }
                } catch (ParseException e) {
                    System.out.println("Input not recognized: " + exception(e));
                }
            } // End server loop
        } else {
            // Single invocation
            File outFile = null;
            if (line.hasOption("o")) {
                outFile = new File(line.getOptionValue("o"));
            }

            ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext"));
            if (format != DEFAULT_FORMAT && outFile == null) {
                System.err.println("You must specify an output file for non-plaintext output.");
                System.exit(1);
            }

            if (line.getArgList().isEmpty()) {
                System.err.println("Please specify an input image.");
                new HelpFormatter().printHelp(INVOCATION, options);
                System.exit(1);
            }
            if (line.getArgList().size() > 1) {
                System.err.println("Please specify one input image only. To process multiple "
                        + "images, use server mode.");
                System.exit(1);
            }
            File inFile = new File((String) line.getArgList().get(0));

            if (!inFile.exists()) {
                System.err.println("The input image does not exist.");
                System.exit(1);
            }

            try {
                Result result = Longan.getDefaultImplementation(enableOpenCL).process(ImageIO.read(inFile));
                if (outFile == null) {
                    String txt = DEFAULT_FORMAT.convert(result);
                    System.out.print(txt);
                } else {
                    if (outFile.getAbsoluteFile().getParentFile() != null
                            && !outFile.getAbsoluteFile().getParentFile().exists()) {
                        outFile.getParentFile().mkdirs();
                    }
                    FileOutputStream fos = new FileOutputStream(outFile);
                    try {
                        format.write(format.convert(result), fos);
                    } finally {
                        fos.close();
                    }
                }
            } catch (Exception e) {
                System.err.println("Processing error: " + exception(e));
                System.exit(1);
            }
        }
    } catch (ParseException e) {
        System.err.println("Parsing command line input failed: " + exception(e));
        System.exit(1);
    }
}

From source file:fuse.okuyamafs.OkuyamaFuse.java

public static void main(String[] args) {

    String fuseArgs[] = new String[args.length - 1];
    System.arraycopy(args, 0, fuseArgs, 0, fuseArgs.length);

    ImdstDefine.valueCompresserLevel = 9;
    try {/*w w w. java2  s.com*/
        String okuyamaStr = args[args.length - 1];

        // Raid0?????????
        if (okuyamaStr.indexOf("#") != -1) {
            stripingDataBlock = true;
            okuyamaStr = okuyamaStr.substring(0, (okuyamaStr.length() - 1));
        }

        String[] masterNodeInfos = null;
        if (okuyamaStr.indexOf(",") != -1) {
            masterNodeInfos = okuyamaStr.split(",");
        } else {
            masterNodeInfos = (okuyamaStr + "," + okuyamaStr).split(",");
        }
        // 1=Memory
        // 2=okuyama
        // 3=LocalCacheOkuyama

        String[] optionParams = { "2", "true" };
        String fsystemMode = optionParams[0].trim();
        boolean singleFlg = new Boolean(optionParams[1].trim()).booleanValue();

        OkuyamaFilesystem.storageType = new Integer(fsystemMode).intValue();
        if (OkuyamaFilesystem.storageType == 1)
            OkuyamaFilesystem.blockSize = OkuyamaFilesystem.blockSize;

        CoreMapFactory.init(new Integer(fsystemMode.trim()).intValue(), masterNodeInfos, stripingDataBlock);
        FilesystemCheckDaemon loopDaemon = new FilesystemCheckDaemon(1, fuseArgs[fuseArgs.length - 1]);
        loopDaemon.start();

        if (OkuyamaFilesystem.storageType == 2) {
            FilesystemCheckDaemon bufferCheckDaemon = new FilesystemCheckDaemon(2, null);
            bufferCheckDaemon.start();
        }

        Runtime.getRuntime().addShutdownHook(new JVMShutdownSequence());
        FuseMount.mount(fuseArgs, new OkuyamaFilesystem(fsystemMode, singleFlg), log);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String url = "jdbc:odbc:technical_library";
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    String theStatement = "SELECT authid, lastname, firstname, email FROM authors ORDER BY authid";

    try {//ww w .j a v  a 2  s.  co  m
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, "guest", "guest");
        Statement queryAuthors = connection.createStatement();
        ResultSet results = queryAuthors.executeQuery(theStatement);

        String lastname, firstname, email;
        int id;
        while (results.next()) {
            id = results.getInt(1);
            lastname = results.getString(2);
            firstname = results.getString(3);
            email = results.getString(4);

            if (results.wasNull()) {
                email = "no email";
            }
            System.out.println(Integer.toString(id) + ", " + lastname.trim() + ", " + firstname.trim() + ", "
                    + email.trim());
        }
        queryAuthors.close();
    } catch (Exception e) {
        System.err.println(e);
    }
}

From source file:Main.java

/** Simple command-line based search demo. */
public static void main(String[] args) throws Exception {
    String usage = "Usage:\tjava SearchFiles [-index dir] [-field f] [-repeat n] [-queries file] [-query string] [-raw] [-paging hitsPerPage]\n\nSee http://lucene.apache.org/core/4_1_0/demo/ for details.";
    if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) {
        System.out.println(usage);
        System.exit(0);/*w  w w. j a v a 2 s. com*/
    }

    String index = "index";
    String field = "contents";
    String queries = null;
    int repeat = 0;
    boolean raw = false;
    String queryString = null;
    int hitsPerPage = 10;

    for (int i = 0; i < args.length; i++) {
        if ("-index".equals(args[i])) {
            index = args[i + 1];
            i++;
        } else if ("-field".equals(args[i])) {
            field = args[i + 1];
            i++;
        } else if ("-queries".equals(args[i])) {
            queries = args[i + 1];
            i++;
        } else if ("-query".equals(args[i])) {
            queryString = args[i + 1];
            i++;
        } else if ("-repeat".equals(args[i])) {
            repeat = Integer.parseInt(args[i + 1]);
            i++;
        } else if ("-raw".equals(args[i])) {
            raw = true;
        } else if ("-paging".equals(args[i])) {
            hitsPerPage = Integer.parseInt(args[i + 1]);
            if (hitsPerPage <= 0) {
                System.err.println("There must be at least 1 hit per page.");
                System.exit(1);
            }
            i++;
        }
    }

    IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(index)));
    IndexSearcher searcher = new IndexSearcher(reader);
    // :Post-Release-Update-Version.LUCENE_XY:
    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_4_10_0);

    BufferedReader in = null;
    if (queries != null) {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(queries), StandardCharsets.UTF_8));
    } else {
        in = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
    }
    // :Post-Release-Update-Version.LUCENE_XY:
    QueryParser parser = new QueryParser(Version.LUCENE_4_10_0, field, analyzer);
    while (true) {
        if (queries == null && queryString == null) { // prompt the user
            System.out.println("Enter query: ");
        }

        String line = queryString != null ? queryString : in.readLine();

        if (line == null || line.length() == -1) {
            break;
        }

        line = line.trim();
        if (line.length() == 0) {
            break;
        }

        Query query = parser.parse(line);
        System.out.println("Searching for: " + query.toString(field));

        if (repeat > 0) { // repeat & time as benchmark
            Date start = new Date();
            for (int i = 0; i < repeat; i++) {
                searcher.search(query, null, 100);
            }
            Date end = new Date();
            System.out.println("Time: " + (end.getTime() - start.getTime()) + "ms");
        }

        doPagingSearch(in, searcher, query, hitsPerPage, raw, queries == null && queryString == null);

        if (queryString != null) {
            break;
        }
    }
    reader.close();
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.FilterVocabulary.java

public static void main(String[] args) {
    String optKeys[] = { IN_VOC_FILE_PARAM, OUT_VOC_FILE_PARAM, CommonParams.MEM_FWD_INDEX_PARAM,
            CommonParams.MAX_WORD_QTY_PARAM };
    String optDescs[] = { IN_VOC_FILE_DESC, OUT_VOC_FILE_DESC, CommonParams.MEM_FWD_INDEX_DESC,
            CommonParams.MAX_WORD_QTY_DESC };
    boolean hasArg[] = { true, true, true, true };

    ParamHelper mParamHelper = null;//from  w w  w  . j  a  va 2 s  .c  o  m

    try {

        mParamHelper = new ParamHelper(args, optKeys, optDescs, hasArg);

        CommandLine cmd = mParamHelper.getCommandLine();

        String outputFile = cmd.getOptionValue(OUT_VOC_FILE_PARAM);
        if (null == outputFile) {
            UsageSpecify(OUT_VOC_FILE_DESC, mParamHelper.getOptions());
        }

        String inputFile = cmd.getOptionValue(IN_VOC_FILE_PARAM);
        if (null == inputFile) {
            UsageSpecify(IN_VOC_FILE_DESC, mParamHelper.getOptions());
        }

        int maxWordQty = Integer.MAX_VALUE;

        String tmpi = cmd.getOptionValue(CommonParams.MAX_WORD_QTY_PARAM);

        if (null != tmpi) {
            maxWordQty = Integer.parseInt(tmpi);
        }

        String memFwdIndxName = cmd.getOptionValue(CommonParams.MEM_FWD_INDEX_PARAM);
        if (null == memFwdIndxName) {
            UsageSpecify(CommonParams.MEM_FWD_INDEX_DESC, mParamHelper.getOptions());
        }

        VocabularyFilterAndRecoder filter = new FrequentIndexWordFilterAndRecoder(memFwdIndxName, maxWordQty);

        BufferedReader finp = new BufferedReader(
                new InputStreamReader(CompressUtils.createInputStream(inputFile)));
        BufferedWriter fout = new BufferedWriter(
                new OutputStreamWriter(CompressUtils.createOutputStream(outputFile)));
        try {

            String line;

            int wordQty = 0;
            long addedQty = 0;
            long totalQty = 0;

            for (totalQty = 0; (line = finp.readLine()) != null;) {
                ++totalQty;
                // Skip empty lines
                line = line.trim();
                if (line.isEmpty())
                    continue;

                GizaVocRec rec = new GizaVocRec(line);

                if (filter.checkWord(rec.mWord)) {
                    rec.save(fout);
                    addedQty++;
                }

                if (totalQty % REPORT_INTERVAL_QTY == 0)
                    System.out.println(String.format(
                            "Processed %d lines (%d source word entries) from '%s', added %d lines", totalQty,
                            wordQty, inputFile, addedQty));
            }

        } finally {
            finp.close();
            fout.close();
        }
    } catch (ParseException e) {
        Usage("Cannot parse arguments", mParamHelper != null ? mParamHelper.getOptions() : null);
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step5LinguisticPreprocessing.java

public static void main(String[] args) throws Exception {
    // input dir - list of xml query containers
    // step4-boiler-plate/
    File inputDir = new File(args[0]);

    // output dir
    File outputDir = new File(args[1]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();//from   w  w w  .  j a  va2 s  .c om
    }

    // iterate over query containers
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));

        for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
            //                System.out.println(rankedResults.plainText);

            if (rankedResults.plainText != null) {
                String[] lines = StringUtils.split(rankedResults.plainText, "\n");

                // collecting all cleaned lines
                List<String> cleanLines = new ArrayList<>(lines.length);
                // collecting line tags
                List<String> lineTags = new ArrayList<>(lines.length);

                for (String line : lines) {
                    // get the tag
                    String tag = null;
                    Matcher m = OPENING_TAG_PATTERN.matcher(line);

                    if (m.find()) {
                        tag = m.group(1);
                    }

                    if (tag == null) {
                        throw new IllegalArgumentException("No html tag found for line:\n" + line);
                    }

                    // replace the tag at the beginning and the end
                    String noTagText = line.replaceAll("^<\\S+>", "").replaceAll("</\\S+>$", "");

                    // do some html cleaning
                    noTagText = noTagText.replaceAll("&nbsp;", " ");

                    noTagText = noTagText.trim();

                    // add to the output
                    if (!noTagText.isEmpty()) {
                        cleanLines.add(noTagText);
                        lineTags.add(tag);
                    }
                }

                if (cleanLines.isEmpty()) {
                    // the document is empty
                    System.err.println("Document " + rankedResults.clueWebID + " in query "
                            + queryResultContainer.qID + " is empty");
                } else {
                    // now join them back to paragraphs
                    String text = StringUtils.join(cleanLines, "\n");

                    // create JCas
                    JCas jCas = JCasFactory.createJCas();
                    jCas.setDocumentText(text);
                    jCas.setDocumentLanguage("en");

                    // annotate WebParagraph
                    SimplePipeline.runPipeline(jCas,
                            AnalysisEngineFactory.createEngineDescription(WebParagraphAnnotator.class));

                    // fill the original tag information
                    List<WebParagraph> webParagraphs = new ArrayList<>(
                            JCasUtil.select(jCas, WebParagraph.class));

                    // they must be the same size as original ones
                    if (webParagraphs.size() != lineTags.size()) {
                        throw new IllegalStateException(
                                "Different size of annotated paragraphs and original lines");
                    }

                    for (int i = 0; i < webParagraphs.size(); i++) {
                        WebParagraph p = webParagraphs.get(i);
                        // get tag
                        String tag = lineTags.get(i);

                        p.setOriginalHtmlTag(tag);
                    }

                    SimplePipeline.runPipeline(jCas,
                            AnalysisEngineFactory.createEngineDescription(StanfordSegmenter.class,
                                    // only on existing WebParagraph annotations
                                    StanfordSegmenter.PARAM_ZONE_TYPES, WebParagraph.class.getCanonicalName()));

                    // now convert to XMI
                    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
                    XmiCasSerializer.serialize(jCas.getCas(), byteOutputStream);

                    // encode to base64
                    String encoded = new BASE64Encoder().encode(byteOutputStream.toByteArray());

                    rankedResults.originalXmi = encoded;
                }
            }
        }

        // and save the query to output dir
        File outputFile = new File(outputDir, queryResultContainer.qID + ".xml");
        FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8");
        System.out.println("Finished " + outputFile);
    }

}

From source file:visualizer.datamining.dataanalysis.NeighborhoodPreservation.java

public static void main(String[] args) throws IOException {
    String outfile = "precision.txt";
    String pointsfile = args[0];//from  w  w  w .jav a2  s.  co  m
    String projsfile = "projfiles.txt";

    int nrneighbors = Integer.parseInt(args[1]);

    DissimilarityType disstype = DissimilarityType.EUCLIDEAN;
    if (args[2].trim().toLowerCase().equals("cosine")) {
        disstype = DissimilarityType.COSINE_BASED;
    }

    ArrayList<String> projfiles = new ArrayList<String>();
    BufferedReader br = new BufferedReader(new FileReader(new File(projsfile)));
    String line = null;
    while ((line = br.readLine()) != null) {
        projfiles.add(line.trim());
    }

    NeighborhoodPreservationEngine npe = new NeighborhoodPreservationEngine();
    npe.neighborhoodPreservation(outfile, pointsfile, projfiles, disstype, nrneighbors);
}

From source file:com.act.lcms.v2.MZCollisionCounter.java

public static void main(String[] args) throws Exception {
    CLIUtil cliUtil = new CLIUtil(MassChargeCalculator.class, HELP_MESSAGE, OPTION_BUILDERS);
    CommandLine cl = cliUtil.parseCommandLine(args);

    File inputFile = new File(cl.getOptionValue(OPTION_INPUT_INCHI_LIST));
    if (!inputFile.exists()) {
        cliUtil.failWithMessage("Input file at does not exist at %s", inputFile.getAbsolutePath());
    }//w  w  w.  j  a v a 2 s .co  m

    List<MassChargeCalculator.MZSource> sources = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            sources.add(new MassChargeCalculator.MZSource(line));
            if (sources.size() % 1000 == 0) {
                LOGGER.info("Loaded %d sources from input file", sources.size());
            }
        }
    }

    Set<String> considerIons = Collections.emptySet();
    if (cl.hasOption(OPTION_ONLY_CONSIDER_IONS)) {
        List<String> ions = Arrays.asList(cl.getOptionValues(OPTION_ONLY_CONSIDER_IONS));
        LOGGER.info("Only considering ions for m/z calculation: %s", StringUtils.join(ions, ", "));
        considerIons = new HashSet<>(ions);
    }

    TSVWriter<String, Long> tsvWriter = new TSVWriter<>(Arrays.asList("collisions", "count"));
    tsvWriter.open(new File(cl.getOptionValue(OPTION_OUTPUT_FILE)));

    try {
        LOGGER.info("Loaded %d sources in total from input file", sources.size());

        MassChargeCalculator.MassChargeMap mzMap = MassChargeCalculator.makeMassChargeMap(sources,
                considerIons);

        if (!cl.hasOption(OPTION_COUNT_WINDOW_INTERSECTIONS)) {
            // Do an exact analysis of the m/z collisions if windowing is not specified.

            LOGGER.info("Computing precise collision histogram.");
            Iterable<Double> mzs = mzMap.ionMZIter();
            Map<Integer, Long> collisionHistogram = histogram(
                    StreamSupport.stream(mzs.spliterator(), false).map(mz -> { // See comment about Iterable below.
                        try {
                            return mzMap.ionMZToMZSources(mz).size();
                        } catch (NoSuchElementException e) {
                            LOGGER.error("Caught no such element exception for mz %f: %s", mz, e.getMessage());
                            throw e;
                        }
                    }));
            List<Integer> sortedCollisions = new ArrayList<>(collisionHistogram.keySet());
            Collections.sort(sortedCollisions);
            for (Integer collision : sortedCollisions) {
                tsvWriter.append(new HashMap<String, Long>() {
                    {
                        put("collisions", collision.longValue());
                        put("count", collisionHistogram.get(collision));
                    }
                });
            }
        } else {
            /* After some deliberation (thanks Gil!), the windowed variant of this calculation counts the number of
             * structures whose 0.01 Da m/z windows (for some set of ions) overlap with each other.
             *
             * For example, let's assume we have five total input structures, and are only searching for one ion.  Let's
             * also assume that three of those structures have m/z A and the remaining two have m/z B.  The windows might
             * look like this in the m/z domain:
             * |----A----|
             *        |----B----|
             * Because A represents three structures and overlaps with B, which represents two, we assign A a count of 5--
             * this is the number of structures we believe could fall into the range of A given our current peak calling
             * approach.  Similarly, B is assigned a count of 5, as the possibility for collision/confusion is symmetric.
             *
             * Note that this is an over-approximation of collisions, as we could more precisely only consider intersections
             * when the exact m/z of B falls within the window around A and vice versa.  However, because we have observed
             * cases where the MS sensor doesn't report structures at exactly the m/z we predict, we employ this weaker
             * definition of intersection to give a slightly pessimistic view of what confusions might be possible. */
            // Compute windows for every m/z.  We don't care about the original mz values since we just want the count.
            List<Double> mzs = mzMap.ionMZsSorted();

            final Double windowHalfWidth;
            if (cl.hasOption(OPTION_WINDOW_HALFWIDTH)) {
                // Don't use get with default for this option, as we want the exact FP value of the default tolerance.
                windowHalfWidth = Double.valueOf(cl.getOptionValue(OPTION_WINDOW_HALFWIDTH));
            } else {
                windowHalfWidth = DEFAULT_WINDOW_TOLERANCE;
            }

            /* Window = (lower bound, upper bound), counter of represented m/z's that collide with this window, and number
             * of representative structures (which will be used in counting collisions). */
            LinkedList<CollisionWindow> allWindows = new LinkedList<CollisionWindow>() {
                {
                    for (Double mz : mzs) {
                        // CPU for memory trade-off: don't re-compute the window bounds over and over and over and over and over.
                        try {
                            add(new CollisionWindow(mz, windowHalfWidth, mzMap.ionMZToMZSources(mz).size()));
                        } catch (NoSuchElementException e) {
                            LOGGER.error("Caught no such element exception for mz %f: %s", mz, e.getMessage());
                            throw e;
                        }
                    }
                }
            };

            // Sweep line time!  The window ranges are the interesting points.  We just accumulate overlap counts as we go.
            LinkedList<CollisionWindow> workingSet = new LinkedList<>();
            List<CollisionWindow> finished = new LinkedList<>();

            while (allWindows.size() > 0) {
                CollisionWindow thisWindow = allWindows.pop();
                // Remove any windows from the working set that don't overlap with the next window.
                while (workingSet.size() > 0 && workingSet.peekFirst().getMaxMZ() < thisWindow.getMinMZ()) {
                    finished.add(workingSet.pop());
                }

                for (CollisionWindow w : workingSet) {
                    /* Add the size of the new overlapping window's structure count to each of the windows in the working set,
                     * which represents the number of possible confused structures that fall within the overlapping region.
                     * We exclude the window itself as it should already have counted the colliding structures it represents. */
                    w.getAccumulator().add(thisWindow.getStructureCount());

                    /* Reciprocally, add the structure counts of all windows with which the current window overlaps to it. */
                    thisWindow.getAccumulator().add(w.getStructureCount());
                }

                // Now that accumulation is complete, we can safely add the current window.
                workingSet.add(thisWindow);
            }

            // All the interesting events are done, so drop the remaining windows into the finished set.
            finished.addAll(workingSet);

            Map<Long, Long> collisionHistogram = histogram(
                    finished.stream().map(w -> w.getAccumulator().longValue()));
            List<Long> sortedCollisions = new ArrayList<>(collisionHistogram.keySet());
            Collections.sort(sortedCollisions);
            for (Long collision : sortedCollisions) {
                tsvWriter.append(new HashMap<String, Long>() {
                    {
                        put("collisions", collision);
                        put("count", collisionHistogram.get(collision));
                    }
                });
            }
        }
    } finally {
        if (tsvWriter != null) {
            tsvWriter.close();
        }
    }
}

From source file:ch.swisscom.mid.verifier.MobileIdCmsVerifier.java

public static void main(String[] args) {

    if (args == null || args.length < 1) {
        System.out.println("Usage: ch.swisscom.mid.verifier.MobileIdCmsVerifier [OPTIONS]");
        System.out.println();//from   w  w  w .j av a  2 s .  co m
        System.out.println("Options:");
        System.out.println(
                "  -cms=VALUE or -stdin   - base64 encoded CMS/PKCS7 signature string, either as VALUE or via standard input");
        System.out.println(
                "  -jks=VALUE             - optional path to truststore file (default is 'jks/truststore.jks')");
        System.out.println("  -jkspwd=VALUE          - optional truststore password (default is 'secret')");
        System.out.println();
        System.out.println("Example:");
        System.out.println("  java ch.swisscom.mid.verifier.MobileIdCmsVerifier -cms=MIII...");
        System.out.println("  echo -n MIII... | java ch.swisscom.mid.verifier.MobileIdCmsVerifier -stdin");
        System.exit(1);
    }

    try {

        MobileIdCmsVerifier verifier = null;

        String jks = "jks/truststore.jks";
        String jkspwd = "secret";

        String param;
        for (int i = 0; i < args.length; i++) {
            param = args[i].toLowerCase();
            if (param.contains("-jks=")) {
                jks = args[i].substring(args[i].indexOf("=") + 1).trim();
            } else if (param.contains("-jkspwd=")) {
                jkspwd = args[i].substring(args[i].indexOf("=") + 1).trim();
            } else if (param.contains("-cms=")) {
                verifier = new MobileIdCmsVerifier(args[i].substring(args[i].indexOf("=") + 1).trim());
            } else if (param.contains("-stdin")) {
                BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                String stdin;
                if ((stdin = in.readLine()) != null && stdin.length() != 0)
                    verifier = new MobileIdCmsVerifier(stdin.trim());
            }
        }

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(jks), jkspwd.toCharArray());

        // If you are behind a Proxy..
        // System.setProperty("proxyHost", "10.185.32.54");
        // System.setProperty("proxyPort", "8079");
        // or set it via VM arguments: -DproxySet=true -DproxyHost=10.185.32.54 -DproxyPort=8079

        // Print Issuer/SubjectDN/SerialNumber of all x509 certificates that can be found in the CMSSignedData
        verifier.printAllX509Certificates();

        // Print Signer's X509 Certificate Details
        System.out.println("X509 SignerCert SerialNumber: " + verifier.getX509SerialNumber());
        System.out.println("X509 SignerCert Issuer: " + verifier.getX509IssuerDN());
        System.out.println("X509 SignerCert Subject DN: " + verifier.getX509SubjectDN());
        System.out.println("X509 SignerCert Validity Not Before: " + verifier.getX509NotBefore());
        System.out.println("X509 SignerCert Validity Not After: " + verifier.getX509NotAfter());
        System.out.println("X509 SignerCert Validity currently valid: " + verifier.isCertCurrentlyValid());

        System.out.println("User's unique Mobile ID SerialNumber: " + verifier.getMIDSerialNumber());

        // Print signed content (should be equal to the DTBS Message of the Signature Request)
        System.out.println("Signed Data: " + verifier.getSignedData());

        // Verify the signature on the SignerInformation object
        System.out.println("Signature Valid: " + verifier.isVerified());

        // Validate certificate path against trust anchor incl. OCSP revocation check
        System.out.println("X509 SignerCert Valid (Path+OCSP): " + verifier.isCertValid(keyStore));

    } catch (Exception e) {
        e.printStackTrace();
    }
}