Example usage for java.io File getName

List of usage examples for java.io File getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the file or directory denoted by this abstract pathname.

Usage

From source file:mzmatch.ipeak.align.CowCoda.java

@SuppressWarnings("unchecked")
public static void main(String args[]) {
    final String lbl_mcq = "mcq";

    try {/* ww  w.j a v  a 2s.com*/
        Tool.init();

        // parse the commandline options
        final Options options = new Options();
        CmdLineParser cmdline = new CmdLineParser(options);

        // check whether we need to show the help
        cmdline.parse(args);
        if (options.help) {
            Tool.printHeader(System.out, application, version);
            cmdline.printUsage(System.out, "");
            return;
        }

        if (options.verbose) {
            Tool.printHeader(System.out, application, version);
            cmdline.printOptions();
        }

        // check the command-line parameters
        int filetype = JFreeChartTools.PDF;
        {
            if (options.ppm == -1) {
                System.err.println("[ERROR]: the ppm-value needs to be set.");
                System.exit(0);
            }
            if (options.order == -1) {
                System.err.println("[ERROR]: the order for the polynomial fit needs to be set.");
                System.exit(0);
            }
            if (options.maxrt == -1) {
                System.err.println("[ERROR]: the maximum retention time shift is not set.");
                System.exit(0);
            }

            if (options.image != null) {
                String extension = options.image.substring(options.image.lastIndexOf('.') + 1);
                if (extension.toLowerCase().equals("png"))
                    filetype = JFreeChartTools.PNG;
                else if (extension.toLowerCase().equals("pdf"))
                    filetype = JFreeChartTools.PDF;
                else {
                    System.err.println(
                            "[ERROR]: file extension of the image file needs to be either PDF or PNG.");
                    System.exit(0);
                }
            }

            // if the output directories do not exist, create them
            if (options.output != null)
                Tool.createFilePath(options.output, true);
            if (options.image != null)
                Tool.createFilePath(options.image, true);
            if (options.selection != null)
                Tool.createFilePath(options.selection, true);
        }

        // load the data
        if (options.verbose)
            System.out.println("Loading the data");
        double maxrt = 0;
        Vector<ParseResult> data = new Vector<ParseResult>();
        Vector<IPeakSet<IPeak>> matchdata = new Vector<IPeakSet<IPeak>>();
        for (String file : options.input) {
            System.out.println("- " + new File(file).getName());

            // load the mass chromatogram data
            ParseResult result = PeakMLParser.parse(new FileInputStream(file), true);
            data.add(result);

            // select the best mass chromatograms
            Vector<IPeak> selection = new Vector<IPeak>();
            for (IPeak peak : (IPeakSet<IPeak>) result.measurement) {
                maxrt = Math.max(maxrt, maxRT(peak));

                double mcq = codaDW(peak);
                peak.addAnnotation(lbl_mcq, Double.toString(mcq), Annotation.ValueType.DOUBLE);
                if (mcq >= options.codadw)
                    selection.add(peak);
            }

            // keep track of the selected mass chromatograms
            int id = options.input.indexOf(file);
            IPeakSet<IPeak> peakset = new IPeakSet<IPeak>(selection);
            peakset.setMeasurementID(id);
            for (IPeak mc : peakset)
                mc.setMeasurementID(id);
            matchdata.add(peakset);
        }

        // match the selection together
        if (options.verbose)
            System.out.println("Matching the data");
        Vector<IPeakSet<IPeak>> matches = IPeak.match((Vector) matchdata, options.ppm,
                new IPeak.MatchCompare<IPeak>() {
                    public double distance(IPeak peak1, IPeak peak2) {
                        double diff = Math.abs(peak1.getRetentionTime() - peak2.getRetentionTime());
                        if (diff > options.maxrt)
                            return -1;

                        Signal signal1 = new Signal(peak1.getSignal());
                        signal1.normalize();
                        Signal signal2 = new Signal(peak2.getSignal());
                        signal2.normalize();

                        double offset = bestOffSet(peak1, peak2, options.maxrt);
                        for (int i = 0; i < signal2.getSize(); ++i)
                            signal2.getX()[i] += offset;

                        double correlation = signal2
                                .pearsonsCorrelation(signal1)[Statistical.PEARSON_CORRELATION];
                        if (correlation < 0.5)
                            return -1;

                        // the match-function optimizes toward 0 (it's a distance)
                        return 1 - correlation;
                    }
                });

        // filter out all incomplete sets
        Vector<IPeakSet<IPeak>> valids = new Vector<IPeakSet<IPeak>>();
        for (IPeakSet<IPeak> set : matches) {
            if (set.size() < options.input.size())
                continue;
            valids.add((IPeakSet) set);
        }

        // calculate the alignment factors
        if (options.verbose)
            System.out.println("Calculating the alignment factors");
        double medians[] = new double[valids.size() + 2];
        DataFrame.Double dataframe = new DataFrame.Double(valids.size() + 2, options.input.size());

        medians[0] = 0;
        medians[medians.length - 1] = maxrt;
        for (int i = 0; i < options.input.size(); ++i) {
            dataframe.set(0, i, 0.1);
            dataframe.set(dataframe.getNrRows() - 1, i, 0);
        }

        for (int matchid = 0; matchid < valids.size(); ++matchid) {
            IPeakSet<IPeak> match = valids.get(matchid);

            // find the most central
            double offsets[][] = new double[match.size()][match.size()];
            for (int i = 0; i < match.size(); ++i)
                for (int j = i + 1; j < match.size(); ++j) {
                    offsets[i][j] = bestOffSet(match.get(i), match.get(j), options.maxrt);
                    offsets[j][i] = -offsets[i][j];
                }

            int besti = 0;
            double bestabssum = Double.MAX_VALUE;
            for (int i = 0; i < match.size(); ++i) {
                double abssum = 0;
                for (int j = 0; j < match.size(); ++j)
                    abssum += Math.abs(offsets[i][j]);
                if (abssum < bestabssum) {
                    besti = i;
                    bestabssum = abssum;
                }
            }

            for (int i = 0; i < match.size(); ++i)
                dataframe.set(matchid + 1, match.get(i).getMeasurementID(),
                        (i == besti ? 0 : offsets[i][besti]));

            medians[matchid + 1] = match.get(besti).getRetentionTime();
            dataframe.setRowName(matchid, Double.toString(match.get(besti).getRetentionTime()));
        }
        double minmedian = Statistical.min(medians);
        double maxmedian = Statistical.max(medians);

        // calculate for each profile the correction function
        PolynomialFunction functions[] = new PolynomialFunction[valids.size()];
        for (int i = 0; i < options.input.size(); ++i)
            functions[i] = PolynomialFunction.fit(options.order, medians, dataframe.getCol(i));

        // make a nice plot out of the whole thing
        if (options.verbose)
            System.out.println("Writing results");
        if (options.image != null) {
            org.jfree.data.xy.XYSeriesCollection dataset = new org.jfree.data.xy.XYSeriesCollection();
            JFreeChart linechart = ChartFactory.createXYLineChart(null, "Retention Time (seconds)", "offset",
                    dataset, PlotOrientation.VERTICAL, true, // legend
                    false, // tooltips
                    false // urls
            );

            // setup the colorkey
            Colormap colormap = new Colormap(Colormap.EXCEL);

            // get the structure behind the graph
            XYPlot plot = (XYPlot) linechart.getPlot();
            XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();

            // setup the plot area
            linechart.setBackgroundPaint(java.awt.Color.WHITE);
            linechart.setBorderVisible(false);
            linechart.setAntiAlias(true);

            plot.setBackgroundPaint(java.awt.Color.WHITE);
            plot.setDomainGridlinesVisible(true);
            plot.setRangeGridlinesVisible(true);

            // create the datasets
            for (int i = 0; i < options.input.size(); ++i) {
                org.jfree.data.xy.XYSeries series = new org.jfree.data.xy.XYSeries(dataframe.getColName(i));
                org.jfree.data.xy.XYSeries function = new org.jfree.data.xy.XYSeries(
                        dataframe.getColName(i) + "-function");
                dataset.addSeries(series);
                dataset.addSeries(function);

                renderer.setSeriesPaint(dataset.getSeriesCount() - 1, new java.awt.Color(colormap.getColor(i)));
                renderer.setSeriesPaint(dataset.getSeriesCount() - 2, new java.awt.Color(colormap.getColor(i)));

                renderer.setSeriesLinesVisible(dataset.getSeriesCount() - 2, false);
                renderer.setSeriesShapesVisible(dataset.getSeriesCount() - 2, true);

                // add the data-points
                for (int j = 0; j < valids.size(); ++j)
                    series.add(medians[j], dataframe.get(j, i));
                for (double x = minmedian; x < maxmedian; ++x)
                    function.add(x, functions[i].getY(x));
            }

            dataset.removeAllSeries();
            for (int i = 0; i < options.input.size(); ++i) {
                Function function = functions[i];

                org.jfree.data.xy.XYSeries series = new org.jfree.data.xy.XYSeries(dataframe.getColName(i));
                dataset.addSeries(series);

                renderer.setSeriesPaint(i, new java.awt.Color(colormap.getColor(i)));
                renderer.setSeriesLinesVisible(i, false);
                renderer.setSeriesShapesVisible(i, true);

                // add the data-points
                for (int j = 0; j < valids.size(); ++j)
                    series.add(medians[j], dataframe.get(j, i) - function.getY(medians[j]));
            }

            JFreeChartTools.writeAs(filetype, new FileOutputStream(options.image), linechart, 800, 500);
        }

        // save the selected
        if (options.selection != null) {
            Header header = new Header();

            // set the number of peaks to be stored
            header.setNrPeaks(valids.size());

            // create a set for the measurements
            SetInfo set = new SetInfo("", SetInfo.SET);
            header.addSetInfo(set);

            // create the measurement infos
            for (int i = 0; i < options.input.size(); ++i) {
                String file = options.input.get(i);

                // create the measurement info
                MeasurementInfo measurement = new MeasurementInfo(i, data.get(i).header.getMeasurementInfo(0));
                measurement.addFileInfo(new FileInfo(file, file));

                header.addMeasurementInfo(measurement);

                // add the file to the set
                set.addChild(new SetInfo(file, SetInfo.SET, i));
            }

            // write the data
            PeakMLWriter.write(header, (Vector) valids, null,
                    new GZIPOutputStream(new FileOutputStream(options.selection)), null);
        }

        // correct the values with the found function and save them
        for (int i = 0; i < options.input.size(); ++i) {
            Function function = functions[i];
            ParseResult result = data.get(i);

            IPeakSet<MassChromatogram<Peak>> peakset = (IPeakSet<MassChromatogram<Peak>>) result.measurement;
            for (IPeak peak : peakset)
                align(peak, function);

            File filename = new File(options.input.get(i));
            String name = filename.getName();

            PeakMLWriter.write(result.header, (Vector) peakset.getPeaks(), null,
                    new GZIPOutputStream(new FileOutputStream(options.output + "/" + name)), null);
        }
    } catch (Exception e) {
        Tool.unexpectedError(e, application);
    }
}

From source file:de.tudarmstadt.ukp.csniper.resbuild.stuff.BncCheckDocuments.java

public static void main(String[] args) throws IOException {
    boolean enabled = false;

    for (File f : FileUtils.listFiles(new File(BASE), new String[] { "xml" }, true)) {
        BufferedInputStream bis = null;
        try {//from  w  ww.j  a va 2s.com
            bis = new BufferedInputStream(new FileInputStream(f));
            int c;
            StringBuilder sb = new StringBuilder();
            while ((c = bis.read()) != '>') {
                if (enabled) {
                    if (c == '"') {
                        enabled = false;
                        break;
                    } else {
                        sb.append((char) c);
                    }
                }
                if (c == '"') {
                    enabled = true;
                }
            }
            String name = f.getName().substring(0, 3);
            String id = sb.toString();
            if (!name.equals(id)) {
                System.out.println("Name is [" + name + "], but ID is [" + id + "].");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(bis);
        }
    }
}

From source file:com.interflora.ftp.SampleFTPS.java

public static final void main(String[] args) {
    boolean storeFile = true, binaryTransfer = false, error = false, listFiles = false, listNames = false,
            hidden = false;//from  w  w w.ja v  a2  s  .  co  m
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    int minParams = 5; // listings require 3 params
    String protocol = "TLS,false"; // SSL protocol
    String doCommand = null;
    String trustmgr = "all";
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    //sample : rose-misc01.hyd.ftd.untd.com rosedev test123 /TestSftp  C:/Users/skarin/Desktop/RosePaths.txt 
    //172.16.160.70 demand quevfoc5 /TestSftp C:/Users/skarin/Desktop/RosePaths.txt 
    int base = 0;
    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-b")) {
            binaryTransfer = true;
        } else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String parts[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (remain < minParams) // server, user, pass, remote, local [protocol]
    {
        System.err.println(USAGE);
        System.exit(1);
    }

    String server = args[base++];
    int port = 0;
    String parts[] = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
    }
    String username = args[base++];
    String password = args[base++];

    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }

    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }

    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String prot[] = protocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(protocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
        /* try{
         //ftps.setFileType(FTP.ASCII_FILE_TYPE);
         ftps.execPBSZ(0); // Set protection buffer size
         ftps.execPROT("C"); // Set data channel protection to private
         }catch(IOException ex ){ex.printStackTrace();};
        */
    }
    // System.out.println("After I/O Exception");

    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    ftp.setListHiddenFiles(hidden);

    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        int reply;
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            System.out.println("Trying to Connect to the server \t" + server);
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemType());

        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

        if (storeFile) {
            //InputStream input;
            File fname = new File(local);

            FileInputStream input = new FileInputStream(fname);
            String localfilename = fname.getName();
            System.out.println("Local file name " + localfilename);

            ftp.storeFile(remote + "/test/" + localfilename, input);

            input.close();
        } else if (listFiles) {
            if (lenient) {
                FTPClientConfig config = new FTPClientConfig();
                config.setLenientFutureDates(true);
                ftp.configure(config);
            }

            for (FTPFile f : ftp.listFiles(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlsd) {
            for (FTPFile f : ftp.mlistDir(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlst) {
            FTPFile f = ftp.mlistFile(remote);
            if (f != null) {
                System.out.println(f.toFormattedString());
            }
        } else if (listNames) {
            for (String s : ftp.listNames(remote)) {
                System.out.println(s);
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) { // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }

                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                    //                           Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
                //                     Command listener has already printed the output
                //                       for(String s : ftp.getReplyStrings()) {
                //                           System.out.println(s);
                //                       }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            ftp.retrieveFile(remote, output);

            output.close();
        }

        ftp.noop(); // check that control connection is working OK

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

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

public static void main(String[] args) throws Exception {
    String inputDir = args[0] + "/";
    // output dir
    File outputDir = new File(args[1]);
    File turkersConfidence = new File(args[2]);
    if (outputDir.exists()) {
        outputDir.delete();//from   w w  w  .  java2  s . com
    }
    outputDir.mkdir();

    List<String> annotatorsIDs = new ArrayList<>();
    //        for (File f : FileUtils.listFiles(new File(inputDir), new String[] { "xml" }, false)) {
    //            QueryResultContainer queryResultContainer = QueryResultContainer
    //                    .fromXML(FileUtils.readFileToString(f, "utf-8"));
    //            for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
    //                for (QueryResultContainer.MTurkRelevanceVote relevanceVote : rankedResults.mTurkRelevanceVotes) {
    //                    if (!annotatorsIDs.contains(relevanceVote.turkID))
    //                        annotatorsIDs.add(relevanceVote.turkID);
    //                }
    //            }
    //        }
    HashMap<String, Integer> countVotesForATurker = new HashMap<>();
    // creates temporary file with format for mace
    // Hashmap annotations: key is the id of a document and a sentence
    // Value is an array votes[] of turkers decisions: true or false (relevant or not)
    // the length of this array equals the number of annotators in List<String> annotatorsIDs.
    // If an annotator worked on the task his decision is written in the array otherwise the value is NULL

    // key: queryID + clueWebID + sentenceID
    // value: true and false annotations
    TreeMap<String, Annotations> annotations = new TreeMap<>();

    for (File f : FileUtils.listFiles(new File(inputDir), new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));
        System.out.println("Reading " + f.getName());
        for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
            String documentID = rankedResults.clueWebID;
            for (QueryResultContainer.MTurkRelevanceVote relevanceVote : rankedResults.mTurkRelevanceVotes) {
                Integer turkerID;
                if (!annotatorsIDs.contains(relevanceVote.turkID)) {
                    annotatorsIDs.add(relevanceVote.turkID);
                    turkerID = annotatorsIDs.size() - 1;
                } else {
                    turkerID = annotatorsIDs.indexOf(relevanceVote.turkID);
                }
                Integer count = countVotesForATurker.get(relevanceVote.turkID);
                if (count == null) {
                    count = 0;
                }
                count++;
                countVotesForATurker.put(relevanceVote.turkID, count);

                String id;
                List<Integer> trueVotes;
                List<Integer> falseVotes;
                for (QueryResultContainer.SingleSentenceRelevanceVote singleSentenceRelevanceVote : relevanceVote.singleSentenceRelevanceVotes)
                    if (!"".equals(singleSentenceRelevanceVote.sentenceID)) {

                        id = f.getName() + "_" + documentID + "_" + singleSentenceRelevanceVote.sentenceID;
                        Annotations turkerVotes = annotations.get(id);
                        if (turkerVotes == null) {
                            trueVotes = new ArrayList<>();
                            falseVotes = new ArrayList<>();
                            turkerVotes = new Annotations(trueVotes, falseVotes);
                        }
                        trueVotes = turkerVotes.trueAnnotations;
                        falseVotes = turkerVotes.falseAnnotations;
                        if ("true".equals(singleSentenceRelevanceVote.relevant)) {
                            // votes[turkerID] = true;
                            trueVotes.add(turkerID);
                        } else if ("false".equals(singleSentenceRelevanceVote.relevant)) {
                            //   votes[turkerID] = false;
                            falseVotes.add(turkerID);
                        } else {
                            throw new IllegalStateException("Annotation value of sentence "
                                    + singleSentenceRelevanceVote.sentenceID + " in " + rankedResults.clueWebID
                                    + " equals " + singleSentenceRelevanceVote.relevant);
                        }
                        try {
                            int allVotesCount = trueVotes.size() + falseVotes.size();
                            if (allVotesCount > 5) {
                                System.err.println(id + " doesn't have 5 annotators: true: " + trueVotes.size()
                                        + " false: " + falseVotes.size());

                                // nasty hack, we're gonna strip some data; true votes first
                                /* we can't do that, it breaks something down the line
                                int toRemove = allVotesCount - 5;
                                if (trueVotes.size() >= toRemove) {
                                trueVotes = trueVotes
                                        .subList(0, trueVotes.size() - toRemove);
                                }
                                else if (
                                    falseVotes.size() >= toRemove) {
                                falseVotes = falseVotes
                                        .subList(0, trueVotes.size() - toRemove);
                                }
                                */
                                System.err.println("Adjusted: " + id + " doesn't have 5 annotators: true: "
                                        + trueVotes.size() + " false: " + falseVotes.size());
                            }
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        }
                        turkerVotes.trueAnnotations = trueVotes;
                        turkerVotes.falseAnnotations = falseVotes;
                        annotations.put(id, turkerVotes);
                    } else {
                        throw new IllegalStateException(
                                "Empty Sentence ID in " + f.getName() + " for turker " + turkerID);
                    }

            }
        }

    }
    File tmp = printHashMap(annotations, annotatorsIDs.size());

    String file = TEMP_DIR + "/" + tmp.getName();
    MACE.main(new String[] { "--prefix", file });

    //gets the keys of the documents and sentences
    ArrayList<String> lines = (ArrayList<String>) FileUtils.readLines(new File(file + ".prediction"));
    int i = 0;
    TreeMap<String, TreeMap<String, ArrayList<HashMap<String, String>>>> ids = new TreeMap<>();
    ArrayList<HashMap<String, String>> sentences;
    if (lines.size() != annotations.size()) {
        throw new IllegalStateException(
                "The size of prediction file is " + lines.size() + "but expected " + annotations.size());
    }
    for (Map.Entry entry : annotations.entrySet()) { //1001.xml_clueweb12-1905wb-13-07360_8783
        String key = (String) entry.getKey();
        String[] IDs = key.split("_");
        if (IDs.length > 2) {
            String queryID = IDs[0];
            String clueWebID = IDs[1];
            String sentenceID = IDs[2];
            TreeMap<String, ArrayList<HashMap<String, String>>> clueWebIDs = ids.get(queryID);
            if (clueWebIDs == null) {
                clueWebIDs = new TreeMap<>();
            }
            sentences = clueWebIDs.get(clueWebID);
            if (sentences == null) {
                sentences = new ArrayList<>();
            }
            HashMap<String, String> sentence = new HashMap<>();
            sentence.put(sentenceID, lines.get(i));
            sentences.add(sentence);
            clueWebIDs.put(clueWebID, sentences);
            ids.put(queryID, clueWebIDs);
        } else {
            throw new IllegalStateException("Wrong ID " + key);
        }

        i++;
    }

    for (Map.Entry entry : ids.entrySet()) {
        TreeMap<Integer, String> value = (TreeMap<Integer, String>) entry.getValue();
        String queryID = (String) entry.getKey();
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(new File(inputDir, queryID), "utf-8"));
        for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
            for (Map.Entry val : value.entrySet()) {
                String clueWebID = (String) val.getKey();
                if (clueWebID.equals(rankedResults.clueWebID)) {
                    List<QueryResultContainer.SingleSentenceRelevanceVote> goldEstimatedLabels = new ArrayList<>();
                    List<QueryResultContainer.SingleSentenceRelevanceVote> turkersVotes = new ArrayList<>();
                    int size = 0;
                    int hitSize = 0;
                    String hitID = "";
                    for (QueryResultContainer.MTurkRelevanceVote vote : rankedResults.mTurkRelevanceVotes) {
                        if (!hitID.equals(vote.hitID)) {
                            hitID = vote.hitID;
                            hitSize = vote.singleSentenceRelevanceVotes.size();
                            size = size + hitSize;
                            turkersVotes.addAll(vote.singleSentenceRelevanceVotes);
                        } else {
                            if (vote.singleSentenceRelevanceVotes.size() != hitSize) {
                                hitSize = vote.singleSentenceRelevanceVotes.size();
                                size = size + hitSize;
                                turkersVotes.addAll(vote.singleSentenceRelevanceVotes);
                            }
                        }
                    }
                    ArrayList<HashMap<String, String>> sentenceList = (ArrayList<HashMap<String, String>>) val
                            .getValue();
                    if (sentenceList.size() != turkersVotes.size()) {
                        try {
                            throw new IllegalStateException("Expected size of annotations is "
                                    + turkersVotes.size() + "but found " + sentenceList.size()
                                    + " for document " + rankedResults.clueWebID + " in " + queryID);
                        } catch (IllegalStateException ex) {
                            ex.printStackTrace();
                        }
                    }
                    for (QueryResultContainer.SingleSentenceRelevanceVote s : turkersVotes) {
                        String valSentence = null;
                        for (HashMap<String, String> anno : sentenceList) {
                            if (anno.keySet().contains(s.sentenceID)) {
                                valSentence = anno.get(s.sentenceID);
                            }
                        }
                        QueryResultContainer.SingleSentenceRelevanceVote singleSentenceVote = new QueryResultContainer.SingleSentenceRelevanceVote();
                        singleSentenceVote.sentenceID = s.sentenceID;
                        if (("false").equals(valSentence)) {
                            singleSentenceVote.relevant = "false";
                        } else if (("true").equals(valSentence)) {
                            singleSentenceVote.relevant = "true";
                        } else {
                            throw new IllegalStateException("Annotation value of sentence "
                                    + singleSentenceVote.sentenceID + " equals " + val.getValue());
                        }
                        goldEstimatedLabels.add(singleSentenceVote);
                    }
                    rankedResults.goldEstimatedLabels = goldEstimatedLabels;
                }
            }
        }
        File outputFile = new File(outputDir, queryID);
        FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8");
        System.out.println("Finished " + outputFile);
    }

    ArrayList<String> annotators = (ArrayList<String>) FileUtils.readLines(new File(file + ".competence"));
    FileWriter fileWriter;
    StringBuilder sb = new StringBuilder();
    for (int j = 0; j < annotatorsIDs.size(); j++) {
        String[] s = annotators.get(0).split("\t");
        Float score = Float.parseFloat(s[j]);
        String turkerID = annotatorsIDs.get(j);
        System.out.println(turkerID + " " + score + " " + countVotesForATurker.get(turkerID));
        sb.append(turkerID).append(" ").append(score).append(" ").append(countVotesForATurker.get(turkerID))
                .append("\n");
    }
    fileWriter = new FileWriter(turkersConfidence);
    fileWriter.append(sb.toString());
    fileWriter.close();

}

From source file:WriteIndex.java

/**
 * @param args/*  w  ww .j a v a  2s.  c om*/
 */
public static void main(String[] args) throws IOException {

    File docs = new File("documents");
    File indexDir = new File(INDEX_DIRECTORY);

    Directory directory = FSDirectory.open(indexDir);

    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);
    IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_35, analyzer);
    IndexWriter writer = new IndexWriter(directory, conf);
    writer.deleteAll();

    for (File file : docs.listFiles()) {
        Metadata metadata = new Metadata();
        ContentHandler handler = new BodyContentHandler();
        ParseContext context = new ParseContext();
        Parser parser = new AutoDetectParser();
        InputStream stream = new FileInputStream(file);
        try {
            parser.parse(stream, handler, metadata, context);
        } catch (TikaException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } finally {
            stream.close();
        }

        String text = handler.toString();
        String fileName = file.getName();

        Document doc = new Document();
        doc.add(new Field("file", fileName, Store.YES, Index.NO));

        for (String key : metadata.names()) {
            String name = key.toLowerCase();
            String value = metadata.get(key);

            if (StringUtils.isBlank(value)) {
                continue;
            }

            if ("keywords".equalsIgnoreCase(key)) {
                for (String keyword : value.split(",?(\\s+)")) {
                    doc.add(new Field(name, keyword, Store.YES, Index.NOT_ANALYZED));
                }
            } else if ("title".equalsIgnoreCase(key)) {
                doc.add(new Field(name, value, Store.YES, Index.ANALYZED));
            } else {
                doc.add(new Field(name, fileName, Store.YES, Index.NOT_ANALYZED));
            }
        }
        doc.add(new Field("text", text, Store.NO, Index.ANALYZED));
        writer.addDocument(doc);

    }

    writer.commit();
    writer.deleteUnusedFiles();

    System.out.println(writer.maxDoc() + " documents written");
}

From source file:ms1quant.MS1Quant.java

/**
 * @param args the command line arguments MS1Quant parameterfile
 *//*from ww w .j a  v a 2 s. c om*/
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:main.RankerOCR.java

/**
 * Command line interface for RankerOCR.
 * <p>/*  w ww  . j  a va2 s  . c o m*/
 * <b>Command line input:</b>
 * <ul>
 * usage: java -jar Ranker-OCR [options]
 * </ul>
 * <b>Options list:</b>
 * <ul>
 * <li>-gui Launch a graphical user interface</li>
 * <li>-help Show the help</li>
 * <li>-indoc1 [arg] Set the file name of the original document</li>
 * <li>-indoc2 [arg] Set the file name of the document to compare</li>
 * <li>-ranker [arg] Set the ranker used for the comparison</li>
 * <li>-outdoc [arg] Set the document where write the results</li>
 * <li>-separator [arg] Set the delimiter char use in the CSV out file</li>
 * </ul>
 * <b>Return values are if error:</b>
 * <ul>
 * <li>(-1) The precision parameter is not a number.</li>
 * <li>(-2) The precision parameter is lower than 0.</li>
 * <li>(-3) The precision parameter is greater than 10.</li>
 * <li>(-11) The ranker name is wrong</li>
 * <li>(-21) The separator char is empty</li>
 * <li>(-22) The separator is not a char</li>
 * <li>(-31) File name doesn't exist</li>
 * <li>(-32) File name is not a file</li>
 * <li>(-33) Error when access to documents files</li>
 * <li>(-34) Output file can not be write</li>
 * <li>(-35) Output file can not be created</li>
 * <li>(-41) Error when parsing parameters</li>
 * <li>(-100) Internal error when creating the ranker. Please report a
 * bug</li>
 * <li>(-101) Internal error when get the ranker list. Please report a
 * bug.</li>
 * <li>(-102) Error when access to help file. Please report a bug.</li>
 * </ul>
 * <p>
 * @param args Argument array which can have the values from options list
 */
public static void main(String[] args) {
    //Parse command line
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("help")) {
            showHelp(hf, options);
        } else if (cmd.hasOption("gui")) {
            display.DispalyRankerOCR.main(new String[] {});
        } else if (cmd.hasOption("indoc1") && cmd.hasOption("indoc2") && cmd.hasOption("outdoc")) {
            //<editor-fold defaultstate="collapsed" desc="Rank documents">
            //Prepare parameter
            Class ranker = evalRanker(cmd.getOptionValue("ranker", "SimpleRanker"));
            char separator = evalSeparator(cmd.getOptionValue("separator", "\t"));
            File f1 = evalInputFile(cmd.getOptionValue("indoc1", ""));
            File f2 = evalInputFile(cmd.getOptionValue("indoc2", ""));
            File f3 = evalOutputFile(cmd.getOptionValue("outdoc", ""), separator);
            //Read file
            String s1 = readInputDocText(f1);
            String s2 = readInputDocText(f2);
            //Compare file
            double percent = rankDocuments(s1, s2, ranker);
            //Write result
            String[] s = { Double.toString(percent), ranker.getSimpleName(), f1.getName(), f2.getName(),
                    f1.getParent(), f2.getParent(), new Date().toString() };
            writeOutpuDocCsv(f3, separator, s);
            //</editor-fold>
        } else {
            printFormated("java -jar Ranker-OCR [options]  please type " + "-help for more info");
        }
    } catch (ParseException ex) {
        printFormated(ex.getLocalizedMessage());
        System.exit(-41);
    }
}

From source file:eu.annocultor.utils.OntologySubtractor.java

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

    boolean copy = checkNoCopyOption(args);

    if (args.length == 2 || args.length == 3) {

        File sourceDir = new File(args[0]);
        File destinationDir = new File(args[1]);

        checkSrcAndDstDirs(sourceDir, destinationDir);

        Collection<String> filesWithDeletedStatements = listNameStamsForFilesWithDeletedStatements(sourceDir);

        if (filesWithDeletedStatements.isEmpty()) {
            System.out.println(//from w ww .  j  a  va  2 s .  c o m
                    "Did not found any file *.*.*.deleted.rdf with statements to be deleted. Do nothing and exit.");
        } else {

            System.out.println(
                    "Found " + filesWithDeletedStatements.size() + " files with statements to be deleted");
            System.out.println(
                    "Copying all RDF files from " + sourceDir.getName() + " to " + destinationDir.getName());

            if (copy) {
                copyRdfFiles(sourceDir, destinationDir);
            }

            sutractAll(sourceDir, destinationDir, filesWithDeletedStatements);
        }
    } else {
        for (Object string : IOUtils.readLines(new AutoCloseInputStream(
                OntologySubtractor.class.getResourceAsStream("/subtractor/readme.txt")))) {
            System.out.println(string.toString());
        }
    }
}

From source file:com.l2jfree.tools.ProjectSettingsSynchronizer.java

public static void main(String[] args) throws IOException {
    final File src = new File(".").getCanonicalFile();
    System.out.println("Copying from: " + src);
    System.out.println();//from  ww w  . j a  va 2s . co  m

    final List<File> destinations = new ArrayList<File>();
    for (File dest : src.getParentFile().listFiles()) {
        if (dest.isHidden() || !dest.isDirectory())
            continue;

        destinations.add(dest);
        System.out.println("Copying to: " + dest);
    }
    System.out.println();

    // .project
    System.out.println(".project");
    System.out.println("================================================================================");
    {
        final List<String> lines = FileUtils.readLines(new File(src, ".project"));

        for (File dest : destinations) {
            lines.set(2, lines.get(2).replaceAll(src.getName(), dest.getName()));
            writeLines(dest, ".project", lines);
            lines.set(2, lines.get(2).replaceAll(dest.getName(), src.getName()));
        }
    }
    System.out.println();

    // .classpath
    System.out.println(".classpath");
    System.out.println("================================================================================");
    {
        final List<String> lines = FileUtils.readLines(new File(src, ".classpath"));

        for (File dest : destinations) {
            if (dest.getName().endsWith("-main") || dest.getName().endsWith("-datapack")) {
                final ArrayList<String> tmp = new ArrayList<String>();

                for (String line : lines)
                    if (!line.contains("classpathentry"))
                        tmp.add(line);

                writeLines(dest, ".classpath", tmp);
                continue;
            }

            writeLines(dest, ".classpath", lines);
        }
    }
    System.out.println();

    // .settings
    System.out.println(".settings");
    System.out.println("================================================================================");
    for (File settingsFile : new File(src, ".settings").listFiles()) {
        if (settingsFile.getName().endsWith(".prefs")) {
            System.out.println(".settings/" + settingsFile.getName());
            System.out.println(
                    "--------------------------------------------------------------------------------");

            final List<String> lines = FileUtils.readLines(settingsFile);

            if (lines.get(0).startsWith("#"))
                lines.remove(0);

            for (File dest : destinations) {
                writeLines(new File(dest, ".settings"), settingsFile.getName(), lines);
            }
            System.out.println();
        }
    }
    System.out.println();
}

From source file:com.clustercontrol.agent.Agent.java

/**
 * ?//from  w w  w .  j a v a 2 s . c o  m
 * 
 * @param args ??
 */
public static void main(String[] args) throws Exception {

    // ?
    if (args.length != 1) {
        System.out.println("Usage : java Agent [Agent.properties File Path]");
        System.exit(1);
    }

    try {
        // System
        m_log.info("starting Hinemos Agent...");
        m_log.info("java.vm.version = " + System.getProperty("java.vm.version"));
        m_log.info("java.vm.vendor = " + System.getProperty("java.vm.vendor"));
        m_log.info("java.home = " + System.getProperty("java.home"));
        m_log.info("os.name = " + System.getProperty("os.name"));
        m_log.info("os.arch = " + System.getProperty("os.arch"));
        m_log.info("os.version = " + System.getProperty("os.version"));
        m_log.info("user.name = " + System.getProperty("user.name"));
        m_log.info("user.dir = " + System.getProperty("user.dir"));
        m_log.info("user.country = " + System.getProperty("user.country"));
        m_log.info("user.language = " + System.getProperty("user.language"));
        m_log.info("file.encoding = " + System.getProperty("file.encoding"));

        // System(SET)
        String limitKey = "jdk.xml.entityExpansionLimit"; // TODO JRE???????????????????
        System.setProperty(limitKey, "0");
        m_log.info(limitKey + " = " + System.getProperty(limitKey));

        // TODO ???agentHome
        // ??????????
        File file = new File(args[0]);
        agentHome = file.getParentFile().getParent() + "/";
        m_log.info("agentHome=" + agentHome);

        // 
        long startDate = HinemosTime.currentTimeMillis();
        m_log.info("start date = " + new Date(startDate) + "(" + startDate + ")");
        agentInfo.setStartupTime(startDate);

        // Agent??
        m_log.info("Agent.properties = " + args[0]);

        // ?
        File scriptDir = new File(agentHome + "script/");
        if (scriptDir.exists()) {
            File[] listFiles = scriptDir.listFiles();
            if (listFiles != null) {
                for (File f : listFiles) {
                    boolean ret = f.delete();
                    if (ret) {
                        m_log.debug("delete script : " + f.getName());
                    } else {
                        m_log.warn("delete script error : " + f.getName());
                    }
                }
            } else {
                m_log.warn("listFiles is null");
            }
        } else {
            //????????
            boolean ret = scriptDir.mkdir();
            if (!ret) {
                m_log.warn("mkdir error " + scriptDir.getPath());
            }
        }

        // queue?
        m_sendQueue = new SendQueue();

        // Agent?
        Agent agent = new Agent(args[0]);

        //-----------------
        //-- 
        //-----------------
        m_log.debug("exec() : create topic ");

        m_receiveTopic = new ReceiveTopic(m_sendQueue);
        m_receiveTopic.setName("ReceiveTopicThread");
        m_log.info("receiveTopic start 1");
        m_receiveTopic.start();
        m_log.info("receiveTopic start 2");

        // ?
        agent.exec();

        m_log.info("Hinemos Agent started");

        // ?
        agent.waitAwakeAgent();
    } catch (Throwable e) {
        m_log.error("Agent.java: Runtime Exception Occurred. " + e.getClass().getName() + ", " + e.getMessage(),
                e);
    }
}