Example usage for org.apache.commons.io FileUtils readFileToString

List of usage examples for org.apache.commons.io FileUtils readFileToString

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils readFileToString.

Prototype

public static String readFileToString(File file) throws IOException 

Source Link

Document

Reads the contents of a file into a String using the default encoding for the VM.

Usage

From source file:ee.ria.xroad.common.signature.BatchSignerIntegrationTest.java

/**
 * Main program entry point./*w  ww  . j a  v  a  2s . c  o  m*/
 * @param args command-line arguments
 * @throws Exception in case of any errors
 */
public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        printUsage();

        return;
    }

    ActorSystem actorSystem = ActorSystem.create("Proxy", ConfigFactory.load().getConfig("proxy"));
    SignerClient.init(actorSystem);

    Thread.sleep(SIGNER_INIT_DELAY); // wait for signer client to connect

    BatchSigner.init(actorSystem);

    X509Certificate subjectCert = TestCertUtil.getConsumer().cert;
    X509Certificate issuerCert = TestCertUtil.getCaCert();
    X509Certificate signerCert = TestCertUtil.getOcspSigner().cert;
    PrivateKey signerKey = TestCertUtil.getOcspSigner().key;

    List<String> messages = new ArrayList<>();

    for (String arg : args) {
        messages.add(FileUtils.readFileToString(new File(arg)));
    }

    latch = new CountDownLatch(messages.size());

    Date thisUpdate = new DateTime().plusDays(1).toDate();
    final OCSPResp ocsp = OcspTestUtils.createOCSPResponse(subjectCert, issuerCert, signerCert, signerKey,
            CertificateStatus.GOOD, thisUpdate, null);

    for (final String message : messages) {
        new Thread(() -> {
            try {
                byte[] hash = hash(message);
                log.info("File: {}, hash: {}", message, hash);

                MessagePart hashPart = new MessagePart(MessageFileNames.MESSAGE, SHA512_ID,
                        calculateDigest(SHA512_ID, message.getBytes()), message.getBytes());

                List<MessagePart> hashes = Collections.singletonList(hashPart);

                SignatureBuilder builder = new SignatureBuilder();
                builder.addPart(hashPart);

                builder.setSigningCert(subjectCert);
                builder.addOcspResponses(Collections.singletonList(ocsp));

                log.info("### Calculating signature...");

                SignatureData signatureData = builder.build(
                        new SignerSigningKey(KEY_ID, CryptoUtils.CKM_RSA_PKCS_NAME), CryptoUtils.SHA512_ID);

                synchronized (sigIdx) {
                    log.info("### Created signature: {}", signatureData.getSignatureXml());

                    log.info("HashChainResult: {}", signatureData.getHashChainResult());
                    log.info("HashChain: {}", signatureData.getHashChain());

                    toFile("message-" + sigIdx + ".xml", message);

                    String sigFileName = signatureData.getHashChainResult() != null ? "batch-sig-" : "sig-";

                    toFile(sigFileName + sigIdx + ".xml", signatureData.getSignatureXml());

                    if (signatureData.getHashChainResult() != null) {
                        toFile("hash-chain-" + sigIdx + ".xml", signatureData.getHashChain());
                        toFile("hash-chain-result.xml", signatureData.getHashChainResult());
                    }

                    sigIdx++;
                }

                try {
                    verify(signatureData, hashes, message);

                    log.info("Verification successful (message hash: {})", hash);
                } catch (Exception e) {
                    log.error("Verification failed (message hash: {})", hash, e);
                }
            } catch (Exception e) {
                log.error("Error", e);
            } finally {
                latch.countDown();
            }
        }).start();
    }

    latch.await();
    actorSystem.shutdown();
}

From source file:edu.lternet.pasta.datapackagemanager.ProvenanceBackfiller.java

/**
 * Main program to backfill the provenance table. 
 * It takes no command arguments. //www .jav a 2s  . c o  m
 * Should be run in the DataPackageManager top-level directory.
 * 
 * @param args   Any arguments passed to the program are ignored.
 */
public static void main(String[] args) {
    int backfillCount = 0;
    int derivedDataPackageCount = 0;
    int recordsInserted = 0;
    final boolean evaluateMode = false;

    try {
        ConfigurationListener configurationListener = new ConfigurationListener();
        configurationListener.initialize(dirPath);
        DataPackageRegistry dpr = DataPackageManager.makeDataPackageRegistry();
        ProvenanceIndex provenanceIndex = new ProvenanceIndex(dpr);
        EmlPackageIdFormat epif = new EmlPackageIdFormat();

        List<EmlPackageId> emlPackageIds = getAllDataPackageRevisions(dpr);

        for (EmlPackageId emlPackageId : emlPackageIds) {
            DataPackageMetadata dataPackageMetadata = new DataPackageMetadata(emlPackageId);
            if (dataPackageMetadata != null) {
                File levelOneEMLFile = dataPackageMetadata.getMetadata(evaluateMode);
                String emlDocument = FileUtils.readFileToString(levelOneEMLFile);
                String packageId = epif.format(emlPackageId);
                System.err.println("  " + packageId);

                try {
                    ArrayList<String> sourceIds = provenanceIndex.insertProvenanceRecords(packageId,
                            emlDocument);
                    if ((sourceIds != null) && (sourceIds.size() > 0)) {
                        derivedDataPackageCount++;
                        recordsInserted += sourceIds.size();
                    }
                } catch (ProvenanceException e) {
                    logger.error(e.getMessage());
                }

                backfillCount++;
            }
        }
    } catch (Exception e) {
        logger.error(
                String.format("An error occurred during provenance backfill processing: %s", e.getMessage()));
        e.printStackTrace();
    }

    System.err.println(String.format(
            "Finished provenance backfill processing. Provenance generated and stored for %d resource(s).",
            backfillCount));
    System.err.println(
            String.format("Total number of derived data packages detected: %d.", derivedDataPackageCount));
    System.err.println(String.format("Total records inserted into provenance table: %d.", recordsInserted));
}

From source file:bboss.org.artofsolving.jodconverter.cli.Convert.java

public static void main(String[] arguments) throws ParseException, JSONException, IOException {
    CommandLineParser commandLineParser = new PosixParser();
    CommandLine commandLine = commandLineParser.parse(OPTIONS, arguments);

    String outputFormat = null;/* w w  w  .  j  a v a 2s  . co m*/
    if (commandLine.hasOption(OPTION_OUTPUT_FORMAT.getOpt())) {
        outputFormat = commandLine.getOptionValue(OPTION_OUTPUT_FORMAT.getOpt());
    }

    int port = DEFAULT_OFFICE_PORT;
    if (commandLine.hasOption(OPTION_PORT.getOpt())) {
        port = Integer.parseInt(commandLine.getOptionValue(OPTION_PORT.getOpt()));
    }

    String[] fileNames = commandLine.getArgs();
    if ((outputFormat == null && fileNames.length != 2) || fileNames.length < 1) {
        String syntax = "java -jar jodconverter-core.jar [options] input-file output-file\n"
                + "or [options] -o output-format input-file [input-file...]";
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp(syntax, OPTIONS);
        System.exit(STATUS_INVALID_ARGUMENTS);
    }

    DocumentFormatRegistry registry;
    if (commandLine.hasOption(OPTION_REGISTRY.getOpt())) {
        File registryFile = new File(commandLine.getOptionValue(OPTION_REGISTRY.getOpt()));
        registry = new JsonDocumentFormatRegistry(FileUtils.readFileToString(registryFile));
    } else {
        registry = new DefaultDocumentFormatRegistry();
    }

    DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
    configuration.setPortNumber(port);
    if (commandLine.hasOption(OPTION_TIMEOUT.getOpt())) {
        int timeout = Integer.parseInt(commandLine.getOptionValue(OPTION_TIMEOUT.getOpt()));
        configuration.setTaskExecutionTimeout(timeout * 1000);
    }
    if (commandLine.hasOption(OPTION_USER_PROFILE.getOpt())) {
        String templateProfileDir = commandLine.getOptionValue(OPTION_USER_PROFILE.getOpt());
        configuration.setTemplateProfileDir(new File(templateProfileDir));
    }

    OfficeManager officeManager = configuration.buildOfficeManager();
    officeManager.start();
    OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager, registry);
    try {
        if (outputFormat == null) {
            File inputFile = new File(fileNames[0]);
            File outputFile = new File(fileNames[1]);
            converter.convert(inputFile, outputFile);
        } else {
            for (int i = 0; i < fileNames.length; i++) {
                File inputFile = new File(fileNames[i]);
                String outputName = FilenameUtils.getBaseName(fileNames[i]) + "." + outputFormat;
                File outputFile = new File(FilenameUtils.getFullPath(fileNames[i]) + outputName);
                converter.convert(inputFile, outputFile);
            }
        }
    } finally {
        officeManager.stop();
    }
}

From source file:jh.tools.office.ConvertOutPDF.java

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

    try {/*  ww w .  ja  va 2  s .c  o m*/
        getInputFilePath(args);
    } catch (IllegalArgumentException e) {
    }

    // Font regex (optional)
    // Set regex if you want to restrict to some defined subset of fonts
    // Here we have to do this before calling createContent,
    // since that discovers fonts
    String regex = null;
    // Windows:
    // String
    // regex=".*(calibri|camb|cour|arial|symb|times|Times|zapf).*";
    //regex=".*(calibri|camb|cour|arial|times|comic|georgia|impact|LSANS|pala|tahoma|trebuc|verdana|symbol|webdings|wingding).*";
    // Mac
    // String
    // regex=".*(Courier New|Arial|Times New Roman|Comic Sans|Georgia|Impact|Lucida Console|Lucida Sans Unicode|Palatino Linotype|Tahoma|Trebuchet|Verdana|Symbol|Webdings|Wingdings|MS Sans Serif|MS Serif).*";
    PhysicalFonts.setRegex(regex);

    // Document loading (required)
    WordprocessingMLPackage wordMLPackage;

    // Load .docx or Flat OPC .xml
    System.out.println("Loading file from " + inputfilepath);
    wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));

    // Refresh the values of DOCPROPERTY fields
    FieldUpdater updater = new FieldUpdater(wordMLPackage);
    //updater.update(true);

    String outputfilepath;
    if (inputfilepath == null) {
        outputfilepath = System.getProperty("user.dir") + "/OUT_FontContent.pdf";
    } else {
        outputfilepath = inputfilepath + ".pdf";
    }

    // All methods write to an output stream
    OutputStream os = new java.io.FileOutputStream(outputfilepath);

    if (!Docx4J.pdfViaFO()) {

        // Since 3.3.0, Plutext's PDF Converter is used by default

        System.out.println("Using Plutext's PDF Converter; add docx4j-export-fo if you don't want that");

        try {
            Docx4J.toPDF(wordMLPackage, os);
        } catch (Docx4JException e) {
            e.printStackTrace();
            // What did we write?
            IOUtils.closeQuietly(os);
            System.out.println(FileUtils.readFileToString(new File(outputfilepath)));
            if (e.getCause() != null && e.getCause() instanceof ConversionException) {

                ConversionException ce = (ConversionException) e.getCause();
                ce.printStackTrace();
            }
        }
        System.out.println("Saved: " + outputfilepath);

        return;
    }

    System.out.println("Attempting to use XSL FO");

    /**
     * Demo of PDF output.
     *
     * PDF output is via XSL FO.
     * First XSL FO is created, then FOP
     * is used to convert that to PDF.
     *
     * Don't worry if you get a class not
     * found warning relating to batik. It
     * doesn't matter.
     *
     * If you don't have logging configured,
     * your PDF will say "TO HIDE THESE MESSAGES,
     * TURN OFF debug level logging for
     * org.docx4j.convert.out.pdf.viaXSLFO".  The thinking is
     * that you need to be able to be warned if there
     * are things in your docx which the PDF output
     * doesn't support...
     *
     * docx4j used to also support creating
     * PDF via iText and via HTML. As of docx4j 2.5.0,
     * only viaXSLFO is supported.  The viaIText and
     * viaHTML source code can be found in src/docx4j-extras directory
     *
     */

    /*
     * NOT WORKING?
     *
     * If you are getting:
     *
     *   "fo:layout-master-set" must be declared before "fo:page-sequence"
     *
     * please check:
     *
     * 1.  the jaxb-xslfo jar is on your classpath
     *
     * 2.  that there is no stack trace earlier in the logs
     *
     * 3.  your JVM has adequate memory, eg
     *
     *           -Xmx1G -XX:MaxPermSize=128m
     *
     */

    // Set up font mapper (optional)
    Mapper fontMapper = new IdentityPlusMapper();
    wordMLPackage.setFontMapper(fontMapper);
    fontMapper.put("", PhysicalFonts.get("LiSu"));
    fontMapper.put("", PhysicalFonts.get("SimSun"));
    fontMapper.put("", PhysicalFonts.get("Microsoft Yahei"));
    fontMapper.put("", PhysicalFonts.get("SimHei"));
    fontMapper.put("", PhysicalFonts.get("KaiTi"));
    fontMapper.put("", PhysicalFonts.get("NSimSun"));
    fontMapper.put("?", PhysicalFonts.get("STXingkai"));
    fontMapper.put("?", PhysicalFonts.get("STFangsong"));
    fontMapper.put("", PhysicalFonts.get("simsun-extB"));
    fontMapper.put("", PhysicalFonts.get("FangSong"));
    fontMapper.put("_GB2312", PhysicalFonts.get("FangSong_GB2312"));
    fontMapper.put("", PhysicalFonts.get("YouYuan"));
    fontMapper.put("?", PhysicalFonts.get("STSong"));
    fontMapper.put("?", PhysicalFonts.get("STZhongsong"));

    // .. example of mapping font Times New Roman which doesn't have certain Arabic glyphs
    // eg Glyph "" (0x64a, afii57450) not available in font "TimesNewRomanPS-ItalicMT".
    // eg Glyph "" (0x62c, afii57420) not available in font "TimesNewRomanPS-ItalicMT".
    // to a font which does
    PhysicalFont font = PhysicalFonts.get("Arial Unicode MS");
    // make sure this is in your regex (if any)!!!
    //      if (font!=null) {
    //         fontMapper.put("Times New Roman", font);
    //         fontMapper.put("Arial", font);
    //      }
    //      fontMapper.put("Libian SC Regular", PhysicalFonts.get("SimSun"));

    // FO exporter setup (required)
    // .. the FOSettings object
    FOSettings foSettings = Docx4J.createFOSettings();
    if (saveFO) {
        foSettings.setFoDumpFile(new java.io.File(inputfilepath + ".fo"));
    }
    foSettings.setWmlPackage(wordMLPackage);

    // Document format:
    // The default implementation of the FORenderer that uses Apache Fop will output
    // a PDF document if nothing is passed via
    // foSettings.setApacheFopMime(apacheFopMime)
    // apacheFopMime can be any of the output formats defined in org.apache.fop.apps.MimeConstants eg org.apache.fop.apps.MimeConstants.MIME_FOP_IF or
    // FOSettings.INTERNAL_FO_MIME if you want the fo document as the result.
    //foSettings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);

    // Specify whether PDF export uses XSLT or not to create the FO
    // (XSLT takes longer, but is more complete).

    // Don't care what type of exporter you use
    Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);

    // Prefer the exporter, that uses a xsl transformation
    // Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);

    // Prefer the exporter, that doesn't use a xsl transformation (= uses a visitor)
    // .. faster, but not yet at feature parity
    // Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_NONXSL);

    System.out.println("Saved: " + outputfilepath);

    // Clean up, so any ObfuscatedFontPart temp files can be deleted
    if (wordMLPackage.getMainDocumentPart().getFontTablePart() != null) {
        wordMLPackage.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles();
    }
    // This would also do it, via finalize() methods
    updater = null;
    foSettings = null;
    wordMLPackage = null;

}

From source file:com.ai.tools.generator.util.XMLFormatter.java

public static void main(String[] args) {
    try {/*from  w  w  w.  j  a  v a  2  s. c om*/
        String xml = FileUtils.readFileToString(new File("E://github/zj_java/POJOTools/DocumentException.xml"));
        xml = formatXML(xml);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:edu.lternet.pasta.client.EmlUtility.java

/**
 * @param args   String array with three arguments:
 *   arg[0] absolute path to the input XML file
 *   arg[1] absolute path to the output HTML file
 *   arg[2] absolute path to the EML XSLT stylesheet
 *//*from w  ww.jav a 2 s. co  m*/
public static void main(String[] args) {

    String inputPath = args[0];
    String outputPath = args[1];
    String emlXslPath = args[2];
    ConfigurationListener.configure();

    File inFile = new File(inputPath);
    File outFile = new File(outputPath);
    String eml = null;

    try {
        eml = FileUtils.readFileToString(inFile);
    } catch (IOException e1) {
        logger.error(e1.getMessage());
        e1.printStackTrace();
    }

    EmlUtility eu = null;

    try {
        eu = new EmlUtility(eml);
    } catch (ParseException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    String html = eu.xmlToHtml(emlXslPath, null);

    try {
        FileUtils.writeStringToFile(outFile, html);
    } catch (IOException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

}

From source file:com.tvh.gmaildrafter.Drafter.java

/**
 * @param args the command line arguments
 *///  w  ww  . jav  a2  s  . com
public static void main(String[] args) {
    Options options = getCMDLineOptions();
    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("help")) {
            printHelpMessage(options);
            System.exit(0);
        }

        String emailBody = null;
        String emailSubject = null;

        if (cmd.hasOption("body")) {
            String bodyFile = cmd.getOptionValue("body");
            File body = new File(bodyFile);
            emailBody = FileUtils.readFileToString(body);
            if (cmd.hasOption("deletebody")) {
                body.delete();
            }
        } else if (cmd.hasOption("stdin")) {
            emailBody = Util.readEntireStdin();
        }

        if (cmd.hasOption("subject"))
            emailSubject = cmd.getOptionValue("subject");
        else if (cmd.hasOption("subjectfile")) {
            String subjectFile = cmd.getOptionValue("subjectfile");
            File subject = new File(subjectFile);
            emailSubject = FileUtils.readFileToString(subject);
            if (cmd.hasOption("deletesubjectfile"))
                subject.delete();
        }

        String username = null;
        if (cmd.hasOption("username"))
            username = cmd.getOptionValue("username");

        String password = null;
        if (cmd.hasOption("password"))
            password = cmd.getOptionValue("password");

        String[] bcc = cmd.getOptionValues("bcc");
        String[] cc = cmd.getOptionValues("cc");

        Boolean sendImmediately = cmd.hasOption("immediate");

        String[] attachments = cmd.getOptionValues("attachments");
        String[] attachmentnames = cmd.getOptionValues("attachmentnames");
        String[] destinations = cmd.getOptionValues("to");

        Credentials credentials = Authenticater.getValidCredentials(username, password);

        if (credentials != null) {
            boolean success = false;
            while (!success) {
                try {
                    composeMail(credentials, emailSubject, emailBody, attachments, attachmentnames,
                            destinations, cc, bcc, sendImmediately);
                    success = true;
                } catch (AuthenticationFailedException e) {
                    JOptionPane.showMessageDialog(null, "Invalid login, please try again!");
                    credentials = Authenticater.getValidCredentials(username, null);
                    success = false;
                }

            }
        }

    } catch (ParseException ex) {
        javax.swing.JOptionPane.showMessageDialog(null, ex.getMessage());
        printHelpMessage(options);
        System.exit(7);
    } catch (IOException ex) {
        System.out.println("IO Exception " + ex.getLocalizedMessage());
        printHelpMessage(options);
        System.exit(2);
    } catch (LoginException ex) {
        System.out.println(ex.getMessage());
        System.exit(3);
    }

    System.exit(0);

}

From source file:com.wittawat.wordseg.Main.java

public static void main(String[] args) throws Exception {
    Console con = System.console();
    if (con == null) {
        System.out.println("The system must support console to run the program.");
        System.exit(1);/* w  w w .  jav a  2 s.c o  m*/
    }
    // Load model
    System.out.println("Loading model ...");
    Classifier model = Data.getDefaultModel();

    System.out.println("Finished loading model.");
    System.out.println(getAgreement());

    boolean isUseDict = true;

    // Dummy statement to eliminate all lazy loading
    System.out.println("\n" + new NukeTokenizer3(
            "?????",
            model, isUseDict).tokenize() + "\n");

    System.out.println(getHelp());

    final String SET_DICT_PAT_STR = "\\s*set\\s+dict\\s+(true|false)\\s*";
    final Pattern SET_DICT_PAT = Pattern.compile(SET_DICT_PAT_STR);
    while (true) {
        System.out.print(">> ");
        String line = con.readLine();
        if (line != null && !line.trim().equals("")) {

            line = line.trim();
            try {
                if (line.equals("h") || line.equals("help")) {
                    System.out.println(getHelp());
                } else if (line.equals("about")) {
                    System.out.println(getAbout());
                } else if (line.equals("agreement")) {
                    System.out.println(getAgreement());
                } else if (SET_DICT_PAT.matcher(line).find()) {
                    Matcher m = SET_DICT_PAT.matcher(line);
                    m.find();
                    String v = m.group(1);
                    isUseDict = v.equals("true");
                    System.out.println("Dictionary will " + (isUseDict ? "" : "not ") + "be used.");
                } else if (line.matches("q|quit|exit")) {
                    System.out.println("Bye");
                    System.exit(0);
                } else if (line.contains(":tokfile:")) {
                    String[] splits = line.split(":tokfile:");
                    String in = splits[0];
                    String out = splits[1];
                    String content = FileUtils.readFileToString(new File(in));
                    long start = new Date().getTime();

                    NukeTokenizer tokenizer = new NukeTokenizer3(content, model, isUseDict);

                    String tokenized = tokenizer.tokenize();
                    long end = new Date().getTime();
                    System.out.println("Time to tokenize: " + (end - start) + " ms.");
                    FileUtils.writeStringToFile(new File(out), tokenized);
                } else if (line.contains(":tokfile")) {
                    String[] splits = line.split(":tokfile");
                    String in = splits[0];

                    String content = FileUtils.readFileToString(new File(in));
                    long start = new Date().getTime();
                    NukeTokenizer tokenizer = new NukeTokenizer3(content, model, isUseDict);
                    String tokenized = tokenizer.tokenize();
                    long end = new Date().getTime();

                    System.out.println(tokenized);
                    System.out.println("Time to tokenize: " + (end - start) + " ms.");
                } else if (line.contains(":tok:")) {
                    String[] splits = line.split(":tok:");
                    String inText = splits[0];
                    String out = splits[1];

                    long start = new Date().getTime();
                    NukeTokenizer tokenizer = new NukeTokenizer3(inText, model, isUseDict);
                    String tokenized = tokenizer.tokenize();
                    long end = new Date().getTime();
                    System.out.println("Time to tokenize: " + (end - start) + " ms.");
                    FileUtils.writeStringToFile(new File(out), tokenized);
                } else if (line.contains(":tok")) {
                    String[] splits = line.split(":tok");
                    String inText = splits[0];

                    long start = new Date().getTime();
                    NukeTokenizer tokenizer = new NukeTokenizer3(inText, model, isUseDict);
                    String tokenized = tokenizer.tokenize();
                    long end = new Date().getTime();

                    System.out.println(tokenized);
                    System.out.println("Time to tokenize: " + (end - start) + " ms.");
                } else {
                    System.out.println("Unknown command");
                }
            } catch (Exception e) {
                System.out.println("Error. See the exception.");
                e.printStackTrace();
            }

        }
    }

}

From source file:edu.illinois.cs.cogcomp.ner.BenchmarkOutputParser.java

/**
 * This main method will take one required argument, idenfitying the file containing 
 * the results. Optionally, "-single" may also be passed indicating it will extract
 * the F1 value for single token values only.
 * @param args//from w ww .  j a v a 2  s  . c om
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    parseArgs(args);
    System.out.println("L1lr,L1t,L2lr,L2t,L1 token,L2 token,F1,F2");
    for (File file : resultsfile.listFiles()) {
        if (file.getName().startsWith("L1r")) {
            File resultsfile = new File(file, "ner/results.out");
            if (resultsfile.exists()) {
                try {
                    Parameters p = parseFilename(file);
                    String lines = FileUtils.readFileToString(resultsfile);

                    // get the token level score.
                    String tokenL2 = null, tokenL1 = null;
                    Matcher matcher = l2tokenlevelpattern.matcher(lines);
                    if (matcher.find())
                        tokenL2 = matcher.group(1);
                    else {
                        matcher = ol2tokenlevelpattern.matcher(lines);
                        if (matcher.find())
                            tokenL2 = matcher.group(1);
                        else
                            System.err.println("No token level match");
                    }

                    matcher = l1tokenlevelpattern.matcher(lines);
                    if (matcher.find())
                        tokenL1 = matcher.group(1);
                    else {
                        matcher = ol1tokenlevelpattern.matcher(lines);
                        if (matcher.find())
                            tokenL1 = matcher.group(1);
                        else
                            System.err.println("No token level match");
                    }

                    matcher = phraselevelpattern.matcher(lines);
                    matcher.find();
                    String phraseL1 = matcher.group(1);
                    String phraseL2 = matcher.group(2);
                    System.out.println(
                            p.toString() + "," + tokenL1 + "," + tokenL2 + "," + phraseL1 + "," + phraseL2);
                } catch (java.lang.IllegalStateException ise) {
                    System.err.println("The results file could not be parsed : \"" + resultsfile + "\"");
                }
            } else {
                System.err.println("no results in " + resultsfile);
            }

        }
    }
}

From source file:launcher.Settings.java

public static Settings load(String configPath) {
    LaunchLogger.info("Pulling launcher settings from: " + configPath);
    try {//from  w  ww. j av a 2s .co m
        Gson gson = new Gson();
        return gson.fromJson(FileUtils.readFileToString(new File(configPath)), Settings.class);
    } catch (Exception e) {
        LaunchLogger.exception(e);
    }
    return null;
}