Example usage for java.io StringWriter toString

List of usage examples for java.io StringWriter toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Return the buffer's current value as a string.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getHSQLConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("create table survey (id int,name varchar);");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
    st.executeUpdate("insert into survey (id,name ) values (2,'anotherValue')");

    WebRowSet webRS;//from   w  w  w  . j  a  v a 2  s .co  m
    ResultSet rs = null;
    Statement stmt = null;
    stmt = conn.createStatement();
    webRS = null;
    String sqlQuery = "SELECT * FROM survey WHERE id='1'";
    webRS = new WebRowSetImpl();
    webRS.setCommand(sqlQuery);
    webRS.execute(conn);

    FileWriter fw = null;

    File file = new File("1.xml");
    fw = new FileWriter(file);
    System.out.println("Writing db data to file " + file.getAbsolutePath());
    webRS.writeXml(fw);

    // convert xml to a String object
    StringWriter sw = new StringWriter();
    webRS.writeXml(sw);
    System.out.println("==============");
    System.out.println(sw.toString());
    System.out.println("==============");
    fw.flush();
    fw.close();
    rs.close();
    stmt.close();
    conn.close();
}

From source file:com.discursive.jccook.slide.GetExample.java

public static void main(String[] args) throws HttpException, IOException {
    HttpClient client = new HttpClient();

    String url = "http://www.discursive.com/jccook/dav/test.html";
    Credentials credentials = new UsernamePasswordCredentials("davuser", "davpass");

    // List resources in top directory
    WebdavResource resource = new WebdavResource(url, credentials);

    System.out.println("The three ways to Read resources.");

    // Read to a temporary file
    File tempFile = new File(resource.getName());
    resource.getMethod(tempFile);/*from w w w  . j av  a 2  s.c  o  m*/
    System.out.println("1. " + resource.getName() + " saved in file: " + tempFile.toString());

    // Read as a String
    String resourceData = resource.getMethodDataAsString();
    System.out.println("2. Contents of " + resource.getName() + " as String.");
    System.out.println(resourceData);

    // Read with a stream
    InputStream resourceStream = resource.getMethodData();
    Reader reader = new InputStreamReader(resourceStream);
    StringWriter writer = new StringWriter();
    while (reader.ready()) {
        writer.write(reader.read());
    }
    System.out.println("3. Contents of " + resource.getName() + " from InputStream.");
    System.out.println(writer.toString());

    resource.close();

}

From source file:ThreadLister.java

/**
 * The main() method create a simple graphical user interface to display the
 * threads in. This allows us to see the "event dispatch thread" used by AWT
 * and Swing.//w w  w .  j av a  2 s  . c  o m
 */
public static void main(String[] args) {
    // Create a simple Swing GUI
    JFrame frame = new JFrame("ThreadLister Demo");
    JTextArea textarea = new JTextArea();
    frame.getContentPane().add(new JScrollPane(textarea), BorderLayout.CENTER);
    frame.setSize(500, 400);
    frame.setVisible(true);

    // Get the threadlisting as a string using a StringWriter stream
    StringWriter sout = new StringWriter(); // To capture the listing
    PrintWriter out = new PrintWriter(sout);
    ThreadLister.listAllThreads(out); // List threads to stream
    out.close();
    String threadListing = sout.toString(); // Get listing as a string

    // Finally, display the thread listing in the GUI
    textarea.setText(threadListing);
}

From source file:ar.com.zauber.garfio.Main.java

/**
 * @param args arguments.//from   w  w  w  .ja v  a  2 s.co  m
 * @throws Exception on error 
 */
public static void main(final String[] args) throws Exception {
    if (args.length < 3) {
        System.err.printf("Usage: %s revision username config.properties [dry-run]", Main.class);
        System.exit(1);
    }
    final String revision = args[0];
    final String username = args[1];
    final String config = args[2];
    final boolean isDryRun = args.length >= 4 && "dry-run".equals(args[3]);

    final PropertiesConfiguration configuration = getConfiguration(config, username, revision);
    final GarfioService garfioService = new DefaultGarfioService(getConfigurationDAO(configuration),
            getErrorNotificator());

    final StringWriter writer = new StringWriter();
    IOUtil.copy(System.in, writer);

    if (isDryRun) {
        final List<String> errors = garfioService.dryrun(configuration.getRepositoryName(), username,
                writer.toString());

        for (String error : errors) {
            System.err.println(error);
        }

        System.exit(errors.isEmpty() ? 0 : 1);
    } else {
        garfioService.run(configuration.getRepositoryName(), revision, args[1], writer.toString());
    }
}

From source file:com.e2info.helloasm.HelloAsmApp.java

public static void main(String[] args) throws IOException {
    String name = "HelloAsm";
    int flag = ClassWriter.COMPUTE_MAXS;
    ClassWriter cw = new ClassWriter(flag);
    cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, name, null, "java/lang/Object", null);

    cw.visitSource(name + ".java", null);

    {//from w  w w  .j  a  va  2s .  co m
        MethodVisitor mv;
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
        mv.visitInsn(Opcodes.RETURN);
        // we need this call to take effect ClassWriter.COMPUTE_MAXS flag.
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

    {
        MethodVisitor mv;
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "main", "([Ljava/lang/String;)V", null,
                null);
        mv.visitCode();
        mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
        mv.visitLdcInsn("hello ASM");
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
        mv.visitInsn(Opcodes.RETURN);
        // we need this call to take effect ClassWriter.COMPUTE_MAXS flag.
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

    cw.visitEnd();

    // build binary
    byte[] bin = cw.toByteArray();

    // save asm trace for human readable
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        new ClassReader(bin).accept(new TraceClassVisitor(pw), 0);
        File f = new File(name + ".txt");
        FileUtils.writeStringToFile(f, sw.toString());
    }

    // save as calss file
    {
        File f = new File(name + ".class");
        FileUtils.writeByteArrayToFile(f, bin);
    }

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Properties prop = new Properties();
    StringWriter sw = new StringWriter();

    prop.setProperty("Chapter Count", "200");
    prop.put("Tutorial Count", "1500");
    prop.put("tutorial", "java2s.com");

    // print the list
    System.out.println(prop);//from   w  w  w  .  j  ava  2s  .c o m

    // store the properties list in an output writer
    prop.store(sw, "Main");

    System.out.println(sw.toString());

}

From source file:com.asual.lesscss.LessEngineCli.java

public static void main(String[] args) throws LessException, URISyntaxException {
    Options cmdOptions = new Options();
    cmdOptions.addOption(LessOptions.CHARSET_OPTION, true, "Input file charset encoding. Defaults to UTF-8.");
    cmdOptions.addOption(LessOptions.COMPRESS_OPTION, false, "Flag that enables compressed CSS output.");
    cmdOptions.addOption(LessOptions.CSS_OPTION, false, "Flag that enables compilation of .css files.");
    cmdOptions.addOption(LessOptions.LESS_OPTION, true, "Path to a custom less.js for Rhino version.");
    try {/*from www.j  av  a2 s  . c  om*/
        CommandLineParser cmdParser = new GnuParser();
        CommandLine cmdLine = cmdParser.parse(cmdOptions, args);
        LessOptions options = new LessOptions();
        if (cmdLine.hasOption(LessOptions.CHARSET_OPTION)) {
            options.setCharset(cmdLine.getOptionValue(LessOptions.CHARSET_OPTION));
        }
        if (cmdLine.hasOption(LessOptions.COMPRESS_OPTION)) {
            options.setCompress(true);
        }
        if (cmdLine.hasOption(LessOptions.CSS_OPTION)) {
            options.setCss(true);
        }
        if (cmdLine.hasOption(LessOptions.LESS_OPTION)) {
            options.setLess(new File(cmdLine.getOptionValue(LessOptions.LESS_OPTION)).toURI().toURL());
        }
        LessEngine engine = new LessEngine(options);
        if (System.in.available() != 0) {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            StringWriter sw = new StringWriter();
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = in.read(buffer))) {
                sw.write(buffer, 0, n);
            }
            String src = sw.toString();
            if (!src.isEmpty()) {
                System.out.println(engine.compile(src, null, options.isCompress()));
                System.exit(0);
            }
        }
        String[] files = cmdLine.getArgs();
        if (files.length == 1) {
            System.out.println(engine.compile(new File(files[0]), options.isCompress()));
            System.exit(0);
        }
        if (files.length == 2) {
            engine.compile(new File(files[0]), new File(files[1]), options.isCompress());
            System.exit(0);
        }

    } catch (IOException ioe) {
        System.err.println("Error opening input file.");
    } catch (ParseException pe) {
        System.err.println("Error parsing arguments.");
    }
    String[] paths = LessEngine.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()
            .split(File.separator);
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("java -jar " + paths[paths.length - 1] + " input [output] [options]", cmdOptions);
    System.exit(1);
}

From source file:com.datatorrent.stram.StreamingAppMaster.java

/**
 * @param args/*  ww  w  .  java  2s .com*/
 *          Command line args
 * @throws Throwable
 */
public static void main(final String[] args) throws Throwable {
    StdOutErrLog.tieSystemOutAndErrToLog();
    LOG.info("Master starting with classpath: {}", System.getProperty("java.class.path"));

    LOG.info("version: {}", VersionInfo.APEX_VERSION.getBuildVersion());
    StringWriter sw = new StringWriter();
    for (Map.Entry<String, String> e : System.getenv().entrySet()) {
        sw.append("\n").append(e.getKey()).append("=").append(e.getValue());
    }
    LOG.info("appmaster env:" + sw.toString());

    Options opts = new Options();
    opts.addOption("app_attempt_id", true, "App Attempt ID. Not to be used unless for testing purposes");

    opts.addOption("help", false, "Print usage");
    CommandLine cliParser = new GnuParser().parse(opts, args);

    // option "help" overrides and cancels any run
    if (cliParser.hasOption("help")) {
        new HelpFormatter().printHelp("ApplicationMaster", opts);
        return;
    }

    Map<String, String> envs = System.getenv();
    ApplicationAttemptId appAttemptID = Records.newRecord(ApplicationAttemptId.class);
    if (!envs.containsKey(Environment.CONTAINER_ID.name())) {
        if (cliParser.hasOption("app_attempt_id")) {
            String appIdStr = cliParser.getOptionValue("app_attempt_id", "");
            appAttemptID = ConverterUtils.toApplicationAttemptId(appIdStr);
        } else {
            throw new IllegalArgumentException("Application Attempt Id not set in the environment");
        }
    } else {
        ContainerId containerId = ConverterUtils.toContainerId(envs.get(Environment.CONTAINER_ID.name()));
        appAttemptID = containerId.getApplicationAttemptId();
    }

    boolean result = false;
    StreamingAppMasterService appMaster = null;
    try {
        appMaster = new StreamingAppMasterService(appAttemptID);
        LOG.info("Initializing Application Master.");

        Configuration conf = new YarnConfiguration();
        appMaster.init(conf);
        appMaster.start();
        result = appMaster.run();
    } catch (Throwable t) {
        LOG.error("Exiting Application Master", t);
        System.exit(1);
    } finally {
        if (appMaster != null) {
            appMaster.stop();
        }
    }

    if (result) {
        LOG.info("Application Master completed.");
        System.exit(0);
    } else {
        LOG.info("Application Master failed.");
        System.exit(2);
    }
}

From source file:org.eclipse.lyo.adapter.tdb.clients.OSLCTriplestoreAdapterResourceCreationClient.java

public static void main(String[] args) {

    String baseHTTPURI = "http://localhost:" + OSLC4JTDBApplication.portNumber + "/oslc4jtdb";
    String projectId = "default";

    // URI of the HTTP request
    String tdbResourceCreationFactoryURI = baseHTTPURI + "/services/" + projectId + "/resources";

    // create RDF to add to the triplestore
    Model resourceRDFModel = ModelFactory.createDefaultModel();
    Resource resource = ResourceFactory
            .createResource("http://localhost:8585/oslc4jtdb/services/default/resources/newBlock4");
    Property property = ResourceFactory/*from  w w w .  j a  v  a  2 s  .c  o m*/
            .createProperty("http://localhost:8585/oslc4jtdb/services/default/resources/newProperty4");
    RDFNode object = ResourceFactory
            .createResource("http://localhost:8585/oslc4jtdb/services/default/resources/newObject4");
    resourceRDFModel.add(resource, property, object);
    StringWriter out = new StringWriter();
    resourceRDFModel.write(out, "RDF/XML");
    resourceRDFModel.write(System.out);

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(tdbResourceCreationFactoryURI);
    String xml = out.toString();
    HttpEntity entity;
    try {
        entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        post.setHeader("Accept", "application/rdf+xml");
        HttpResponse response = client.execute(post);

        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:de.akquinet.dustjs.DustEngine.java

public static void main(String[] args) throws URISyntaxException {
    Options cmdOptions = new Options();
    cmdOptions.addOption(DustOptions.CHARSET_OPTION, true, "Input file charset encoding. Defaults to UTF-8.");
    cmdOptions.addOption(DustOptions.DUST_OPTION, true, "Path to a custom dust.js for Rhino version.");
    try {//w  w  w. j  ava2  s .  c o  m
        CommandLineParser cmdParser = new GnuParser();
        CommandLine cmdLine = cmdParser.parse(cmdOptions, args);
        DustOptions options = new DustOptions();
        if (cmdLine.hasOption(DustOptions.CHARSET_OPTION)) {
            options.setCharset(cmdLine.getOptionValue(DustOptions.CHARSET_OPTION));
        }
        if (cmdLine.hasOption(DustOptions.DUST_OPTION)) {
            options.setDust(new File(cmdLine.getOptionValue(DustOptions.DUST_OPTION)).toURI().toURL());
        }
        DustEngine engine = new DustEngine(options);
        String[] files = cmdLine.getArgs();

        String src = null;
        if (files == null || files.length == 0) {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            StringWriter sw = new StringWriter();
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = in.read(buffer))) {
                sw.write(buffer, 0, n);
            }
            src = sw.toString();
        }

        if (src != null && !src.isEmpty()) {
            System.out.println(engine.compile(src, "test"));
            return;
        }

        if (files.length == 1) {
            System.out.println(engine.compile(new File(files[0])));
            return;
        }

        if (files.length == 2) {
            engine.compile(new File(files[0]), new File(files[1]));
            return;
        }

    } catch (IOException ioe) {
        System.err.println("Error opening input file.");
    } catch (ParseException pe) {
        System.err.println("Error parsing arguments.");
    }

    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("java -jar dust-engine.jar input [output] [options]", cmdOptions);
    System.exit(1);
}