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

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

Introduction

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

Prototype

public static void write(StringBuffer data, OutputStream output, String encoding) throws IOException 

Source Link

Document

Writes chars from a StringBuffer to bytes on an OutputStream using the specified character encoding.

Usage

From source file:com.evolveum.midpoint.testing.model.client.sample.RunScript.java

/**
* @param args/*from w  w w.  j  a  va 2s .c om*/
*/
public static void main(String[] args) {
    try {

        Options options = new Options();
        options.addOption(OPT_HELP, "help", false, "Print this help information");
        options.addOption(OPT_SCRIPT, "script", true, "Script file (XML for the moment)");
        options.addOption(OPT_URL, true, "Endpoint URL (default: " + DEFAULT_ENDPOINT_URL + ")");
        options.addOption(OPT_USER, "user", true, "User name (default: " + ADM_USERNAME + ")");
        options.addOption(OPT_PASSWORD, "password", true, "Password");
        options.addOption(OPT_FILE_FOR_DATA, "file-for-data", true,
                "Name of the file to write resulting XML data into");
        options.addOption(OPT_FILE_FOR_CONSOLE, "file-for-console", true,
                "Name of the file to write resulting console output into");
        options.addOption(OPT_FILE_FOR_RESULT, "file-for-result", true,
                "Name of the file to write operation result into");
        options.addOption(OPT_HIDE_DATA, "hide-data", false, "Don't display data output");
        options.addOption(OPT_HIDE_SCRIPT, "hide-script", false, "Don't display input script");
        options.addOption(OPT_HIDE_CONSOLE, "hide-console", false, "Don't display console output");
        options.addOption(OPT_HIDE_RESULT, "hide-result", false,
                "Don't display detailed operation result (default: showing if not SUCCESS)");
        options.addOption(OPT_SHOW_RESULT, "show-result", false,
                "Always show detailed operation result (default: showing if not SUCCESS)");
        options.addOption(OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator()
                .withDescription("use value for given property").create("D"));
        CommandLineParser parser = new GnuParser();
        CommandLine cmdline = parser.parse(options, args);

        if (!cmdline.hasOption(OPT_SCRIPT) || cmdline.hasOption("h")) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("runscript", options);
            System.exit(0);
        }

        ExecuteScriptsType request = new ExecuteScriptsType();
        String script = readXmlFile(cmdline.getOptionValue(OPT_SCRIPT));
        script = replaceParameters(script, cmdline.getOptionProperties("D"));
        request.setMslScripts(script); // todo fix this hack
        ExecuteScriptsOptionsType optionsType = new ExecuteScriptsOptionsType();
        optionsType.setOutputFormat(OutputFormatType.MSL); // todo fix this hack
        request.setOptions(optionsType);

        if (!cmdline.hasOption(OPT_HIDE_SCRIPT)) {
            System.out.println("\nScript to execute:\n" + script);
        }
        System.out.println("=================================================================");

        ModelPortType modelPort = createModelPort(cmdline);

        ExecuteScriptsResponseType response = modelPort.executeScripts(request);

        System.out.println("=================================================================");

        for (SingleScriptOutputType output : response.getOutputs().getOutput()) {
            if (!cmdline.hasOption(OPT_HIDE_DATA)) {
                System.out.println("Data:\n" + output.getMslData());
                System.out.println("-----------------------------------------------------------------");
            }
            if (cmdline.hasOption(OPT_FILE_FOR_DATA)) {
                IOUtils.write(output.getMslData(),
                        new FileOutputStream(cmdline.getOptionValue(OPT_FILE_FOR_DATA)), "UTF-8");
            }
            if (!cmdline.hasOption(OPT_HIDE_CONSOLE)) {
                System.out.println("Console output:\n" + output.getTextOutput());
            }
            if (cmdline.hasOption(OPT_HIDE_CONSOLE)) {
                IOUtils.write(output.getMslData(),
                        new FileWriter(cmdline.getOptionValue(OPT_FILE_FOR_CONSOLE)));
            }
        }

        System.out.println("=================================================================");
        System.out.println("Operation result: " + getResultStatus(response.getResult()));
        if (!cmdline.hasOption(OPT_HIDE_RESULT)
                && (cmdline.hasOption(OPT_SHOW_RESULT) || response.getResult() == null
                        || response.getResult().getStatus() != OperationResultStatusType.SUCCESS)) {
            System.out.println("\n\n" + marshalResult(response.getResult()));
        }
        if (cmdline.hasOption(OPT_FILE_FOR_RESULT)) {
            IOUtils.write(marshalResult(response.getResult()),
                    new FileWriter(cmdline.getOptionValue(OPT_FILE_FOR_RESULT)));
        }

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:ca.uhn.fhir.jpa.dao.GZipUtil.java

public static byte[] compress(String theEncoded) {
    try {/*w  w w  . j  a v  a  2s .  c  om*/
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        GZIPOutputStream gos = new GZIPOutputStream(os);
        IOUtils.write(theEncoded, gos, "UTF-8");
        gos.close();
        os.close();
        byte[] retVal = os.toByteArray();
        return retVal;
    } catch (IOException e) {
        throw new DataFormatException("Compress contents", e);
    }
}

From source file:de.urszeidler.ethereum.licencemanager1.deployer.LicenseManagerDeployer.java

/**
 * @param args//from  w ww  .  j a v  a  2s .c  o  m
 */
public static void main(String[] args) {
    Options options = createOptions();
    CommandLineParser parser = new DefaultParser();
    int returnValue = 0;
    boolean dontExit = false;
    try {
        CommandLine commandLine = parser.parse(options, args);
        if (commandLine.hasOption("h")) {
            printHelp(options);
            return;
        }
        if (commandLine.hasOption("de"))
            dontExit = true;

        String senderKey = null;
        String senderPass = null;
        if (commandLine.hasOption("sk"))
            senderKey = commandLine.getOptionValue("sk");
        if (commandLine.hasOption("sp"))
            senderPass = commandLine.getOptionValue("sp");

        LicenseManagerDeployer manager = new LicenseManagerDeployer();

        try {
            manager.init(senderKey, senderPass);

            long currentMili = 0;
            EthValue balance = null;
            if (commandLine.hasOption("calcDeploymendCost")) {
                currentMili = System.currentTimeMillis();
                balance = manager.ethereum.getBalance(manager.sender);
            }
            if (commandLine.hasOption("observeBlock")) {
                manager.ethereum.events().observeBlocks()
                        .subscribe(b -> System.out.println("Block: " + b.blockNumber + " " + b.receipts));
            }

            if (commandLine.hasOption("f")) {
                String[] values = commandLine.getOptionValues("f");

                String filename = values[0];
                String isCompiled = values[1];
                manager.deployer.setContractSource(filename, Boolean.parseBoolean(isCompiled));
            }
            if (commandLine.hasOption("millis")) {
                manager.setMillis(Long.parseLong(commandLine.getOptionValue("millis")));
            }

            if (commandLine.hasOption("c")) {
                String[] values = commandLine.getOptionValues("c");
                if (values == null || values.length != 2) {
                    System.out.println("Error. Need 2 parameters: paymentAddress,name");
                    System.out.println("");
                    printHelp(options);
                    return;
                }

                String paymentAddress = values[0];
                String name = values[1];
                manager.deployLicenseManager(EthAddress.of(paymentAddress), name);
            } else if (commandLine.hasOption("l")) {
                String contractAddress = commandLine.getOptionValue("l");
                if (contractAddress == null) {
                    System.out.println("Error. Need 1 parameters: contract address");
                    System.out.println("");
                    printHelp(options);
                    return;
                }
                manager.setManager(EthAddress.of(contractAddress));
                manager.listContractData(EthAddress.of(contractAddress));
            } else if (commandLine.hasOption("cic")) {
                String[] values = commandLine.getOptionValues("cic");
                if (values == null || values.length != 6) {
                    System.out.println("Error. Need 6 itemName, textHash, url, lifeTime, price");
                    System.out.println("");
                    printHelp(options);
                    return;
                }
                String contractAddress = values[0];
                String itemName = values[1];
                String textHash = values[2];
                String url = values[3];
                String lifeTime = values[4];
                String price = values[5];

                manager.setManager(EthAddress.of(contractAddress));
                manager.createIssuerContract(itemName, textHash, url, Integer.parseInt(lifeTime),
                        Integer.parseInt(price));
            } else if (commandLine.hasOption("bli")) {
                String[] values = commandLine.getOptionValues("bli");
                if (values == null || values.length < 2 || values.length > 3) {
                    System.out.println(
                            "Error. Need 2-3 issuerAddress, name, optional an address when not use the sender.");
                    System.out.println("");
                    printHelp(options);
                    return;
                }
                String issuerAddress = values[0];
                String name = values[1];
                String address = values.length > 2 ? values[2] : null;

                manager.buyLicense(issuerAddress, name, address);
            } else if (commandLine.hasOption("v")) {
                String[] values = commandLine.getOptionValues("v");

                String issuerAddress = values[0];
                String message = values[1];
                String signature = values[2];
                String publicKey = values[3];

                manager.verifyLicense(issuerAddress, message, signature, publicKey);
            } else if (commandLine.hasOption("cs")) {
                String message = commandLine.getOptionValue("cs");
                if (message == null) {
                    System.out.println("Error. Need 1 parameter: message");
                    System.out.println("");
                    printHelp(options);
                    return;
                }
                String signature = createSignature(manager.sender, message);
                String publicKeyString = toPublicKeyString(manager.sender);
                System.out.println("The signature for the message is:");
                System.out.println(signature);
                System.out.println("The public key is:");
                System.out.println(publicKeyString);
            } else if (commandLine.hasOption("co")) {
                String[] values = commandLine.getOptionValues("co");
                if (values == null || values.length != 2) {
                    System.out.println("Error. Need 2 parameters: contractAddress, newOwnerAddress");
                    System.out.println("");
                    printHelp(options);
                    return;
                }

                String contractAddress = values[0];
                String newOwner = values[1];

                manager.changeOwner(EthAddress.of(contractAddress), EthAddress.of(newOwner));
            } else if (commandLine.hasOption("si")) {
                String contractAddress = commandLine.getOptionValue("si");
                if (contractAddress == null) {
                    System.out.println("Error. Need 1 parameters: contract address");
                    System.out.println("");
                    printHelp(options);
                    return;
                }
                manager.setManager(EthAddress.of(contractAddress));
                manager.stopIssue(contractAddress);
            } else if (commandLine.hasOption("ppuk")) {
                System.out.println("Public key: " + toPublicKeyString(manager.sender));
            }

            if (manager.licenseManager != null && commandLine.hasOption("wca")) {
                String[] values = commandLine.getOptionValues("wca");
                String filename = values[0];

                File file = new File(filename);
                IOUtils.write(
                        !commandLine.hasOption("cic") ? manager.licenseManager.contractAddress.withLeading0x()
                                : manager.licenseManager.contractInstance
                                        .contracts(manager.licenseManager.contractInstance.contractCount() - 1)
                                        .withLeading0x(),
                        new FileOutputStream(file), "UTF-8");
            }

            if (commandLine.hasOption("calcDeploymendCost")) {
                balance = balance.minus(manager.ethereum.getBalance(manager.sender));
                BigDecimal divide = new BigDecimal(balance.inWei())
                        .divide(BigDecimal.valueOf(1_000_000_000_000_000_000L));

                System.out.println("Deployment cost: " + (divide) + " in wei:" + balance.inWei()
                        + " time need: " + (System.currentTimeMillis() - currentMili));
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
            printHelp(options);
            returnValue = 10;
        }

    } catch (ParseException e1) {
        System.out.println(e1.getMessage());
        printHelp(options);
        returnValue = 10;
    }
    if (!dontExit)
        System.exit(returnValue);
}

From source file:dk.nsi.minlog.test.utils.TestHelper.java

public static String sendRequest(String url, String action, String docXml, boolean failOnError)
        throws IOException, ServiceException {
    URL u = new URL(url);
    HttpURLConnection uc = (HttpURLConnection) u.openConnection();
    uc.setDoOutput(true);//from  w w  w .  j a v a 2s .  c om
    uc.setDoInput(true);
    uc.setRequestMethod("POST");
    uc.setRequestProperty("SOAPAction", "\"" + action + "\"");
    uc.setRequestProperty("Content-Type", "text/xml; charset=utf-8;");
    OutputStream os = uc.getOutputStream();

    IOUtils.write(docXml, os, "UTF-8");
    os.flush();
    os.close();

    InputStream is;
    if (uc.getResponseCode() != 200) {
        is = uc.getErrorStream();
    } else {
        is = uc.getInputStream();
    }
    String res = IOUtils.toString(is);

    is.close();
    if (uc.getResponseCode() != 200 && (uc.getResponseCode() != 500 || failOnError)) {
        throw new ServiceException(res);
    }
    uc.disconnect();

    return res;
}

From source file:me.mast3rplan.phantombot.HTTPResponse.java

HTTPResponse(String address, String request) throws IOException {

    Socket sock = new Socket(address, 80);
    Writer output = new StringWriter();
    IOUtils.write(request, sock.getOutputStream(), "utf-8");
    IOUtils.copy(sock.getInputStream(), output);
    com.gmt2001.Console.out.println(output.toString());
    Scanner scan = new Scanner(sock.getInputStream());
    String errorLine = scan.nextLine();
    for (String line = scan.nextLine(); !line.equals(""); line = scan.nextLine()) {
        String[] keyval = line.split(":", 2);
        if (keyval.length == 2) {
            values.put(keyval[0], keyval[1].trim());
        } else {/*  ww w .  ja  v  a  2  s  .  c o m*/
            //?
        }
    }
    while (scan.hasNextLine()) {
        body += scan.nextLine();
    }
    sock.close();

}

From source file:com.galenframework.actions.GalenActionConfig.java

@Override
public void execute() throws IOException {
    File file = new File("config");

    if (!file.exists()) {
        file.createNewFile();/* w  w w .  ja  v a 2  s . com*/
        FileOutputStream fos = new FileOutputStream(file);

        StringWriter writer = new StringWriter();
        IOUtils.copy(getClass().getResourceAsStream("/config-template.conf"), writer, "UTF-8");
        IOUtils.write(writer.toString(), fos, "UTF-8");
        fos.flush();
        fos.close();
        outStream.println("Created config file");
    } else {
        errStream.println("Config file already exists");
    }
}

From source file:eu.annocultor.data.destinations.SolrSynonymsFile.java

@Override
public void endRdf() throws Exception {

    if (writingHappened()) {
        OutputStream os = new FileOutputStream(getFinalFile(getVolume()));
        for (Entry<Object, Object> entry : synonyms.entrySet()) {
            IOUtils.write(entry.getKey() + "," + entry.getValue() + "\n", os, "UTF-8");
        }/*w  w w.j  a va2  s . c o m*/
        os.close();
    }
}

From source file:de.jcup.code2doc.generator.docbook.XMLSpecificationFileGenerator.java

@Override
protected void generateImpl(File newFile, SpecificationImpl spec) throws IOException {
    DocbookStringSpecificationGenerator stringGeno = new DocbookStringSpecificationGenerator();
    stringGeno.setFilter(getFilter());/*from w ww . j a  v  a 2  s .  com*/
    String output = stringGeno.generate(spec);
    IOUtils.write(output, new FileOutputStream(newFile), ENCODING);
}

From source file:com.stratio.mojo.scala.crossbuild.FileRewriter.java

public void rewrite(final File file) throws IOException {
    if (!file.exists()) {
        throw new FileNotFoundException("File does not exist: " + file);
    }/*ww w .  j  a  va2s  . c o  m*/
    backupFile(file);
    String result = IOUtils.toString(new FileInputStream(file), StandardCharsets.UTF_8);
    for (final RewriteRule rule : rules) {
        result = rule.replace(result);
    }
    IOUtils.write(result, new FileOutputStream(file), StandardCharsets.UTF_8);
}

From source file:com.hortonworks.registries.schemaregistry.avro.AvroSchemaRegistryClientWithConfFileTest.java

@Before
public void setup() throws IOException {

    Path confFilePath = Files.createTempFile("sr-client-conf", ".props");
    File confFile = confFilePath.toFile();
    try (FileOutputStream fos = new FileOutputStream(confFile);
            InputStream fis = this.getClass().getResourceAsStream("/schema-registry-client.yaml")) {
        String confText = IOUtils.toString(fis, "UTF-8").replace("__registry_url", rootUrl);
        IOUtils.write(confText, fos, "UTF-8");
    }/*from w  w  w .  j  a  v a2s  .  com*/
    schemaRegistryClient = new SchemaRegistryClient(confFile);
}