Example usage for java.io BufferedReader BufferedReader

List of usage examples for java.io BufferedReader BufferedReader

Introduction

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

Prototype

public BufferedReader(Reader in) 

Source Link

Document

Creates a buffering character-input stream that uses a default-sized input buffer.

Usage

From source file:com.genentech.chemistry.openEye.apps.SDFMCSSSphereExclusion.java

public static void main(String... args) throws IOException {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//ww w .  j  a  va  2s  . c  om
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp();
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    // the only reason not to match centroids in reverse order id if
    // a non-centroid is to be assigned to multiple centroids
    boolean printSphereMatchCount = cmd.hasOption("printSphereMatchCount");
    boolean reverseMatch = !cmd.hasOption("checkSpheresInOrder") && !printSphereMatchCount;
    boolean printAll = cmd.hasOption("printAll") || printSphereMatchCount;
    double radius = Double.parseDouble(cmd.getOptionValue("radius"));
    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String refFile = cmd.getOptionValue("ref");

    SimComparatorFactory<OEMolBase, OEMolBase, SimComparator<OEMolBase>> compFact;
    compFact = getComparatorFactory(cmd);

    SphereExclusion<OEMolBase, SimComparator<OEMolBase>> alg = new SphereExclusion<OEMolBase, SimComparator<OEMolBase>>(
            compFact, refFile, outFile, radius, reverseMatch, printSphereMatchCount, printAll);
    alg.run(inFile);
    alg.close();
}

From source file:edu.mit.fss.examples.TDRSSFederate.java

/**
 * The main method. This configures the Orekit data path, creates the
 * SaudiComsat federate objects and launches the associated graphical user
 * interface./* ww  w.  ja  v a 2  s .  co  m*/
 *
 * @param args the arguments
 * @throws RTIexception the RTI exception
 * @throws URISyntaxException 
 */
public static void main(String[] args) throws RTIexception, URISyntaxException {
    BasicConfigurator.configure();

    logger.debug("Setting Orekit data path.");
    System.setProperty(DataProvidersManager.OREKIT_DATA_PATH,
            new File(TDRSSFederate.class.getResource("/orekit-data.zip").toURI()).getAbsolutePath());

    logger.trace("Creating federate instance.");
    final TDRSSFederate federate = new TDRSSFederate();

    logger.trace("Setting minimum step duration and time step.");
    long timeStep = 60 * 1000, minimumStepDuration = 100;
    federate.setMinimumStepDuration(minimumStepDuration);
    federate.setTimeStep(timeStep);

    logger.debug("Loading TLE data from file.");
    final List<Component> panels = new ArrayList<Component>();
    for (String satName : Arrays.asList("TDRS 3", "TDRS 5", "TDRS 6", "TDRS 7", "TDRS 8", "TDRS 9", "TDRS 10",
            "TDRS 11")) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    federate.getClass().getClassLoader().getResourceAsStream("edu/mit/fss/examples/data.tle")));

            while (br.ready()) {
                if (br.readLine().matches(".*" + satName + ".*")) {
                    logger.debug("Found " + satName + " data.");

                    logger.trace("Adding " + satName + " supplier space system.");
                    SpaceSystem system = new SpaceSystem(satName, new TLE(br.readLine(), br.readLine()),
                            5123e3);
                    federate.addObject(system);

                    panels.add(new SpaceSystemPanel(federate, system));

                    try {
                        logger.trace("Setting inital time.");
                        federate.setInitialTime(system.getInitialState().getDate()
                                .toDate(TimeScalesFactory.getUTC()).getTime());
                    } catch (IllegalArgumentException | OrekitException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                    break;
                }
            }
            br.close();
        } catch (IllegalArgumentException | OrekitException | IOException e) {
            e.printStackTrace();
            logger.fatal(e);
        }
    }

    try {
        logger.trace("Adding WSGT ground station.");
        SurfaceSystem wsgt = new SurfaceSystem("WSGT",
                new GeodeticPoint(FastMath.toRadians(32.5007), FastMath.toRadians(-106.6086), 1474),
                new AbsoluteDate(), 5123e3, 5);
        federate.addObject(wsgt);
        panels.add(new SurfaceSystemPanel(federate, wsgt));

        logger.trace("Adding STGT ground station.");
        SurfaceSystem stgt = new SurfaceSystem("STGT",
                new GeodeticPoint(FastMath.toRadians(32.5430), FastMath.toRadians(-106.6120), 1468),
                new AbsoluteDate(), 5123e3, 5);
        federate.addObject(stgt);
        panels.add(new SurfaceSystemPanel(federate, stgt));

        logger.trace("Adding GRGT ground station.");
        SurfaceSystem grgt = new SurfaceSystem("GRGT",
                new GeodeticPoint(FastMath.toRadians(13.6148), FastMath.toRadians(144.8565), 142),
                new AbsoluteDate(), 5123e3, 5);
        federate.addObject(grgt);
        panels.add(new SurfaceSystemPanel(federate, grgt));
    } catch (OrekitException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    logger.debug("Launching the graphical user interface.");
    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                MemberFrame frame = new MemberFrame(federate, new MultiComponentPanel(panels));
                frame.pack();
                frame.setVisible(true);
            }
        });
    } catch (InvocationTargetException | InterruptedException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    logger.trace("Setting federate name, type, and FOM path.");
    federate.getConnection().setFederateName("TDRSS");
    federate.getConnection().setFederateType("FSS Supplier");
    federate.getConnection().setFederationName("FSS");
    federate.getConnection().setFomPath(
            new File(federate.getClass().getClassLoader().getResource("edu/mit/fss/hla/fss.xml").toURI())
                    .getAbsolutePath());
    federate.getConnection().setOfflineMode(false);
    federate.connect();
}

From source file:de.citec.csra.elancsv.parser.SimpleParser.java

public static void main(String[] args) throws IOException, ParseException {

    Options opts = new Options();
    opts.addOption("file", true, "Tab-separated ELAN export file to load.");
    opts.addOption("tier", true,
            "Tier to analyze. Optional: Append ::num to interpret annotations numerically.");
    opts.addOption("format", true,
            "How to read information from the file name. %V -> participant, %A -> annoatator, %C -> condition, e.g. \"%V - %A\"");
    opts.addOption("help", false, "Print this help and exit");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(opts, args);
    if (cmd.hasOption("help")) {
        helpExit(opts, "where OPTION includes:");
    }/*from   w w w  . jav a2s  . co  m*/

    String infile = cmd.getOptionValue("file");
    if (infile == null) {
        helpExit(opts, "Error: no file given.");
    }

    String format = cmd.getOptionValue("format");
    if (format == null) {
        helpExit(opts, "Error: no format given.");
    }

    String tier = cmd.getOptionValue("tier");
    if (tier == null) {
        helpExit(opts, "Error: no tier given.");
    }

    //      TODO count values in annotations (e.g. search all robot occurrences)
    String[] tn = tier.split("::");
    boolean numeric = false;
    if (tn.length == 2 && tn[1].equals("num")) {
        numeric = true;
        tier = tn[0];
    }

    format = "^" + format + "$";
    format = format.replaceFirst("%V", "(?<V>.*?)");
    format = format.replaceFirst("%A", "(?<A>.*?)");
    format = format.replaceFirst("%C", "(?<C>.*?)");
    Pattern pa = Pattern.compile(format);

    Map<String, Participant> participants = new HashMap<>();
    BufferedReader br = new BufferedReader(new FileReader(infile));
    String line;
    int lineno = 0;
    while ((line = br.readLine()) != null) {
        String[] parts = line.split("\t");
        lineno++;
        if (parts.length < 5) {
            System.err.println("WARNING: line '" + lineno + "' too short '" + line + "'");
            continue;
        }
        Annotation a = new Annotation(Long.valueOf(parts[ElanFormat.START.field]),
                Long.valueOf(parts[ElanFormat.STOP.field]), Long.valueOf(parts[ElanFormat.DURATION.field]),
                parts[ElanFormat.VALUE.field]);
        String tname = parts[ElanFormat.TIER.field];
        String file = parts[ElanFormat.FILE.field].replaceAll(".eaf", "");

        Matcher m = pa.matcher(file);
        String vp = file;
        String condition = "?";
        String annotator = "?";
        String participantID = vp;

        if (m.find()) {
            vp = m.group("V");
            if (format.indexOf("<A>") > 0) {
                annotator = m.group("A");
            }

            if (format.indexOf("<C>") > 0) {
                condition = m.group("C");
            }
        }
        participantID = vp + ";" + annotator;

        if (!participants.containsKey(participantID)) {
            participants.put(participantID, new Participant(vp, condition, annotator));
        }
        Participant p = participants.get(participantID);

        if (!p.tiers.containsKey(tname)) {
            p.tiers.put(tname, new Tier(tname));
        }

        p.tiers.get(tname).annotations.add(a);

    }

    Map<String, Map<String, Number>> values = new HashMap<>();
    Set<String> rownames = new HashSet<>();

    String allCountKey = "c: all values";
    String allDurationKey = "d: all values";
    String allMeanKey = "m: all values";

    for (Map.Entry<String, Participant> e : participants.entrySet()) {
        //         System.out.println(e);
        Tier t = e.getValue().tiers.get(tier);
        String participantID = e.getKey();

        if (!values.containsKey(participantID)) {
            values.put(participantID, new HashMap<String, Number>());
        }
        Map<String, Number> row = values.get(participantID); //participant id

        if (t != null) {

            row.put(allCountKey, 0l);
            row.put(allDurationKey, 0l);
            row.put(allMeanKey, 0l);

            for (Annotation a : t.annotations) {

                long countAll = (long) row.get(allCountKey) + 1;
                long durationAll = (long) row.get(allDurationKey) + a.duration;
                long meanAll = durationAll / countAll;

                row.put(allCountKey, countAll);
                row.put(allDurationKey, durationAll);
                row.put(allMeanKey, meanAll);

                if (!numeric) {
                    String countKey = "c: " + a.value;
                    String durationKey = "d: " + a.value;
                    String meanKey = "m: " + a.value;

                    if (!row.containsKey(countKey)) {
                        row.put(countKey, 0l);
                    }
                    if (!row.containsKey(durationKey)) {
                        row.put(durationKey, 0l);
                    }
                    if (!row.containsKey(meanKey)) {
                        row.put(meanKey, 0d);
                    }

                    long count = (long) row.get(countKey) + 1;
                    long duration = (long) row.get(durationKey) + a.duration;
                    double mean = duration * 1.0 / count;

                    row.put(countKey, count);
                    row.put(durationKey, duration);
                    row.put(meanKey, mean);

                    rownames.add(countKey);
                    rownames.add(durationKey);
                    rownames.add(meanKey);
                } else {
                    String countKey = "c: " + t.name;
                    String sumKey = "s: " + t.name;
                    String meanKey = "m: " + t.name;

                    if (!row.containsKey(countKey)) {
                        row.put(countKey, 0l);
                    }
                    if (!row.containsKey(sumKey)) {
                        row.put(sumKey, 0d);
                    }
                    if (!row.containsKey(meanKey)) {
                        row.put(meanKey, 0d);
                    }

                    double d = 0;
                    try {
                        d = Double.valueOf(a.value);
                    } catch (NumberFormatException ex) {

                    }

                    long count = (long) row.get(countKey) + 1;
                    double sum = (double) row.get(sumKey) + d;
                    double mean = sum / count;

                    row.put(countKey, count);
                    row.put(sumKey, sum);
                    row.put(meanKey, mean);

                    rownames.add(countKey);
                    rownames.add(sumKey);
                    rownames.add(meanKey);
                }

            }
        }

    }

    ArrayList<String> list = new ArrayList(rownames);
    Collections.sort(list);
    StringBuilder header = new StringBuilder("ID;Annotator;");
    header.append(allCountKey);
    header.append(";");
    header.append(allDurationKey);
    header.append(";");
    header.append(allMeanKey);
    header.append(";");
    for (String l : list) {
        header.append(l);
        header.append(";");
    }
    System.out.println(header);

    for (Map.Entry<String, Map<String, Number>> e : values.entrySet()) {
        StringBuilder row = new StringBuilder(e.getKey());
        row.append(";");
        if (e.getValue().containsKey(allCountKey)) {
            row.append(e.getValue().get(allCountKey));
        } else {
            row.append("0");
        }
        row.append(";");
        if (e.getValue().containsKey(allDurationKey)) {
            row.append(e.getValue().get(allDurationKey));
        } else {
            row.append("0");
        }
        row.append(";");
        if (e.getValue().containsKey(allMeanKey)) {
            row.append(e.getValue().get(allMeanKey));
        } else {
            row.append("0");
        }
        row.append(";");
        for (String l : list) {
            if (e.getValue().containsKey(l)) {
                row.append(e.getValue().get(l));
            } else {
                row.append("0");
            }
            row.append(";");
        }
        System.out.println(row);
    }
}

From source file:PlyBounder.java

public static void main(String[] args) {

    // Get the commandline arguments
    Options options = new Options();
    // Available options
    Option plyPath = OptionBuilder.withArgName("dir").hasArg()
            .withDescription("directory containing input .ply files").create("plyPath");
    Option boundingbox = OptionBuilder.withArgName("string").hasArg()
            .withDescription("bounding box in WKT notation").create("boundingbox");
    Option outputPlyFile = OptionBuilder.withArgName("file").hasArg().withDescription("output PLY file name")
            .create("outputPlyFile");
    options.addOption(plyPath);/*  ww w  .j  a  v a  2  s. c  o m*/
    options.addOption(boundingbox);
    options.addOption(outputPlyFile);

    String plydir = ".";
    String boundingboxstr = "";
    String outputfilename = "";

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

        boundingboxstr = line.getOptionValue("boundingbox");
        outputfilename = line.getOptionValue("outputPlyFile");

        if (line.hasOption("plyPath")) {
            // print the value of block-size
            plydir = line.getOptionValue("plyPath");
            System.out.println("Using plyPath=" + plydir);
        } else {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("PlyBounder", options);
        }
        //System.out.println( "plyPath=" + line.getOptionValue( "plyPath" ) );
    } catch (ParseException exp) {
        System.err.println("Error getting arguments: " + exp.getMessage());
    }

    // input directory
    // Get list of files
    File dir = new File(plydir);

    //System.out.println("Getting all files in " + dir.getCanonicalPath());
    List<File> files = (List<File>) FileUtils.listFiles(dir, new String[] { "ply", "PLY" }, false);
    for (File file : files) {
        try {
            System.out.println("file=" + file.getCanonicalPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String sometempfile = "magweg.wkt";
    String s = null;

    // Loop through .ply files in directory
    for (File file : files) {
        try {
            String cmdl[] = { "./ply-tool.py", "intersection", file.getCanonicalPath(), boundingboxstr,
                    sometempfile };
            //System.out.println("Running: " + Arrays.toString(cmdl));
            Process p = Runtime.getRuntime().exec(cmdl);

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            // read the output from the command
            System.out.println("cmdout:\n");
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }

            // read any errors from the attempted command
            System.out.println("cmderr:\n");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Write new .ply file
    //ply-tool write setfile outputPlyFile
    try {
        String cmdl = "./ply-tool.py write " + sometempfile + " " + outputfilename;
        System.out.println("Running: " + cmdl);
        Process p = Runtime.getRuntime().exec(cmdl);

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

        // read the output from the command
        System.out.println("cmdout:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        // read any errors from the attempted command
        System.out.println("cmderr:\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Done
    System.out.println("Done");
}

From source file:edu.upenn.egricelab.AlignerBoost.FilterSAMAlignPE.java

public static void main(String[] args) {
    if (args.length == 0) {
        printUsage();/*ww  w  .j a  v a 2s  . c o  m*/
        return;
    }
    try {
        parseOptions(args);
    } catch (IllegalArgumentException e) {
        System.err.println("Error: " + e.getMessage());
        printUsage();
        return;
    }

    // Read in chrList, if specified
    if (chrFile != null) {
        chrFilter = new HashSet<String>();
        try {
            BufferedReader chrFilterIn = new BufferedReader(new FileReader(chrFile));
            String chr = null;
            while ((chr = chrFilterIn.readLine()) != null)
                chrFilter.add(chr);
            chrFilterIn.close();
            if (verbose > 0)
                System.err.println(
                        "Only looking at alignments on " + chrFilter.size() + " specified chromosomes");
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
            return;
        }
    }

    if (verbose > 0) {
        // Start the processMonitor
        processMonitor = new Timer();
        // Start the ProcessStatusTask
        statusTask = new ProcessStatusTask();
        // Schedule to show the status every 1 second
        processMonitor.scheduleAtFixedRate(statusTask, 0, statusFreq);
    }

    // Read in known SNP file, if specified
    if (knownSnpFile != null) {
        if (verbose > 0)
            System.err.println("Checking known SNPs from user specified VCF file");
        knownVCF = new VCFFileReader(new File(knownSnpFile));
    }

    SamReaderFactory readerFac = SamReaderFactory.makeDefault();
    SAMFileWriterFactory writerFac = new SAMFileWriterFactory();
    if (!isSilent)
        readerFac.validationStringency(ValidationStringency.LENIENT); // use LENIENT stringency
    else
        readerFac.validationStringency(ValidationStringency.SILENT); // use SILENT stringency

    SamReader in = readerFac.open(new File(inFile));
    SAMFileHeader inHeader = in.getFileHeader();
    if (inHeader.getGroupOrder() == GroupOrder.reference && inHeader.getSortOrder() == SortOrder.coordinate)
        System.err.println("Warning: Input file '" + inFile
                + "' might be sorted by coordinate and cannot be correctly processed!");

    SAMFileHeader header = inHeader.clone(); // copy the inFile header as outFile header
    // Add new programHeader
    SAMProgramRecord progRec = new SAMProgramRecord(progName);
    progRec.setProgramName(progName);
    progRec.setProgramVersion(progVer);
    progRec.setCommandLine(StringUtils.join(" ", args));
    header.addProgramRecord(progRec);
    //System.err.println(inFile + " groupOrder: " + in.getFileHeader().getGroupOrder() + " sortOrder: " + in.getFileHeader().getSortOrder());
    // reset the orders
    header.setGroupOrder(groupOrder);
    header.setSortOrder(sortOrder);

    // write SAMHeader
    String prevID = null;
    SAMRecord prevRecord = null;
    List<SAMRecord> alnList = new ArrayList<SAMRecord>();
    List<SAMRecordPair> alnPEList = null;

    // Estimate fragment length distribution by scan one-pass through the alignments
    SAMRecordIterator results = in.iterator();
    if (!NO_ESTIMATE) {
        if (verbose > 0) {
            System.err.println("Estimating insert fragment size distribution ...");
            statusTask.reset();
            statusTask.setInfo("alignments scanned");
        }
        long N = 0;
        double fragL_S = 0; // fragLen sum
        double fragL_SS = 0; // fragLen^2 sum
        while (results.hasNext()) {
            SAMRecord record = results.next();
            if (verbose > 0)
                statusTask.updateStatus();
            if (record.getFirstOfPairFlag() && !record.isSecondaryOrSupplementary()) {
                double fragLen = Math.abs(record.getInferredInsertSize());
                if (fragLen != 0 && fragLen >= MIN_FRAG_LEN && fragLen <= MAX_FRAG_LEN) { // only consider certain alignments
                    N++;
                    fragL_S += fragLen;
                    fragL_SS += fragLen * fragLen;
                }
                // stop estimate if already enough
                if (MAX_ESTIMATE_SCAN > 0 && N >= MAX_ESTIMATE_SCAN)
                    break;
            }
        }
        if (verbose > 0)
            statusTask.finish();
        // estimate fragment size
        if (N >= MIN_ESTIMATE_BASE) { // override command line values
            MEAN_FRAG_LEN = fragL_S / N;
            SD_FRAG_LEN = Math.sqrt((N * fragL_SS - fragL_S * fragL_S) / (N * (N - 1)));
            String estStr = String.format("Estimated fragment size distribution: N(%.1f, %.1f)", MEAN_FRAG_LEN,
                    SD_FRAG_LEN);
            if (verbose > 0)
                System.err.println(estStr);
            // also add the estimation to comment
            header.addComment(estStr);
        } else {
            System.err.println(
                    "Unable to estimate the fragment size distribution due to too few observed alignments");
            System.err.println(
                    "You have to specify the '--mean-frag-len' and '--sd-frag-len' on the command line and re-run this step");
            statusTask.cancel();
            processMonitor.cancel();
            return;
        }
        // Initiate the normal model
        normModel = new NormalDistribution(MEAN_FRAG_LEN, SD_FRAG_LEN);
        // reset the iterator, if necessary
        if (in.type() == SamReader.Type.SAM_TYPE) {
            try {
                in.close();
            } catch (IOException e) {
                System.err.println(e.getMessage());
            }
            in = readerFac.open(new File(inFile));
        }
        results.close();
        results = in.iterator();
    } // end of NO_ESTIMATE

    SAMFileWriter out = OUT_IS_SAM ? writerFac.makeSAMWriter(header, false, new File(outFile))
            : writerFac.makeBAMWriter(header, false, new File(outFile));

    // check each alignment again
    if (verbose > 0) {
        System.err.println("Filtering alignments ...");
        statusTask.reset();
        statusTask.setInfo("alignments processed");
    }
    while (results.hasNext()) {
        SAMRecord record = results.next();
        if (verbose > 0)
            statusTask.updateStatus();
        String ID = record.getReadName();
        // fix read and quality string for this read, if is a secondary hit from multiple hits, used for BWA alignment
        if (ID.equals(prevID) && record.getReadLength() == 0)
            SAMAlignFixer.fixSAMRecordRead(record, prevRecord);
        if (chrFilter != null && !chrFilter.contains(record.getReferenceName())) {
            prevID = ID;
            prevRecord = record;
            continue;
        }

        // fix MD:Z string for certain aligners with invalid format (i.e. seqAlto)
        if (fixMD)
            SAMAlignFixer.fixMisStr(record);

        // fix alignment, ignore if failed (unmapped or empty)
        if (!SAMAlignFixer.fixSAMRecord(record, knownVCF, DO_1DP)) {
            prevID = ID;
            prevRecord = record;
            continue;
        }
        if (!record.getReadPairedFlag()) {
            System.err.println("Error: alignment is not from a paired-end read at\n" + record.getSAMString());
            out.close();
            statusTask.cancel();
            processMonitor.cancel();
            return;
        }

        if (!ID.equals(prevID) && prevID != null || !results.hasNext()) { // a non-first new ID meet, or end of alignments
            // create alnPEList from filtered alnList
            alnPEList = createAlnPEListFromAlnList(alnList);
            //System.err.printf("%d alignments for %s transformed to %d alnPairs%n", alnList.size(), prevID, alnPEList.size());
            int totalPair = alnPEList.size();
            // filter highly unlikely PEhits
            filterPEHits(alnPEList, MIN_ALIGN_RATE, MIN_IDENTITY);
            // calculate posterior mapQ for each pair
            calcPEHitPostP(alnPEList, totalPair, MAX_HIT);
            // filter hits by mapQ
            if (MIN_MAPQ > 0)
                filterPEHits(alnPEList, MIN_MAPQ);

            // sort the list first with an anonymous class of comparator, with DESCREASING order
            Collections.sort(alnPEList, Collections.reverseOrder());
            // control max-best
            if (MAX_BEST != 0 && alnPEList.size() > MAX_BEST) { // potential too much best hits
                int nBestStratum = 0;
                int bestMapQ = alnPEList.get(0).getPEMapQ(); // best mapQ from first PE
                for (SAMRecordPair pr : alnPEList)
                    if (pr.getPEMapQ() == bestMapQ)
                        nBestStratum++;
                    else
                        break; // stop searching for sorted list
                if (nBestStratum > MAX_BEST)
                    alnPEList.clear();
            }
            // filter alignments with auxiliary filters
            if (!MAX_SENSITIVITY)
                filterPEHits(alnPEList, MAX_SEED_MIS, MAX_SEED_INDEL, MAX_ALL_MIS, MAX_ALL_INDEL);

            // report remaining secondary alignments, up-to MAX_REPORT
            for (int i = 0; i < alnPEList.size() && (MAX_REPORT == 0 || i < MAX_REPORT); i++) {
                SAMRecordPair repPair = alnPEList.get(i);
                if (doUpdateBit)
                    repPair.setNotPrimaryAlignmentFlags(i != 0);
                int nReport = MAX_REPORT == 0 ? Math.min(alnPEList.size(), MAX_REPORT) : alnPEList.size();
                int nFiltered = alnPEList.size();
                if (repPair.fwdRecord != null) {
                    repPair.fwdRecord.setAttribute("NH", nReport);
                    repPair.fwdRecord.setAttribute("XN", nFiltered);
                    out.addAlignment(repPair.fwdRecord);
                }
                if (repPair.revRecord != null) {
                    repPair.revRecord.setAttribute("NH", nReport);
                    repPair.revRecord.setAttribute("XN", nFiltered);
                    out.addAlignment(repPair.revRecord);
                }
            }
            // reset list
            alnList.clear();
            alnPEList.clear();
        }
        // update
        if (!ID.equals(prevID)) {
            prevID = ID;
            prevRecord = record;
        }
        alnList.add(record);
    } // end while
    try {
        in.close();
        out.close();
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
    // Terminate the monitor task and monitor
    if (verbose > 0) {
        statusTask.cancel();
        statusTask.finish();
        processMonitor.cancel();
    }
}

From source file:com.cyberway.issue.net.PublicSuffixes.java

/**
 * Utility method for dumping a regex String, based on a published public
 * suffix list, which matches any SURT-form hostname up through the broadest
 * 'private' (assigned/sold) domain-segment. That is, for any of the
 * SURT-form hostnames...//w w  w . j  a  v  a2s.c o  m
 * 
 * com,example, com,example,www, com,example,california,www
 * 
 * ...the regex will match 'com,example,'.
 * 
 * @param args
 * @throws IOException
 */
public static void main(String args[]) throws IOException {

    String regex;

    if (args.length == 0 || "=".equals(args[0])) {
        // use bundled list
        regex = getTopmostAssignedSurtPrefixRegex();
    } else {
        // use specified filename
        BufferedReader reader = new BufferedReader(new FileReader(args[0]));
        regex = getTopmostAssignedSurtPrefixRegex(reader);
        IOUtils.closeQuietly(reader);
    }

    boolean needsClose = false;
    BufferedWriter writer;
    if (args.length >= 2) {
        // writer to specified file
        writer = new BufferedWriter(new FileWriter(args[1]));
        needsClose = true;
    } else {
        // write to stdout
        writer = new BufferedWriter(new OutputStreamWriter(System.out));
    }
    writer.append(regex);
    writer.flush();
    if (needsClose) {
        writer.close();
    }
}

From source file:de.binfalse.jatter.App.java

/**
 * Run jatter's main./*from w w w .  j  a  va 2  s  .  co m*/
 *
 * @param args
 *          the arguments
 * @throws Exception
 *           the exception
 */
public static void main(String[] args) throws Exception {
    Options options = new Options();

    Option conf = new Option("c", "config", true, "config file path");
    conf.setRequired(false);
    options.addOption(conf);

    Option t = new Option("t", "template", false, "show a config template");
    t.setRequired(false);
    options.addOption(t);

    Option v = new Option("v", "verbose", false, "print information messages");
    v.setRequired(false);
    options.addOption(v);

    Option d = new Option("d", "debug", false, "print debugging messages incl stack traces");
    d.setRequired(false);
    options.addOption(d);

    Option h = new Option("h", "help", false, "show help");
    h.setRequired(false);
    options.addOption(h);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h"))
            throw new RuntimeException("showing the help page");
    } catch (Exception e) {
        help(options, e.getMessage());
        return;
    }

    if (cmd.hasOption("t")) {
        System.out.println();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                App.class.getClassLoader().getResourceAsStream("config.properties.template")));
        while (br.ready())
            System.out.println(br.readLine());
        br.close();
        System.exit(0);
    }

    if (cmd.hasOption("v"))
        LOGGER.setMinLevel(LOGGER.INFO);

    if (cmd.hasOption("d")) {
        LOGGER.setMinLevel(LOGGER.DEBUG);
        LOGGER.setLogStackTrace(true);
    }

    if (!cmd.hasOption("c"))
        help(options, "a config file is required for running jatter");

    startJatter(cmd.getOptionValue("c"));
}

From source file:com.interacciones.mxcashmarketdata.driver.client.DriverClient.java

public static void main(String[] args) throws Throwable {
    init(args);/*from   w  w  w.  j a  v a  2  s . c o  m*/

    NioSocketConnector connector = new NioSocketConnector();

    // Configure the service.
    connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
    if (USE_CUSTOM_CODEC) {
        connector.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(new SumUpProtocolCodecFactory(false)));
    } else {
        connector.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
    }
    int[] values = new int[] {};
    connector.getFilterChain().addLast("logger", new LoggingFilter());
    connector.setHandler(new ClientSessionHandler(values));

    long time = System.currentTimeMillis();
    IoSession session;
    for (;;) {
        try {
            System.out.println(host + " " + port + " " + fileTest);
            ConnectFuture future = connector.connect(new InetSocketAddress(host, port));
            future.awaitUninterruptibly();
            session = future.getSession();

            File file = new File(fileTest);
            FileInputStream is = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            int data = br.read();
            int count = 0;

            IoBuffer ib = IoBuffer.allocate(274);
            ib.setAutoExpand(true);
            boolean flagcount = false;

            while (data != -1) {
                data = br.read();
                ib.put((byte) data);

                if (flagcount) {
                    count++;
                }
                if (data == 13) {
                    count = 1;
                    flagcount = true;
                    LOGGER.debug(ib.toString());
                }
                if (count == 4) {
                    ib.flip();
                    session.write(ib);
                    ib = IoBuffer.allocate(274);
                    ib.setAutoExpand(true);
                    flagcount = false;
                    count = 0;
                    //Thread.sleep(500);
                }
            }

            break;
        } catch (RuntimeIoException e) {
            LOGGER.error("Failed to connect.");
            e.printStackTrace();
            Thread.sleep(5000);
        }
    }
    time = System.currentTimeMillis() - time;
    LOGGER.info("Time " + time);
    // wait until the summation is done
    session.getCloseFuture().awaitUninterruptibly();
    connector.dispose();
}

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  av a  2 s .  co  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:smtpsend.java

/**
 * Example of how to extend the SMTPTransport class.
 * This example illustrates how to issue the XACT
 * command before the SMTPTransport issues the DATA
 * command./*  w ww . j a v  a  2s .c o  m*/
 *
public static class SMTPExtension extends SMTPTransport {
public SMTPExtension(Session session, URLName url) {
   super(session, url);
   // to check that we're being used
   System.out.println("SMTPExtension: constructed");
}
        
protected synchronized OutputStream data() throws MessagingException {
   if (supportsExtension("XACCOUNTING"))
  issueCommand("XACT", 250);
   return super.data();
}
}
 */

public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;
    String mailer = "smtpsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    boolean verbose = false;
    boolean auth = false;
    String prot = "smtp";
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    /*
     * Process command line arguments.
     */
    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-a")) {
            file = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-A")) {
            auth = true;
        } else if (argv[optind].equals("-S")) {
            prot = "smtps";
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]");
            System.out.println("\t[-v] [-A] [-S] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        /*
         * Prompt for To and Subject, if not specified.
         */
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        /*
         * Initialize the JavaMail Session.
         */
        Properties props = System.getProperties();
        if (mailhost != null)
            props.put("mail." + prot + ".host", mailhost);
        if (auth)
            props.put("mail." + prot + ".auth", "true");

        /*
         * Create a Provider representing our extended SMTP transport
         * and set the property to use our provider.
         *
        Provider p = new Provider(Provider.Type.TRANSPORT, prot,
        "smtpsend$SMTPExtension", "JavaMail demo", "no version");
        props.put("mail." + prot + ".class", "smtpsend$SMTPExtension");
         */

        // Get a Session object
        Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);

        /*
         * Register our extended SMTP transport.
         *
        session.addProvider(p);
         */

        /*
         * Construct the message and send it.
         */
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        String text = collect(in);

        if (file != null) {
            // Attach the specified file.
            // We need a multipart message to hold the attachment.
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(text);
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.attachFile(file);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
            msg.setContent(mp);
        } else {
            // If the desired charset is known, you can use
            // setText(text, charset)
            msg.setText(text);
        }

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        /*
         * The simple way to send a message is this:
         *
        Transport.send(msg);
         *
         * But we're going to use some SMTP-specific features for
         * demonstration purposes so we need to manage the Transport
         * object explicitly.
         */
        SMTPTransport t = (SMTPTransport) session.getTransport(prot);
        try {
            if (auth)
                t.connect(mailhost, user, password);
            else
                t.connect();
            t.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (verbose)
                System.out.println("Response: " + t.getLastServerResponse());
            t.close();
        }

        System.out.println("\nMail was sent successfully.");

        /*
         * Save a copy of the message, if requested.
         */
        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                URLName urln = new URLName(url);
                store = session.getStore(urln);
                store.connect();
            } else {
                if (protocol != null)
                    store = session.getStore(protocol);
                else
                    store = session.getStore();

                // Connect
                if (host != null || user != null || password != null)
                    store.connect(host, user, password);
                else
                    store.connect();
            }

            // Get record Folder.  Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        /*
         * Handle SMTP-specific exceptions.
         */
        if (e instanceof SendFailedException) {
            MessagingException sfe = (MessagingException) e;
            if (sfe instanceof SMTPSendFailedException) {
                SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
                System.out.println("SMTP SEND FAILED:");
                if (verbose)
                    System.out.println(ssfe.toString());
                System.out.println("  Command: " + ssfe.getCommand());
                System.out.println("  RetCode: " + ssfe.getReturnCode());
                System.out.println("  Response: " + ssfe.getMessage());
            } else {
                if (verbose)
                    System.out.println("Send failed: " + sfe.toString());
            }
            Exception ne;
            while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) {
                sfe = (MessagingException) ne;
                if (sfe instanceof SMTPAddressFailedException) {
                    SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe;
                    System.out.println("ADDRESS FAILED:");
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                } else if (sfe instanceof SMTPAddressSucceededException) {
                    System.out.println("ADDRESS SUCCEEDED:");
                    SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe;
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                }
            }
        } else {
            System.out.println("Got Exception: " + e);
            if (verbose)
                e.printStackTrace();
        }
    }
}