Example usage for org.apache.commons.io IOUtils closeQuietly

List of usage examples for org.apache.commons.io IOUtils closeQuietly

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils closeQuietly.

Prototype

public static void closeQuietly(OutputStream output) 

Source Link

Document

Unconditionally close an OutputStream.

Usage

From source file:com.textocat.textokit.postagger.GenerateAggregateDescriptorForMorphAnnotator.java

public static void main(String[] args) throws UIMAException, IOException, SAXException {
    if (args.length != 1) {
        System.err.println("Usage: <output-path>");
        System.exit(1);//from w  w w.  j a  v  a 2s.  c om
    }
    String outputPath = args[0];
    // NOTE! A file URL for generated SerializedDictionaryResource description assumes
    // that the required dictionary file is within one of UIMA datapath folders.
    // So users of the generated aggregate descriptor should setup 'uima.datapath' properly .
    ExternalResourceDescription morphDictDesc = getMorphDictionaryAPI()
            .getResourceDescriptionWithPredictorEnabled();

    Map<String, MetaDataObject> aeDescriptions = Maps.newLinkedHashMap();
    aeDescriptions.put("tokenizer", TokenizerAPI.getAEImport());
    //
    aeDescriptions.put("sentence-splitter", SentenceSplitterAPI.getAEImport());
    //
    aeDescriptions.put("morph-analyzer", MorphologyAnnotator.createDescription(DefaultAnnotationAdapter.class,
            PosTaggerAPI.getTypeSystemDescription()));
    //
    aeDescriptions.put("tag-assembler", TagAssembler.createDescription());
    AnalysisEngineDescription desc = PipelineDescriptorUtils.createAggregateDescription(aeDescriptions);
    // bind the dictionary resource
    bindExternalResource(desc, "morph-analyzer/" + MorphologyAnnotator.RESOURCE_KEY_DICTIONARY, morphDictDesc);
    bindExternalResource(desc, "tag-assembler/" + GramModelBasedTagMapper.RESOURCE_GRAM_MODEL, morphDictDesc);

    FileOutputStream out = FileUtils.openOutputStream(new File(outputPath));
    try {
        desc.toXML(out);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

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

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

    String regex;

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

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

From source file:com.opengamma.bbg.loader.BloombergSwaptionFileLoader.java

/**
 * Little util to parse swaption tickers into a csv for further analysis.
 * @param args command line params//from   w  ww .  java  2  s.  co  m
 */
public static void main(String[] args) { // CSIGNORE
    CSVReader csvReader = null;
    CSVWriter csvWriter = null;
    try {
        csvReader = new CSVReader(new BufferedReader(new FileReader(args[0])));
        csvWriter = new CSVWriter(new BufferedWriter(new FileWriter(args[1])));
        String[] line;
        Pattern pattern = Pattern.compile("^(\\w\\w\\w).*?(\\d+)(M|Y)(\\d+)(M|Y)\\s*?(PY|RC)\\s*?(.*)$");
        BloombergReferenceDataProvider rawBbgRefDataProvider = getBloombergSecurityFileLoader();
        MongoDBValueCachingReferenceDataProvider bbgRefDataProvider = MongoCachedReferenceData
                .makeMongoProvider(rawBbgRefDataProvider, BloombergSwaptionFileLoader.class);
        while ((line = csvReader.readNext()) != null) {
            String name = line[NAME_FIELD];
            Matcher matcher = pattern.matcher(name);
            if (matcher.matches()) {
                String ccy = matcher.group(1);
                String swapTenorSize = matcher.group(2);
                String swapTenorUnit = matcher.group(3);
                String optionTenorSize = matcher.group(4);
                String optionTenorUnit = matcher.group(5);
                String payReceive = matcher.group(6);
                String distanceATM = matcher.group(7);

                String buid = "/buid/" + line[BUID_FIELD];
                String value = bbgRefDataProvider.getReferenceDataValue(buid, "TICKER");
                csvWriter.writeNext(new String[] { name, ccy, swapTenorSize, swapTenorUnit, optionTenorSize,
                        optionTenorUnit, payReceive, distanceATM, value });
            } else {
                s_logger.error("Couldn't parse " + name + " field");
            }

        }
    } catch (IOException ioe) {
        s_logger.error("Error while reading file", ioe);
    } finally {
        IOUtils.closeQuietly(csvReader);
        IOUtils.closeQuietly(csvWriter);
    }
}

From source file:fr.itinerennes.bundler.cli.GtfsItinerennesBundler.java

/**
 * @param args/*from w  w w  .  j  a  va 2  s  .  com*/
 */
public static void main(final String[] args) throws IOException {

    final GtfsItinerennesBundler main = new GtfsItinerennesBundler();
    main.parseCmdLine(args);

    ClassPathXmlApplicationContext bootCtx = null;
    ClassPathXmlApplicationContext ctx = null;
    try {
        LOGGER.info("Initialization...");
        // pre-context dynamically initialize some beans depending on program args
        bootCtx = new ClassPathXmlApplicationContext("classpath:/boot-context.xml");
        main.loadArguments(bootCtx.getBean("programArgs", Properties.class));
        bootCtx.getBean("agencyMapping", Map.class).putAll(main.agencyMapping);

        ctx = new ClassPathXmlApplicationContext(new String[] { "classpath:/application-context.xml" },
                bootCtx);
        LOGGER.info("Application context initialization finished");

        if (main.listTasks) {
            main.listTasksAndExit(ctx);
        }

        final List<AbstractTask> selectedTasks = main.verifySelectedTasksExists(ctx);
        LOGGER.info("Start tasks execution...");
        main.execute(selectedTasks);
        LOGGER.info("Tasks execution finished");
    } finally {
        IOUtils.closeQuietly(ctx);
        IOUtils.closeQuietly(bootCtx);
    }
}

From source file:hu.bme.mit.sette.run.Run.java

public static void main(String[] args) {
    LOG.debug("main() called");

    // parse properties
    Properties prop = new Properties();
    InputStream is = null;/*  ww w  .ja v  a 2s  .c  om*/

    try {
        is = new FileInputStream(SETTE_PROPERTIES);
        prop.load(is);
    } catch (IOException e) {
        System.err.println("Parsing  " + SETTE_PROPERTIES + " has failed");
        e.printStackTrace();
        System.exit(1);
    } finally {
        IOUtils.closeQuietly(is);
    }

    String[] basedirs = StringUtils.split(prop.getProperty("basedir"), '|');
    String snippetDir = prop.getProperty("snippet-dir");
    String snippetProject = prop.getProperty("snippet-project");
    String catgPath = prop.getProperty("catg");
    String catgVersionFile = prop.getProperty("catg-version-file");
    String jPETPath = prop.getProperty("jpet");
    String jPETDefaultBuildXml = prop.getProperty("jpet-default-build.xml");
    String jPETVersionFile = prop.getProperty("jpet-version-file");
    String spfPath = prop.getProperty("spf");
    String spfDefaultBuildXml = prop.getProperty("spf-default-build.xml");
    String spfVersionFile = prop.getProperty("spf-version-file");
    String outputDir = prop.getProperty("output-dir");

    Validate.notEmpty(basedirs, "At least one basedir must be specified in " + SETTE_PROPERTIES);
    Validate.notBlank(snippetDir, "The property snippet-dir must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(snippetProject, "The property snippet-project must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(catgPath, "The property catg must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(jPETPath, "The property jpet must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(spfPath, "The property spf must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(outputDir, "The property output-dir must be set in " + SETTE_PROPERTIES);

    String basedir = null;
    for (String bd : basedirs) {
        bd = StringUtils.trimToEmpty(bd);

        if (bd.startsWith("~")) {
            // Linux home
            bd = System.getProperty("user.home") + bd.substring(1);
        }

        FileValidator v = new FileValidator(new File(bd));
        v.type(FileType.DIRECTORY);

        if (v.isValid()) {
            basedir = bd;
            break;
        }
    }

    if (basedir == null) {
        System.err.println("basedir = " + Arrays.toString(basedirs));
        System.err.println("ERROR: No valid basedir was found, please check " + SETTE_PROPERTIES);
        System.exit(2);
    }

    BASEDIR = new File(basedir);
    SNIPPET_DIR = new File(basedir, snippetDir);
    SNIPPET_PROJECT = snippetProject;
    OUTPUT_DIR = new File(basedir, outputDir);

    try {
        String catgVersion = readToolVersion(new File(BASEDIR, catgVersionFile));
        if (catgVersion != null) {
            new CatgTool(new File(BASEDIR, catgPath), catgVersion);
        }

        String jPetVersion = readToolVersion(new File(BASEDIR, jPETVersionFile));
        if (jPetVersion != null) {
            new JPetTool(new File(BASEDIR, jPETPath), new File(BASEDIR, jPETDefaultBuildXml), jPetVersion);
        }

        String spfVersion = readToolVersion(new File(BASEDIR, spfVersionFile));
        if (spfVersion != null) {
            new SpfTool(new File(BASEDIR, spfPath), new File(BASEDIR, spfDefaultBuildXml), spfVersion);
        }

        // TODO stuff
        stuff(args);
    } catch (Exception e) {
        System.err.println(ExceptionUtils.getStackTrace(e));

        ValidatorException vex = (ValidatorException) e;

        for (ValidationException v : vex.getValidator().getAllExceptions()) {
            v.printStackTrace();
        }

        // System.exit(0);

        e.printStackTrace();
        System.err.println("==========");
        e.printStackTrace();

        if (e instanceof ValidatorException) {
            System.err.println("Details:");
            System.err.println(((ValidatorException) e).getFullMessage());
        } else if (e.getCause() instanceof ValidatorException) {
            System.err.println("Details:");
            System.err.println(((ValidatorException) e.getCause()).getFullMessage());
        }
    }
}

From source file:com.revo.deployr.client.example.data.io.anon.discrete.exec.RepoFileInGraphicsPlotOut.java

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

    RClient rClient = null;//  www  .  ja v a2  s . co m

    try {

        /*
         * Determine DeployR server endpoint.
         */
        String endpoint = System.getProperty("endpoint");
        log.info("[ CONFIGURATION  ] Using endpoint=" + endpoint);

        /*
         * Establish RClient connection to DeployR server.
         *
         * An RClient connection is the mandatory starting
         * point for any application using the client library.
         */
        rClient = RClientFactory.createClient(endpoint);

        log.info("[   CONNECTION   ] Established anonymous " + "connection [ RClient ].");

        /*
         * Create the AnonymousProjectExecutionOptions object
         * to specify data inputs and output to the script.
         *
         * This options object can be used to pass standard
         * execution model parameters on execution calls. All
         * fields are optional.
         *
         * See the Standard Execution Model chapter in the
         * Client Library Tutorial on the DeployR website for
         * further details.
         */
        AnonymousProjectExecutionOptions options = new AnonymousProjectExecutionOptions();

        /* 
         * Preload from the DeployR repository the following
         * data input file:
         * /testuser/example-data-io/hipStar.dat
         */
        ProjectPreloadOptions preloadDirectory = new ProjectPreloadOptions();
        preloadDirectory.filename = "hipStar.dat";
        preloadDirectory.directory = "example-data-io";
        preloadDirectory.author = "testuser";
        options.preloadDirectory = preloadDirectory;
        /*
         * Blackbox must be enabled in order for an anonymous
         * caller to request a repository-managed file (hipStar.dat)
         * to be loaded into the working directory on the execution.
         */
        options.blackbox = true;

        log.info("[   DATA INPUT   ] Repository data file input "
                + "set on execution, [ ProjectExecutionOptions.preloadDirectory ].");

        /*
         * Execute a public analytics Web service as an anonymous
         * user based on a repository-managed R script:
         * /testuser/example-data-io/dataIO.R
         */
        RScriptExecution exec = rClient.executeScript("dataIO.R", "example-data-io", "testuser", null, options);

        log.info("[   EXECUTION    ] Discrete R script " + "execution completed [ RScriptExecution ].");

        /*
         * Retrieve R graphics device plot (result) called
         * unnamedplot*.png that was generated by the execution.
         *
         * Outputs generated by an execution can be used in any
         * number of ways by client applications, including:
         *
         * 1. Use output data to perform further calculations.
         * 2. Display output data to an end-user.
         * 3. Write output data to a database.
         * 4. Pass output data along to another Web service.
         * 5. etc.
         */
        List<RProjectResult> results = exec.about().results;

        for (RProjectResult result : results) {
            log.info("[  DATA OUTPUT   ] Retrieved graphics device " + "plot output " + result.about().filename
                    + " [ RProjectResult ].");
            InputStream fis = null;
            try {
                fis = result.download();
            } catch (Exception ex) {
                log.warn("Graphics device plot " + ex);
            } finally {
                IOUtils.closeQuietly(fis);
            }
        }

    } catch (Exception ex) {
        log.warn("Unexpected runtime exception=" + ex);
    } finally {
        try {
            if (rClient != null) {
                /*
                 * Release rClient connection before application exits.
                 */
                rClient.release();
            }
        } catch (Exception fex) {
        }
    }

}

From source file:com.revo.deployr.client.example.data.io.anon.discrete.exec.EncodedDataInBinaryFileOut.java

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

    RClient rClient = null;/* w  w w  .j a  v  a 2 s.  co m*/

    try {

        /*
         * Determine DeployR server endpoint.
         */
        String endpoint = System.getProperty("endpoint");
        log.info("[ CONFIGURATION  ] Using endpoint=" + endpoint);

        /*
         * Establish RClient connection to DeployR server.
         *
         * An RClient connection is the mandatory starting
         * point for any application using the client library.
         */
        rClient = RClientFactory.createClient(endpoint);

        log.info("[   CONNECTION   ] Established anonymous " + "connection [ RClient ].");

        /*
         * Create the AnonymousProjectExecutionOptions object
         * to specify data inputs and output to the script.
         *
         * This options object can be used to pass standard
         * execution model parameters on execution calls. All
         * fields are optional.
         *
         * See the Standard Execution Model chapter in the
         * Client Library Tutorial on the DeployR website for
         * further details.
         */
        AnonymousProjectExecutionOptions options = new AnonymousProjectExecutionOptions();

        /* 
         * Simulate application generated data. This data
         * is first encoded using the RDataFactory before
         * being passed as an input on the execution.
         *
         * This encoded R input is automatically converted
         * into a workspace object before script execution.
         */
        RData generatedData = simulateGeneratedData();
        if (generatedData != null) {
            List<RData> rinputs = Arrays.asList(generatedData);
            options.rinputs = rinputs;
        }

        log.info("[   DATA INPUT   ] DeployR-encoded R input "
                + "set on execution, [ ProjectExecutionOptions.rinputs ].");

        /*
         * Execute a public analytics Web service as an anonymous
         * user based on a repository-managed R script:
         * /testuser/example-data-io/dataIO.R
         */
        RScriptExecution exec = rClient.executeScript("dataIO.R", "example-data-io", "testuser", null, options);

        log.info("[   EXECUTION    ] Discrete R script " + "execution completed [ RScriptExecution ].");

        /*
         * Retrieve the working directory file (artifact) called
         * hip.rData that was generated by the execution.
         *
         * Outputs generated by an execution can be used in any
         * number of ways by client applications, including:
         *
         * 1. Use output data to perform further calculations.
         * 2. Display output data to an end-user.
         * 3. Write output data to a database.
         * 4. Pass output data along to another Web service.
         * 5. etc.
         */
        List<RProjectFile> wdFiles = exec.about().artifacts;

        for (RProjectFile wdFile : wdFiles) {
            if (wdFile.about().filename.equals("hip.rData")) {
                log.info("[  DATA OUTPUT   ] Retrieved working directory " + "file output "
                        + wdFile.about().filename + " [ RProjectFile ].");
                InputStream fis = null;
                try {
                    fis = wdFile.download();
                } catch (Exception ex) {
                    log.warn("Working directory binary file " + ex);
                } finally {
                    IOUtils.closeQuietly(fis);
                }
            }
        }

    } catch (Exception ex) {
        log.warn("Unexpected runtime exception=" + ex);
    } finally {
        try {
            if (rClient != null) {
                /*
                 * Release rClient connection before application exits.
                 */
                rClient.release();
            }
        } catch (Exception fex) {
        }
    }

}

From source file:fr.inria.atlanmod.kyanos.benchmarks.ReferencesCounter.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);// ww w .j a v a2s  .  c  om
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output file");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(IN_EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of input EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option labelOpt = OptionBuilder.create(LABEL);
    labelOpt.setArgName("LABEL");
    labelOpt.setDescription("Label for the data set");
    labelOpt.setArgs(1);
    labelOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(outputOpt);
    options.addOption(inClassOpt);
    options.addOption(labelOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);
        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        Class<?> inClazz = ReferencesCounter.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(IN_EPACKAGE_CLASS));
        @SuppressWarnings("unused")
        EPackage inEPackage = (EPackage) inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());

        Resource sourceResource = resourceSet.getResource(sourceUri, true);

        FileWriter writer = new FileWriter(new File(commandLine.getOptionValue(OUT)));
        try {
            writer.write(commandLine.getOptionValue(LABEL));
            writer.write("\n");

            for (Iterator<EObject> iterator = sourceResource.getAllContents(); iterator.hasNext();) {
                EObject eObject = iterator.next();
                for (EStructuralFeature feature : eObject.eClass().getEAllStructuralFeatures()) {
                    if (feature.isMany() && eObject.eIsSet(feature)) {
                        EList<?> value = (EList<?>) eObject.eGet(feature);
                        //                     if (value.size() > 10) 
                        writer.write(String.format("%d\n", value.size()));
                    }
                }
            }
        } finally {
            IOUtils.closeQuietly(writer);
        }

    } catch (ParseException e) {
        showError(e.toString());
        showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        showError(e.toString());
    }
}

From source file:com.revo.deployr.client.example.data.io.anon.discrete.exec.ExternalDataInDataFileOut.java

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

    RClient rClient = null;//from  w ww . j av  a  2 s  .  c o m

    try {

        /*
         * Determine DeployR server endpoint.
         */
        String endpoint = System.getProperty("endpoint");
        log.info("[ CONFIGURATION  ] Using endpoint=" + endpoint);

        /*
         * Establish RClient connection to DeployR server.
         *
         * An RClient connection is the mandatory starting
         * point for any application using the client library.
         */
        rClient = RClientFactory.createClient(endpoint);

        log.info("[   CONNECTION   ] Established anonymous " + "connection [ RClient ].");

        /*
         * Create the AnonymousProjectExecutionOptions object
         * to specify data inputs and output to the script.
         *
         * This options object can be used to pass standard
         * execution model parameters on execution calls. All
         * fields are optional.
         *
         * See the Standard Execution Model chapter in the
         * Client Library Tutorial on the DeployR website for
         * further details.
         */
        AnonymousProjectExecutionOptions options = new AnonymousProjectExecutionOptions();

        /* 
         * Load an R object literal "hipStarUrl" into the
         * workspace prior to script execution.
         *
         * The R script checks for the existence of "hipStarUrl"
         * in the workspace and if present uses the URL path
         * to load the Hipparcos star dataset from the DAT file
         * at that location.
         */
        RData hipStarUrl = RDataFactory.createString("hipStarUrl", HIP_DAT_URL);
        List<RData> rinputs = Arrays.asList(hipStarUrl);
        options.rinputs = rinputs;

        log.info("[   DATA INPUT   ] External data source input "
                + "set on execution, [ ProjectPreloadOptions.rinputs ].");

        /*
         * Execute a public analytics Web service as an anonymous
         * user based on a repository-managed R script:
         * /testuser/example-data-io/dataIO.R
         */
        RScriptExecution exec = rClient.executeScript("dataIO.R", "example-data-io", "testuser", null, options);

        log.info("[   EXECUTION    ] Discrete R script " + "execution completed [ RScriptExecution ].");

        /*
         * Retrieve the working directory file (artifact) called
         * hip.csv that was generated by the execution.
         *
         * Outputs generated by an execution can be used in any
         * number of ways by client applications, including:
         *
         * 1. Use output data to perform further calculations.
         * 2. Display output data to an end-user.
         * 3. Write output data to a database.
         * 4. Pass output data along to another Web service.
         * 5. etc.
         */
        List<RProjectFile> wdFiles = exec.about().artifacts;

        for (RProjectFile wdFile : wdFiles) {
            if (wdFile.about().filename.equals("hip.csv")) {
                log.info("[  DATA OUTPUT   ] Retrieved working directory " + "file output "
                        + wdFile.about().filename + " [ RProjectFile ].");
                InputStream fis = null;
                try {
                    fis = wdFile.download();
                } catch (Exception ex) {
                    log.warn("Working directory data file " + ex);
                } finally {
                    IOUtils.closeQuietly(fis);
                }
            }
        }

    } catch (Exception ex) {
        log.warn("Unexpected runtime exception=" + ex);
    } finally {
        try {
            if (rClient != null) {
                /*
                 * Release rClient connection before application exits.
                 */
                rClient.release();
            }
        } catch (Exception fex) {
        }
    }

}

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

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

    try {/*w w  w. j a v  a  2  s . com*/
        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;

}