Example usage for java.io ByteArrayInputStream ByteArrayInputStream

List of usage examples for java.io ByteArrayInputStream ByteArrayInputStream

Introduction

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

Prototype

public ByteArrayInputStream(byte buf[]) 

Source Link

Document

Creates a ByteArrayInputStream so that it uses buf as its buffer array.

Usage

From source file:net.sf.mcf2pdf.Main.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();

    Option o = OptionBuilder.hasArg().isRequired()
            .withDescription("Installation location of My CEWE Photobook. REQUIRED.").create('i');
    options.addOption(o);/*from w w w.  jav a  2  s . c  om*/
    options.addOption("h", false, "Prints this help and exits.");
    options.addOption("t", true, "Location of MCF temporary files.");
    options.addOption("w", true, "Location for temporary images generated during conversion.");
    options.addOption("r", true, "Sets the resolution to use for page rendering, in DPI. Default is 150.");
    options.addOption("n", true, "Sets the page number to render up to. Default renders all pages.");
    options.addOption("b", false, "Prevents rendering of binding between double pages.");
    options.addOption("x", false, "Generates only XSL-FO content instead of PDF content.");
    options.addOption("q", false, "Quiet mode - only errors are logged.");
    options.addOption("d", false, "Enables debugging logging output.");

    CommandLine cl;
    try {
        CommandLineParser parser = new PosixParser();
        cl = parser.parse(options, args);
    } catch (ParseException pe) {
        printUsage(options, pe);
        System.exit(3);
        return;
    }

    if (cl.hasOption("h")) {
        printUsage(options, null);
        return;
    }

    if (cl.getArgs().length != 2) {
        printUsage(options,
                new ParseException("INFILE and OUTFILE must be specified. Arguments were: " + cl.getArgList()));
        System.exit(3);
        return;
    }

    File installDir = new File(cl.getOptionValue("i"));
    if (!installDir.isDirectory()) {
        printUsage(options, new ParseException("Specified installation directory does not exist."));
        System.exit(3);
        return;
    }

    File tempDir = null;
    String sTempDir = cl.getOptionValue("t");
    if (sTempDir == null) {
        tempDir = new File(new File(System.getProperty("user.home")), ".mcf");
        if (!tempDir.isDirectory()) {
            printUsage(options, new ParseException("MCF temporary location not specified and default location "
                    + tempDir + " does not exist."));
            System.exit(3);
            return;
        }
    } else {
        tempDir = new File(sTempDir);
        if (!tempDir.isDirectory()) {
            printUsage(options, new ParseException("Specified temporary location does not exist."));
            System.exit(3);
            return;
        }
    }

    File mcfFile = new File(cl.getArgs()[0]);
    if (!mcfFile.isFile()) {
        printUsage(options, new ParseException("MCF input file does not exist."));
        System.exit(3);
        return;
    }
    mcfFile = mcfFile.getAbsoluteFile();

    File tempImages = new File(new File(System.getProperty("user.home")), ".mcf2pdf");
    if (cl.hasOption("w")) {
        tempImages = new File(cl.getOptionValue("w"));
        if (!tempImages.mkdirs() && !tempImages.isDirectory()) {
            printUsage(options,
                    new ParseException("Specified working dir does not exist and could not be created."));
            System.exit(3);
            return;
        }
    }

    int dpi = 150;
    if (cl.hasOption("r")) {
        try {
            dpi = Integer.valueOf(cl.getOptionValue("r")).intValue();
            if (dpi < 30 || dpi > 600)
                throw new IllegalArgumentException();
        } catch (Exception e) {
            printUsage(options,
                    new ParseException("Parameter for option -r must be an integer between 30 and 600."));
        }
    }

    int maxPageNo = -1;
    if (cl.hasOption("n")) {
        try {
            maxPageNo = Integer.valueOf(cl.getOptionValue("n")).intValue();
            if (maxPageNo < 0)
                throw new IllegalArgumentException();
        } catch (Exception e) {
            printUsage(options, new ParseException("Parameter for option -n must be an integer >= 0."));
        }
    }

    boolean binding = true;
    if (cl.hasOption("b")) {
        binding = false;
    }

    OutputStream finalOut;
    if (cl.getArgs()[1].equals("-"))
        finalOut = System.out;
    else {
        try {
            finalOut = new FileOutputStream(cl.getArgs()[1]);
        } catch (IOException e) {
            printUsage(options, new ParseException("Output file could not be created."));
            System.exit(3);
            return;
        }
    }

    // configure logging, if no system property is present
    if (System.getProperty("log4j.configuration") == null) {
        PropertyConfigurator.configure(Main.class.getClassLoader().getResource("log4j.properties"));

        Logger.getRootLogger().setLevel(Level.INFO);
        if (cl.hasOption("q"))
            Logger.getRootLogger().setLevel(Level.ERROR);
        if (cl.hasOption("d"))
            Logger.getRootLogger().setLevel(Level.DEBUG);
    }

    // start conversion to XSL-FO
    // if -x is specified, this is the only thing we do
    OutputStream xslFoOut;
    if (cl.hasOption("x"))
        xslFoOut = finalOut;
    else
        xslFoOut = new ByteArrayOutputStream();

    Log log = LogFactory.getLog(Main.class);

    try {
        new Mcf2FoConverter(installDir, tempDir, tempImages).convert(mcfFile, xslFoOut, dpi, binding,
                maxPageNo);
        xslFoOut.flush();

        if (!cl.hasOption("x")) {
            // convert to PDF
            log.debug("Converting XSL-FO data to PDF");
            byte[] data = ((ByteArrayOutputStream) xslFoOut).toByteArray();
            PdfUtil.convertFO2PDF(new ByteArrayInputStream(data), finalOut, dpi);
            finalOut.flush();
        }
    } catch (Exception e) {
        log.error("An exception has occured", e);
        System.exit(1);
        return;
    } finally {
        if (finalOut instanceof FileOutputStream) {
            try {
                finalOut.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:ca.uqac.info.trace.execution.BabelTrace.java

/**
 * Main program loop//from w  w w. j  av a 2  s . com
 * @param args
 */
public static void main(String[] args) {
    String trace_type = "", tool_name = "";
    String trace_in_filename = "", formula_in_filename = "";
    String out_formula = "", out_trace = "", out_signature = "", output_dir = "";
    File formula_in, trace_in;
    trace_in = null;
    Operator op = null;
    EventTrace trace = null;
    boolean run_tool = false, show_command = false;

    // Parse command line arguments
    Options options = setupOptions();
    CommandLine c_line = setupCommandLine(args, options);
    assert c_line != null;
    if (c_line.hasOption("version")) {
        System.out.println("\nBabelTrace build " + BUILD_STRING);
        System.out.println("(C) 2012-2013 Sylvain Hall et al., Universit du Qubec  Chicoutimi");
        System.out.println("This program comes with ABSOLUTELY NO WARRANTY.");
        System.out.println("This is a free software, and you are welcome to redistribute it");
        System.out.println("under certain conditions. See the file COPYING for details.\n");
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("t"))
        trace_in_filename = c_line.getOptionValue("t");
    else {
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    if (c_line.hasOption("f"))
        formula_in_filename = c_line.getOptionValue("f");
    else {
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    if (c_line.hasOption("i"))
        trace_type = c_line.getOptionValue("i");
    else {
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    if (c_line.hasOption("c"))
        tool_name = c_line.getOptionValue("c");
    else {
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    if (c_line.hasOption("o"))
        output_dir = c_line.getOptionValue("o");
    else {
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    if (c_line.hasOption("b")) {
        run_tool = false;
        show_command = true;
    }
    if (c_line.hasOption("r")) {
        run_tool = true;
        show_command = false;
    }

    // Read input formula
    formula_in = new File(formula_in_filename);
    if (!formula_in.exists()) {
        System.err.println("Error reading " + formula_in_filename);
        System.exit(ERR_IO);
    }
    try {
        out_formula = ca.uqac.info.util.FileReadWrite.readFile(formula_in_filename);
    } catch (java.io.FileNotFoundException e) {
        System.err.println("File not found: " + formula_in_filename);
        System.exit(ERR_IO);
    } catch (java.io.IOException e) {
        System.err.println("IO Exception: " + formula_in_filename);
        e.printStackTrace();
        System.exit(ERR_IO);
    }

    // Get trace file
    trace_in = new File(trace_in_filename);

    // Get execution
    Execution ex = getExecution(tool_name);

    // Get filenames for each part
    String base_filename = FileReadWrite.baseName(trace_in) + "." + FileReadWrite.baseName(formula_in);
    String trace_filename = output_dir + "/" + base_filename + "." + ex.getTraceExtension();
    String formula_filename = output_dir + "/" + base_filename + "." + ex.getFormulaExtension();
    String signature_filename = output_dir + "/" + base_filename + "." + ex.getSignatureExtension();

    // Setup execution environment
    ex.setProperty(formula_filename);
    ex.setSignature(signature_filename);
    ex.setTrace(trace_filename);

    // Show command lines and leave
    if (show_command) {
        String[] cl = ex.getCommandLines();
        for (String c : cl) {
            System.out.println(c);
        }
        System.exit(ERR_OK);
    }

    // Initialize the translator
    Translator tt = getTraceTranslator(tool_name);
    if (tt == null) {
        System.err.println("Error: unrecognized conversion format \"" + tool_name + "\"");
        System.exit(ERR_NO_SUCH_TOOL);
    }
    tt.setTrace(trace);

    // Parse the trace
    TraceReader t_read = getTraceReader(trace_type);
    try {
        trace = t_read.parseEventTrace(new FileInputStream(trace_in));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        System.exit(ERR_IO);
    }

    // Get the formula as an operator
    try {
        op = Operator.parseFromString(out_formula);
    } catch (ParseException e) {
        System.err.println("Error parsing the input formula");
        System.exit(ERR_PARSE);
    }
    assert op != null;

    // Does the formula require flat messages and formulas?
    if (tt.requiresFlat()) {
        // Convert the first-order formula to a propositional one
        FlatTranslator pt = new FlatTranslator();
        pt.setFormula(op);
        pt.setTrace(trace);
        // Flatten the trace
        String tr_trans = pt.translateTrace();
        TraceReader xtr = new XmlTraceReader();
        trace = xtr.parseEventTrace(new ByteArrayInputStream(tr_trans.getBytes()));
        // Flatten the formula
        String op_trans = pt.translateFormula();
        try {
            op = Operator.parseFromString(op_trans);
        } catch (ParseException e) {
            System.err.println("Error parsing the formula once translated to propositional");
            System.exit(ERR_PARSE);
        }
    }

    // Is the formula first-order while the tool requires propositional?
    if (tt.requiresPropositional() && FirstOrderDetector.isFirstOrder(op)) {
        // Convert the first-order formula to a propositional one
        PropositionalTranslator pt = new PropositionalTranslator();
        pt.setFormula(op);
        pt.setTrace(trace);
        String op_trans = pt.translateFormula();
        try {
            op = Operator.parseFromString(op_trans);
        } catch (ParseException e) {
            System.err.println("Error parsing the formula once translated to propositional");
            System.exit(ERR_PARSE);
        }
        // We also convert equalities between constants produced by the translator
        // into Booleans
        ConstantConverter cc = new ConstantConverter();
        op.accept(cc);
        op = cc.getFormula();
        // And then propagate those constants
        UnitPropagator up = new UnitPropagator();
        op.accept(up);
        op = up.getFormula();
    }

    // Convert
    tt.setTrace(trace);
    tt.setFormula(op);
    tt.translateAll();
    out_trace = tt.getTraceFile();
    out_formula = tt.getFormulaFile();
    out_signature = tt.getSignatureFile();

    // Save conversions to files
    try {
        if (!out_trace.isEmpty()) {
            ca.uqac.info.util.FileReadWrite.writeToFile(trace_filename, out_trace);
        }
        if (!out_formula.isEmpty()) {
            ca.uqac.info.util.FileReadWrite.writeToFile(formula_filename, out_formula);
        }
        if (!out_signature.isEmpty()) {
            ca.uqac.info.util.FileReadWrite.writeToFile(signature_filename, out_signature);
        }
    } catch (java.io.IOException e) {
        System.err.println("Error writing to file");
        System.err.println(e.getMessage());
        System.exit(ERR_IO);
    }

    // Now that all conversions have been made, run the tool
    if (run_tool) {
        try {
            ex.run();
        } catch (Execution.CommandLineException e) {
            System.err.println("Error running command");
            System.exit(ERR_TOOL_EXECUTION);
        }

        // Print results
        ReturnVerdict ex_retval = ex.getReturnVerdict();
        float ex_time = (float) ex.getTime() / (float) 1000000000; // We show seconds, not s
        float ex_memory = (float) ex.getMemory() / (float) 1024; // We show megabytes, not bytes
        System.out.printf("%s,%.2f,%.2f\n", ex_retval, ex_time, ex_memory);

        // If an error occurred, dump it
        if (ex_retval == ReturnVerdict.ERROR) {
            System.err.println("Error while executing " + tool_name);
            System.err.println("Command line(s):");
            for (String cl : ex.getCommandLines()) {
                System.err.println(cl);
            }
            System.err.println("Below is the string returned by the tool\n");
            System.err.println(ex.getErrorString());
            System.exit(ERR_TOOL_EXECUTION);
        }
    }

    // Quit
    System.exit(ERR_OK);
}

From source file:net.padaf.xmpbox.parser.XMLValueTypeDescriptionManager.java

/**
 * Sample of using to write/read information
 * //w ww  .jav  a  2 s . co m
 * @param args
 *            not used
 * @throws BuildPDFAExtensionSchemaDescriptionException
 *             When errors during building/reading xml file
 */
public static void main(String[] args) throws BuildPDFAExtensionSchemaDescriptionException {
    XMLValueTypeDescriptionManager vtMaker = new XMLValueTypeDescriptionManager();

    // add Descriptions
    for (int i = 0; i < 3; i++) {
        vtMaker.addValueTypeDescription("testType" + i, "nsURI" + i, "prefix" + i, "description" + i);

    }
    List<FieldDescription> fieldSample = new ArrayList<FieldDescription>();
    for (int i = 0; i < 2; i++) {
        fieldSample.add(new FieldDescription("fieldName" + i, "valueType" + i, "description" + i));
    }
    vtMaker.addValueTypeDescription("testTypeField", "http://test.withfield.com/vt/", "prefTest",
            " value type description", fieldSample);

    // Display XML conversion
    System.out.println("Display XML Result:");
    vtMaker.toXML(System.out);

    // Sample to show how to build object from XML file
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    vtMaker.toXML(bos);
    IOUtils.closeQuietly(bos);

    // emulate a new reading
    InputStream is = new ByteArrayInputStream(bos.toByteArray());
    vtMaker = new XMLValueTypeDescriptionManager();
    vtMaker.loadListFromXML(is);
    List<ValueTypeDescription> result = vtMaker.getValueTypesDescriptionList();
    System.out.println();
    System.out.println();
    System.out.println("Result of XML Loading :");
    for (ValueTypeDescription propertyDescription : result) {
        System.out.println(propertyDescription.getType() + " :" + propertyDescription.getDescription());
        if (propertyDescription.getFields() != null) {
            Iterator<FieldDescription> fit = propertyDescription.getFields().iterator();
            FieldDescription field;
            while (fit.hasNext()) {
                field = fit.next();
                System.out.println("Field " + field.getName() + " :" + field.getValueType());
            }
        }
    }

}

From source file:com.netscape.cmstools.OCSPClient.java

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

    Options options = createOptions();//ww  w  .  j  av  a2  s. c  o m
    CommandLine cmd = null;

    try {
        CommandLineParser parser = new PosixParser();
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        printError(e);
        System.exit(1);
    }

    if (cmd.hasOption("help")) {
        printHelp();
        System.exit(0);
    }

    boolean verbose = cmd.hasOption("v");

    String databaseDir = cmd.getOptionValue("d", ".");
    String hostname = cmd.getOptionValue("h", InetAddress.getLocalHost().getCanonicalHostName());
    int port = Integer.parseInt(cmd.getOptionValue("p", "8080"));
    String path = cmd.getOptionValue("t", "/ocsp/ee/ocsp");
    String caNickname = cmd.getOptionValue("c", "CA Signing Certificate");
    int times = Integer.parseInt(cmd.getOptionValue("n", "1"));

    String input = cmd.getOptionValue("input");
    String serial = cmd.getOptionValue("serial");
    String output = cmd.getOptionValue("output");

    if (times < 1) {
        printError("Invalid number of submissions");
        System.exit(1);
    }

    try {
        if (verbose)
            System.out.println("Initializing security database");
        CryptoManager.initialize(databaseDir);

        String url = "http://" + hostname + ":" + port + path;

        OCSPProcessor processor = new OCSPProcessor();
        processor.setVerbose(verbose);

        OCSPRequest request;
        if (serial != null) {
            if (verbose)
                System.out.println("Creating request for serial number " + serial);

            BigInteger serialNumber = new BigInteger(serial);
            request = processor.createRequest(caNickname, serialNumber);

        } else if (input != null) {
            if (verbose)
                System.out.println("Loading request from " + input);

            try (FileInputStream in = new FileInputStream(input)) {
                byte[] data = new byte[in.available()];
                in.read(data);
                request = processor.createRequest(data);
            }

        } else {
            throw new Exception("Missing serial number or input file.");
        }

        OCSPResponse response = null;
        for (int i = 0; i < times; i++) {

            if (verbose)
                System.out.println("Submitting OCSP request");
            response = processor.submitRequest(url, request);

            ResponseBytes bytes = response.getResponseBytes();
            BasicOCSPResponse basic = (BasicOCSPResponse) BasicOCSPResponse.getTemplate()
                    .decode(new ByteArrayInputStream(bytes.getResponse().toByteArray()));

            ResponseData rd = basic.getResponseData();
            for (int j = 0; j < rd.getResponseCount(); j++) {
                SingleResponse sr = rd.getResponseAt(j);

                if (sr == null) {
                    throw new Exception("No OCSP Response data.");
                }

                System.out.println("CertID.serialNumber=" + sr.getCertID().getSerialNumber());

                CertStatus status = sr.getCertStatus();
                if (status instanceof GoodInfo) {
                    System.out.println("CertStatus=Good");

                } else if (status instanceof UnknownInfo) {
                    System.out.println("CertStatus=Unknown");

                } else if (status instanceof RevokedInfo) {
                    System.out.println("CertStatus=Revoked");
                }
            }
        }

        if (output != null) {
            if (verbose)
                System.out.println("Storing response into " + output);

            try (FileOutputStream out = new FileOutputStream(output)) {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                response.encode(os);
                out.write(os.toByteArray());
            }

            System.out.println("Success: Output " + output);
        }

    } catch (Exception e) {
        if (verbose)
            e.printStackTrace();
        printError(e);
        System.exit(1);
    }
}

From source file:mitm.common.security.ca.handlers.ejbca.ws.EjbcaWSClient.java

public static void main(String args[]) throws Exception {
    BasicConfigurator.configure();/*  w w w.jav a2s  .  co m*/

    JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();

    factory.setServiceClass(EjbcaWS.class);
    factory.setAddress("https://192.168.178.113:8443/ejbca/ejbcaws/ejbcaws");
    factory.setServiceName(SERVICE_NAME);

    EjbcaWS client = (EjbcaWS) factory.create();

    Client proxy = ClientProxy.getClient(client);
    HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
    TLSClientParameters tlsClientParameters = new TLSClientParameters();

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

    java.security.KeyStore keyStore = java.security.KeyStore.getInstance("PKCS12");
    InputStream keyInput = new FileInputStream("/home/martijn/temp/superadmin.p12");

    String password = "ejbca";

    keyStore.load(keyInput, password.toCharArray());
    keyInput.close();
    keyManagerFactory.init(keyStore, password.toCharArray());

    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    tlsClientParameters.setDisableCNCheck(true);

    tlsClientParameters.setKeyManagers(keyManagers);

    X509TrustManager trustAll = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
                throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    trustManagerFactory.init(new KeyStoreLoader().loadKeyStore(new File("/home/martijn/temp/truststore.jks"),
            "changeit".toCharArray()));

    tlsClientParameters.setTrustManagers(new TrustManager[] { trustAll });
    //tlsClientParameters.setTrustManagers(trustManagerFactory.getTrustManagers());

    conduit.setTlsClientParameters(tlsClientParameters);

    System.out.println(client.getEjbcaVersion());

    UserDataVOWS userData = new UserDataVOWS();

    userData.setEmail("test@example.com");
    userData.setUsername("test@example.com");
    //userData.setPassword("test@example.com");
    userData.setSubjectDN("CN=test@example.com");
    userData.setSubjectAltName("rfc822Name=test@example.com");
    userData.setEndEntityProfileName("test");
    userData.setCaName("AdminCA1");
    userData.setCertificateProfileName("ENDUSER");
    userData.setStatus(EJBCAConst.STATUS_NEW);
    userData.setTokenType(EJBCAConst.TOKEN_TYPE_USERGENERATED);

    try {
        //client.editUser(userData);

        SecurityFactory securityFactory = SecurityFactoryFactory.getSecurityFactory();

        SecureRandom randomSource = securityFactory.createSecureRandom();

        KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA");

        keyPairGenerator.initialize(2048, randomSource);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X500PrincipalBuilder builder = new X500PrincipalBuilder();

        builder.setCommonName("john doe");
        builder.setEmail("test@example.com");

        PKCS10CertificationRequestBuilder requestBuilder = new PKCS10CertificationRequestBuilder(
                X500PrincipalUtils.toX500Name(builder.buildPrincipal()),
                SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

        PKCS10CertificationRequest pkcs10 = requestBuilder
                .build(getContentSigner("SHA1WithRSA", keyPair.getPrivate()));

        String base64PKCS10 = Base64Utils.encode(pkcs10.getEncoded());

        CertificateResponse certificateResponse = client.certificateRequest(userData, base64PKCS10,
                EJBCAConst.CERT_REQ_TYPE_PKCS10, null, EJBCAConst.RESPONSETYPE_CERTIFICATE);

        if (certificateResponse != null && certificateResponse.getData() != null) {
            /*
             * The result is a base64 encoded certificate 
             */
            Collection<X509Certificate> certificates = CertificateUtils.readX509Certificates(
                    new ByteArrayInputStream(Base64.decode(certificateResponse.getData())));

            if (CollectionUtils.isNotEmpty(certificates)) {
                for (X509Certificate certificate : certificates) {
                    System.out.println(certificate);
                }
            } else {
                System.out.println("No certificates found");
            }
        } else {
            System.out.println("certificateResponse is empty");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:act.installer.pubchem.PubchemSynonymFinder.java

public static void main(String[] args) throws Exception {
    org.apache.commons.cli.Options opts = new org.apache.commons.cli.Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//from w w  w  .  j  ava  2s. c om
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    File rocksDBFile = new File(cl.getOptionValue(OPTION_INDEX_PATH));
    if (!rocksDBFile.isDirectory()) {
        System.err.format("Index directory does not exist or is not a directory at '%s'",
                rocksDBFile.getAbsolutePath());
        HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    List<String> compoundIds = null;
    if (cl.hasOption(OPTION_PUBCHEM_COMPOUND_ID)) {
        compoundIds = Collections.singletonList(cl.getOptionValue(OPTION_PUBCHEM_COMPOUND_ID));
    } else if (cl.hasOption(OPTION_IDS_FILE)) {
        File idsFile = new File(cl.getOptionValue(OPTION_IDS_FILE));
        if (!idsFile.exists()) {
            System.err.format("Cannot find Pubchem CIDs file at %s", idsFile.getAbsolutePath());
            HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                    true);
            System.exit(1);
        }

        compoundIds = getCIDsFromFile(idsFile);

        if (compoundIds.size() == 0) {
            System.err.format("Found zero Pubchem CIDs to process in file at '%s', exiting",
                    idsFile.getAbsolutePath());
            HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                    true);
            System.exit(1);
        }
    } else {
        System.err.format("Must specify one of '%s' or '%s'; index is too big to print all synonyms.",
                OPTION_PUBCHEM_COMPOUND_ID, OPTION_IDS_FILE);
        HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    // Run a quick check to warn users of malformed ids.
    compoundIds.forEach(x -> {
        if (!PC_CID_PATTERN.matcher(x).matches()) { // Use matches() for complete matching.
            LOGGER.warn("Specified compound id does not match expected format: %s", x);
        }
    });

    LOGGER.info("Opening DB and searching for %d Pubchem CIDs", compoundIds.size());
    Pair<RocksDB, Map<PubchemTTLMerger.COLUMN_FAMILIES, ColumnFamilyHandle>> dbAndHandles = null;
    Map<String, PubchemSynonyms> results = new LinkedHashMap<>(compoundIds.size());
    try {
        dbAndHandles = PubchemTTLMerger.openExistingRocksDB(rocksDBFile);
        RocksDB db = dbAndHandles.getLeft();
        ColumnFamilyHandle cidToSynonymsCfh = dbAndHandles.getRight()
                .get(PubchemTTLMerger.COLUMN_FAMILIES.CID_TO_SYNONYMS);

        for (String cid : compoundIds) {
            PubchemSynonyms synonyms = null;
            byte[] val = db.get(cidToSynonymsCfh, cid.getBytes(UTF8));
            if (val != null) {
                ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(val));
                // We're relying on our use of a one-value-type per index model here so we can skip the instanceof check.
                synonyms = (PubchemSynonyms) oi.readObject();
            } else {
                LOGGER.warn("No synonyms available for compound id '%s'", cid);
            }
            results.put(cid, synonyms);
        }
    } finally {
        if (dbAndHandles != null) {
            dbAndHandles.getLeft().close();
        }
    }

    try (OutputStream outputStream = cl.hasOption(OPTION_OUTPUT)
            ? new FileOutputStream(cl.getOptionValue(OPTION_OUTPUT))
            : System.out) {
        OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValue(outputStream, results);
        new OutputStreamWriter(outputStream).append('\n');
    }
    LOGGER.info("Done searching for Pubchem synonyms");
}

From source file:Main.java

public static ByteArrayInputStream toStream(String str) {
    return new ByteArrayInputStream(str.getBytes());
}

From source file:marytts.tools.analysis.CopySynthesis.java

/**
 * @param args/*from  w  w w. j a v a2 s  .c om*/
 */
public static void main(String[] args) throws Exception {
    String wavFilename = null;
    String labFilename = null;
    String pitchFilename = null;
    String textFilename = null;

    String locale = System.getProperty("locale");
    if (locale == null) {
        throw new IllegalArgumentException("No locale given (-Dlocale=...)");
    }

    for (String arg : args) {
        if (arg.endsWith(".txt"))
            textFilename = arg;
        else if (arg.endsWith(".wav"))
            wavFilename = arg;
        else if (arg.endsWith(".ptc"))
            pitchFilename = arg;
        else if (arg.endsWith(".lab"))
            labFilename = arg;
        else
            throw new IllegalArgumentException("Don't know how to treat argument: " + arg);
    }

    // The intonation contour
    double[] contour = null;
    double frameShiftTime = -1;
    if (pitchFilename == null) { // need to create pitch contour from wav file 
        if (wavFilename == null) {
            throw new IllegalArgumentException("Need either a pitch file or a wav file");
        }
        AudioInputStream ais = AudioSystem.getAudioInputStream(new File(wavFilename));
        AudioDoubleDataSource audio = new AudioDoubleDataSource(ais);
        PitchFileHeader params = new PitchFileHeader();
        params.fs = (int) ais.getFormat().getSampleRate();
        F0TrackerAutocorrelationHeuristic tracker = new F0TrackerAutocorrelationHeuristic(params);
        tracker.pitchAnalyze(audio);
        frameShiftTime = tracker.getSkipSizeInSeconds();
        contour = tracker.getF0Contour();
    } else { // have a pitch file -- ignore any wav file
        PitchReaderWriter f0rw = new PitchReaderWriter(pitchFilename);
        if (f0rw.contour == null) {
            throw new NullPointerException("Cannot read f0 contour from " + pitchFilename);
        }
        contour = f0rw.contour;
        frameShiftTime = f0rw.header.skipSizeInSeconds;
    }
    assert contour != null;
    assert frameShiftTime > 0;

    // The ALLOPHONES data and labels
    if (labFilename == null) {
        throw new IllegalArgumentException("No label file given");
    }
    if (textFilename == null) {
        throw new IllegalArgumentException("No text file given");
    }
    MaryTranscriptionAligner aligner = new MaryTranscriptionAligner();
    aligner.SetEnsureInitialBoundary(false);
    String labels = MaryTranscriptionAligner.readLabelFile(aligner.getEntrySeparator(),
            aligner.getEnsureInitialBoundary(), labFilename);
    MaryHttpClient mary = new MaryHttpClient();
    String text = FileUtils.readFileToString(new File(textFilename), "ASCII");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mary.process(text, "TEXT", "ALLOPHONES", locale, null, null, baos);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(true);
    DocumentBuilder builder = docFactory.newDocumentBuilder();
    Document doc = builder.parse(bais);
    aligner.alignXmlTranscriptions(doc, labels);
    assert doc != null;

    // durations
    double[] endTimes = new LabelfileDoubleDataSource(new File(labFilename)).getAllData();
    assert endTimes.length == labels.split(Pattern.quote(aligner.getEntrySeparator())).length;

    // Now add durations and f0 targets to document
    double prevEnd = 0;
    NodeIterator ni = MaryDomUtils.createNodeIterator(doc, MaryXML.PHONE, MaryXML.BOUNDARY);
    for (int i = 0; i < endTimes.length; i++) {
        Element e = (Element) ni.nextNode();
        if (e == null)
            throw new IllegalStateException("More durations than elements -- this should not happen!");
        double durInSeconds = endTimes[i] - prevEnd;
        int durInMillis = (int) (1000 * durInSeconds);
        if (e.getTagName().equals(MaryXML.PHONE)) {
            e.setAttribute("d", String.valueOf(durInMillis));
            e.setAttribute("end", new Formatter(Locale.US).format("%.3f", endTimes[i]).toString());
            // f0 targets at beginning, mid, and end of phone
            StringBuilder f0String = new StringBuilder();
            double startF0 = getF0(contour, frameShiftTime, prevEnd);
            if (startF0 != 0 && !Double.isNaN(startF0)) {
                f0String.append("(0,").append((int) startF0).append(")");
            }
            double midF0 = getF0(contour, frameShiftTime, prevEnd + 0.5 * durInSeconds);
            if (midF0 != 0 && !Double.isNaN(midF0)) {
                f0String.append("(50,").append((int) midF0).append(")");
            }
            double endF0 = getF0(contour, frameShiftTime, endTimes[i]);
            if (endF0 != 0 && !Double.isNaN(endF0)) {
                f0String.append("(100,").append((int) endF0).append(")");
            }
            if (f0String.length() > 0) {
                e.setAttribute("f0", f0String.toString());
            }
        } else { // boundary
            e.setAttribute("duration", String.valueOf(durInMillis));
        }
        prevEnd = endTimes[i];
    }
    if (ni.nextNode() != null) {
        throw new IllegalStateException("More elements than durations -- this should not happen!");
    }

    // TODO: add pitch values

    String acoustparams = DomUtils.document2String(doc);
    System.out.println("ACOUSTPARAMS:");
    System.out.println(acoustparams);
}

From source file:Main.java

private static InputStream stream(String contents) {
    return new ByteArrayInputStream(contents.getBytes());
}

From source file:Main.java

public static InputStream bytes2Stream(byte[] buf) {
    return new ByteArrayInputStream(buf);
}