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

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

Introduction

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

Prototype

public static String toString(byte[] input, String encoding) throws IOException 

Source Link

Document

Get the contents of a byte[] as a String using the specified character encoding.

Usage

From source file:eu.riscoss.datacollectors.ExampleDataCollector.java

public static void main(String[] args) throws Exception {
    JSONObject input;/*  ww w. j  a va 2 s . com*/
    if (args.length > 0 && "--stdin-conf".equals(args[args.length - 1])) {
        String stdin = IOUtils.toString(System.in, "UTF-8");
        input = new JSONObject(stdin);
    } else {
        input = testInput();
        System.out.println("using " + input + " as test configuration.");
        System.out.println("In production, use --stdin-conf and pass configuration to stdin");
    }

    JSONObject outObj = new JSONObject();
    outObj.put("id", COLLECTOR_ID);
    outObj.put("type", COLLECTOR_DATATYPE);
    outObj.put("target", input.getString("riscoss_targetName"));
    outObj.put("value", getData(input));

    JSONArray outArray = new JSONArray();
    outArray.put(outObj);
    System.out.println("-----BEGIN RISK DATA-----");
    System.out.println(outArray.toString());
    System.out.println("-----END RISK DATA-----");
}

From source file:ee.ria.xroad.common.conf.globalconfextension.StdinValidator.java

/**
 * Program entry point/* w w  w  .j a  v a  2 s  .c o m*/
 */
public static void main(String[] args) throws Exception {
    String string = IOUtils.toString(System.in, StandardCharsets.UTF_8.toString());
    System.out.println(string);
    OcspNextUpdateSchemaValidator.validate(string);
}

From source file:ee.ria.xroad.common.conf.globalconfextension.OcspFetchIntervalStdinValidator.java

/**
 * Program entry point/*  w ww. ja  v  a2  s.  c  o  m*/
 */
public static void main(String[] args) throws Exception {
    String string = IOUtils.toString(System.in, StandardCharsets.UTF_8.toString());
    System.out.println(string);
    OcspFetchIntervalSchemaValidator.validate(string);
}

From source file:ee.ria.xroad.proxy.serverproxy.StdinValidator.java

/**
 * Program entry point//from w w w . j  a  va2 s  .  c  o m
 */
public static void main(String[] args) throws Exception {
    String string = IOUtils.toString(System.in, StandardCharsets.UTF_8.toString());
    System.out.println(string);
    MonitoringParametersSchemaValidator.validate(string);
}

From source file:com.javacreed.examples.sql.Example3.java

public static void main(final String[] args) throws Exception {
    try (BasicDataSource dataSource = DatabaseUtils.createDataSource();
            Connection connection = dataSource.getConnection()) {
        final ExampleTest test = new ExampleTest(connection, "compressed_table", "compressed") {
            @Override//from   w  w w . j av a2 s  .c o m
            protected String parseRow(final ResultSet resultSet) throws Exception {
                try (InputStream in = new LZ4BlockInputStream(resultSet.getBinaryStream("compressed"))) {
                    return IOUtils.toString(in, "UTF-8");
                }
            }

            @Override
            protected void setPreparedStatement(final String data, final PreparedStatement statement)
                    throws Exception {
                final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length());
                try (OutputStream out = new LZ4BlockOutputStream(baos)) {
                    out.write(data.getBytes("UTF-8"));
                }
                statement.setBinaryStream(1, new ByteArrayInputStream(baos.toByteArray()));
            }
        };
        test.runTest();
    }
    Example3.LOGGER.debug("Done");
}

From source file:com.javacreed.examples.sql.Example4.java

public static void main(final String[] args) throws Exception {
    try (BasicDataSource dataSource = DatabaseUtils.createDataSource();
            Connection connection = dataSource.getConnection()) {
        final ExampleTest test = new ExampleTest(connection, "compressed_table", "compressed") {

            @Override/*from ww w  . j a v  a 2  s  . co  m*/
            protected String parseRow(final ResultSet resultSet) throws Exception {
                try (InputStream in = new LZ4BlockInputStream(
                        CryptoUtils.wrapInToCipheredInputStream(resultSet.getBinaryStream("compressed")))) {
                    return IOUtils.toString(in, "UTF-8");
                }
            }

            @Override
            protected void setPreparedStatement(final String data, final PreparedStatement statement)
                    throws Exception {
                final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length());
                try (OutputStream out = new LZ4BlockOutputStream(
                        CryptoUtils.wrapInToCipheredOutputStream(baos))) {
                    out.write(data.getBytes("UTF-8"));
                }
                statement.setBinaryStream(1, new ByteArrayInputStream(baos.toByteArray()));
            }

        };
        test.runTest();
    }
    Example4.LOGGER.debug("Done");
}

From source file:com.javacreed.examples.sql.Example2.java

public static void main(final String[] args) throws Exception {
    try (BasicDataSource dataSource = DatabaseUtils.createDataSource();
            Connection connection = dataSource.getConnection()) {
        final ExampleTest test = new ExampleTest(connection, "compressed_table", "compressed") {
            @Override/*from w  w w  . j  av a 2 s .  c om*/
            protected String parseRow(final ResultSet resultSet) throws Exception {
                try (GZIPInputStream in = new GZIPInputStream(resultSet.getBinaryStream("compressed"))) {
                    return IOUtils.toString(in, "UTF-8");
                }
            }

            @Override
            protected void setPreparedStatement(final String data, final PreparedStatement statement)
                    throws Exception {
                // Compress the data before inserting it. We need to compress before inserting the data to make this process
                // as realistic as possible.
                final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length());
                try (OutputStream out = new GZIPOutputStream(baos, data.length())) {
                    out.write(data.getBytes("UTF-8"));
                }
                statement.setBinaryStream(1, new ByteArrayInputStream(baos.toByteArray()));
            }
        };
        test.runTest();
    }
    Example2.LOGGER.debug("Done");
}

From source file:com.doctor.ganymed_ssh2.Basic.java

/**
 * Password authentication fails, I get "Authentication method password
 * not supported by the server at this stage
 * // w ww.j av a 2 s.c  om
 * ssh? /ect/ssh/sshd_config  ? "PasswordAuthentication"  "no" .
 * changed it to "PasswordAuthentication yes"
 * 
 * 
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    String hostname = "127.0.0.1";
    String username = "doctor";
    String passwd = "xxx";
    Connection connection = new Connection(hostname);
    connection.connect();

    boolean authenticateWithPassword = connection.authenticateWithPassword(username, passwd);
    if (!authenticateWithPassword) {
        throw new RuntimeException("authenticateWithPassword failed");
    }

    Session session = connection.openSession();
    session.execCommand("pwd  ; date ;echo hello doctor");
    InputStream streamGobbler = new StreamGobbler(session.getStdout());

    String result = IOUtils.toString(streamGobbler, StandardCharsets.UTF_8);
    System.out.println("result:" + result);
    System.out.println("ExitStatus:" + session.getExitStatus());

    session.close();
    connection.close();

}

From source file:main.ReportGenerator.java

/**
 * Entry point for the program.//from  w ww . j av a  2 s  . co  m
 * Takes the variables as JSON on the standard input.
 * @param args Arguments from the command line.
 */
public static void main(String[] args) {
    CommandLine cmd = createOptions(args);

    GeneratorError result = GeneratorError.NO_ERROR;
    try {
        //Build the output name, by default ./output
        String directory = cmd.getOptionValue("output", "./");
        if (!directory.endsWith(File.separator))
            directory += File.separator;
        String filename = cmd.getOptionValue("name", "output");
        String output = directory + filename;

        //Get the JSON from file if given, or get it from the standard input.
        String jsonText = null;
        if (!cmd.hasOption("input")) {
            // Initializes the input with the standard input
            jsonText = IOUtils.toString(System.in, "UTF-8");
        } else // read the file
        {
            FileInputStream inputStream = new FileInputStream(cmd.getOptionValue("input"));
            try {
                jsonText = IOUtils.toString(inputStream);
            } finally {
                inputStream.close();
            }
        }

        //Build the report object
        Report report = new Report(jsonText, cmd.getOptionValue("template"), output);

        //Generate the document
        if (cmd.hasOption("all")) {
            new AllGenerator(report).generate();
        } else {
            if (cmd.hasOption("html"))
                new HTMLGenerator(report).generate();
            if (cmd.hasOption("pdf"))
                new PDFGenerator(report).generate();
            if (cmd.hasOption("doc"))
                new DocGenerator(report).generate();
        }

    } catch (IOException e) {
        System.err.println("Error: " + e.getMessage());
        System.exit(GeneratorError.IO_ERROR.getCode());
    } catch (GeneratorException e) {
        System.err.println("Error: " + e.getMessage());
        System.exit(e.getError().getCode());
    }
    System.exit(result.getCode());
}

From source file:com.github.thesmartenergy.sparql.generate.generator.CMDGenerator.java

public static void main(String[] args) {

    List<String> formats = Arrays.asList("TTL", "TURTLE", "NTRIPLES", "TRIG", "RDFXML", "JSONLD");

    try {/*www.j  av a  2 s  . c  om*/
        CommandLine cl = CMDConfigurations.parseArguments(args);

        String query = "";
        String outputFormat = "TTL";

        if (cl.getArgList().size() == 0) {
            CMDConfigurations.displayHelp();
            return;
        }

        fileManager = FileManager.makeGlobal();
        if (cl.hasOption('l')) {
            Enumeration<String> loggers = LogManager.getLogManager().getLoggerNames();
            while (loggers.hasMoreElements()) {
                java.util.logging.Logger element = LogManager.getLogManager().getLogger(loggers.nextElement());
                element.setLevel(Level.OFF);
            }
            Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF);

        }
        LOG = Logger.getLogger(CMDGenerator.class);

        //get query file path
        //check if the file exists
        if (cl.hasOption("qf")) {
            String file_path = cl.getOptionValue("qf");
            File f = new File(file_path);
            if (f.exists() && !f.isDirectory()) {
                FileInputStream fisTargetFile = new FileInputStream(f);
                query = IOUtils.toString(fisTargetFile, "UTF-8");
                LOG.debug("\n\nRead SPARQL-Generate Query ..\n" + query + "\n\n");
            } else {
                LOG.error("File " + file_path + " not found.");
            }
        }

        //get query string
        if (cl.hasOption("qs")) {
            query = cl.getOptionValue("qs");
        }
        System.out.println("Query:" + query);

        //get and validate the output format
        if (cl.hasOption("f")) {
            String format = cl.getOptionValue("f");
            if (formats.contains(format)) {
                outputFormat = format;
            } else {
                LOG.error("Invalid output format," + cl.getOptionProperties("f").getProperty("description"));
                return;
            }
        }

        Model configurationModel = null;
        String conf = "";
        if (cl.hasOption("c")) {
            conf = cl.getOptionValue("c");
            configurationModel = ProcessQuery.generateConfiguration(conf);
        }

        String output = ProcessQuery.process(query, conf, outputFormat);
        System.out.println(output);

    } catch (org.apache.commons.cli.ParseException ex) {
        LOG.error(ex);
    } catch (FileNotFoundException ex) {
        LOG.error(ex);
    } catch (IOException ex) {
        LOG.error(ex);
    }

}