Example usage for java.io StringWriter StringWriter

List of usage examples for java.io StringWriter StringWriter

Introduction

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

Prototype

public StringWriter() 

Source Link

Document

Create a new string writer using the default initial string-buffer size.

Usage

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 ww . java2 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: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;//  w w  w. jav a2s .  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: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  ww  .j  av  a2s  .  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:net.jcreate.e3.templateEngine.webmacro.WebMacroTemplateEngine.java

public static void main(String[] args) {
    WebMacroTemplateEngine a = new WebMacroTemplateEngine();
    Template t = new DefaultTemplate();
    t.setResource("noservlet.wm");
    Context c = new DefaultContext();
    c.put("msg", "hello.");
    StringWriter writer = new StringWriter();
    a.mergeTemplate(t, c, writer);//from ww w .j a  v  a 2s.c  o m
    System.out.println(writer.toString());
}

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  .ja  v  a 2 s  . co 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);
}

From source file:net.jcreate.e3.templateEngine.jxp.JxpTemplateEngine.java

public static void main(String[] args) {
    JxpTemplateEngine a = new JxpTemplateEngine();
    Template t = new DefaultTemplate();
    t.setResource("test.jxp");
    Context c = new DefaultContext();
    c.put("msg", "hello");
    c.put("msg2", ".");
    StringWriter writer = new StringWriter();
    a.mergeFileTemplate(t, c, writer);//from  w  w w .j  a  va2 s. c om
    System.out.println(writer.toString());
}

From source file:Anaphora_Resolution.ParseAllXMLDocuments.java

public static void main(String[] args)
        throws IOException, SAXException, ParserConfigurationException, TransformerException {
    //      File dataFolder = new File("DataToPort");
    //      File[] documents;
    String grammar = "grammar/englishPCFG.ser.gz";
    String[] options = { "-maxLength", "100", "-retainTmpSubcategories" };
    //LexicalizedParser lp =  new LexicalizedParser(grammar, options);
    LexicalizedParser lp = LexicalizedParser.loadModel("edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz");
    ///*from  ww  w  . j a  v a 2  s .c om*/
    //      if (dataFolder.isDirectory()) {
    //          documents = dataFolder.listFiles();
    //      } else {
    //          documents = new File[] {dataFolder};
    //      }
    //      int currfile = 0;
    //      int totfiles = documents.length;
    //      for (File paper : documents) {
    //          currfile++;
    //          if (paper.getName().equals(".DS_Store")||paper.getName().equals(".xml")) {
    //              currfile--;
    //              totfiles--;
    //              continue;
    //          }
    //          System.out.println("Working on "+paper.getName()+" (file "+currfile+" out of "+totfiles+").");
    //
    //          DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); // This is for XML
    //          DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    //          Document doc = docBuilder.parse(paper.getAbsolutePath());
    //
    //          NodeList textlist = doc.getElementsByTagName("text");
    //          for(int i=0; i < textlist.getLength(); i++) {
    //              Node currentnode = textlist.item(i);
    //              String wholetext = textlist.item(i).getTextContent();
    String wholetext = "How about other changes for example the ways of doing the work and \n" + "\n"
            + "Iwould say security has , there 's more pressure put on people now than there used to be because obviously , especially after Locherbie , they tightened up on security and there 's a lot more pressure now especially from the ETR and stuff like that \n"
            + "People do n't feel valued any more , they feel  I do n't know I think they feel that nobody cares about them really anyway \n";

    //System.out.println(wholetext);
    //Iterable<List<? extends HasWord>> sentences;

    ArrayList<Tree> parseTrees = new ArrayList<Tree>();
    String asd = "";
    int j = 0;
    StringReader stringreader = new StringReader(wholetext);
    DocumentPreprocessor dp = new DocumentPreprocessor(stringreader);
    @SuppressWarnings("rawtypes")
    ArrayList<List> sentences = preprocess(dp);
    for (List sentence : sentences) {
        parseTrees.add(lp.apply(sentence)); // Parsing a new sentence and adding it to the parsed tree
        ArrayList<Tree> PronounsList = findPronouns(parseTrees.get(j)); // Locating all pronouns to resolve in the sentence
        Tree corefedTree;
        for (Tree pronounTree : PronounsList) {
            parseTrees.set(parseTrees.size() - 1, HobbsResolve(pronounTree, parseTrees)); // Resolving the coref and modifying the tree for each pronoun
        }
        StringWriter strwr = new StringWriter();
        PrintWriter prwr = new PrintWriter(strwr);
        TreePrint tp = new TreePrint("penn");
        tp.printTree(parseTrees.get(j), prwr);
        prwr.flush();
        asd += strwr.toString();
        j++;
    }
    String armando = "";
    for (Tree sentence : parseTrees) {
        for (Tree leaf : Trees.leaves(sentence))
            armando += leaf + " ";
    }
    System.out.println(wholetext);

    System.out.println();
    System.out.println("......");
    System.out.println(armando);
    System.out.println("All done.");
    //              currentnode.setTextContent(asd);
    //          }
    //          TransformerFactory transformerFactory = TransformerFactory.newInstance();
    //          Transformer transformer = transformerFactory.newTransformer();
    //          DOMSource source = new DOMSource(doc);
    //          StreamResult result = new StreamResult(paper);
    //          transformer.transform(source, result);
    //
    //          System.out.println("Done");
    //      }
}

From source file:com.semsaas.jsonxml.tools.JsonXpath.java

public static void main(String[] args) {
    /*/*from w ww.  ja v  a 2 s .  c  o  m*/
     * Process options
     */
    LinkedList<String> files = new LinkedList<String>();
    LinkedList<String> expr = new LinkedList<String>();
    boolean help = false;
    String activeOption = null;
    String error = null;

    for (int i = 0; i < args.length && error == null && !help; i++) {
        if (activeOption != null) {
            if (activeOption.equals("-e")) {
                expr.push(args[i]);
            } else if (activeOption.equals("-h")) {
                help = true;
            } else {
                error = "Unknown option " + activeOption;
            }
            activeOption = null;
        } else {
            if (args[i].startsWith("-")) {
                activeOption = args[i];
            } else {
                files.push(args[i]);
            }
        }
    }

    if (error != null) {
        System.err.println(error);
        showHelp();
    } else if (help) {
        showHelp();
    } else {
        try {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            for (String f : files) {
                System.out.println("*** " + f + " ***");
                try {
                    // Create a JSON XML reader
                    XMLReader reader = XMLReaderFactory.createXMLReader("com.semsaas.jsonxml.JsonXMLReader");

                    // Prepare a reader with the JSON file as input
                    InputStreamReader stringReader = new InputStreamReader(new FileInputStream(f));
                    SAXSource saxSource = new SAXSource(reader, new InputSource(stringReader));

                    // Prepare a DOMResult which will hold the DOM of the xjson
                    DOMResult domResult = new DOMResult();

                    // Run SAX processing through a transformer
                    // (This could be done more simply, but we have here the opportunity to pass our xjson through
                    // an XSLT and get a legacy XML output ;) )
                    transformer.transform(saxSource, domResult);
                    Node dom = domResult.getNode();

                    XPathFactory xpathFactory = XPathFactory.newInstance();
                    for (String x : expr) {
                        try {
                            XPath xpath = xpathFactory.newXPath();
                            xpath.setNamespaceContext(new NamespaceContext() {
                                public Iterator getPrefixes(String namespaceURI) {
                                    return null;
                                }

                                public String getPrefix(String namespaceURI) {
                                    return null;
                                }

                                public String getNamespaceURI(String prefix) {
                                    if (prefix == null) {
                                        return XJSON.XMLNS;
                                    } else if ("j".equals(prefix)) {
                                        return XJSON.XMLNS;
                                    } else {
                                        return null;
                                    }
                                }
                            });
                            NodeList nl = (NodeList) xpath.evaluate(x, dom, XPathConstants.NODESET);
                            System.out.println("-- Found " + nl.getLength() + " nodes for xpath '" + x
                                    + "' in file '" + f + "'");
                            for (int i = 0; i < nl.getLength(); i++) {
                                System.out.println(" +(" + i + ")+ ");
                                XMLJsonGenerator handler = new XMLJsonGenerator();
                                StringWriter buffer = new StringWriter();
                                handler.setOutputWriter(buffer);

                                SAXResult result = new SAXResult(handler);
                                transformer.transform(new DOMSource(nl.item(i)), result);

                                System.out.println(buffer.toString());
                            }
                        } catch (XPathExpressionException e) {
                            System.err.println("-- Error evaluating '" + x + "' on file '" + f + "'");
                            e.printStackTrace();
                        } catch (TransformerException e) {
                            System.err.println("-- Error evaluating '" + x + "' on file '" + f + "'");
                            e.printStackTrace();
                        }
                    }
                } catch (FileNotFoundException e) {
                    System.err.println("File '" + f + "' was not found");
                } catch (SAXException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TransformerException e) {
                    e.printStackTrace();
                }
            }
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
    }
}

From source file:kishida.cnn.NeuralNetwork.java

public static void main(String[] args) throws IOException {
    NeuralNetwork nn = new NeuralNetwork();
    nn.getLayers()//from w w  w . j a  v  a  2  s.c om
            .addAll(Arrays.asList(new InputLayer(20, 20), new ConvolutionLayer("conv1", 3, 7, 2, 1, true),
                    new MaxPoolingLayer("pool", 3, 2), new MultiNormalizeLayer("norm1", 5, .0001f, true),
                    new FullyConnect("test", 3, 0, 1, new LogisticFunction(), true)));
    nn.init();
    nn.random.nextInt();
    StringWriter sw = new StringWriter();
    nn.writeAsJson(sw);
    System.out.println(sw);

    // ??????????????
    StringReader sr0 = new StringReader(sw.toString());
    NeuralNetwork nn0 = nn.readFromJson(sr0);
    nn0.init();
    ConvolutionLayer conv1o = (ConvolutionLayer) nn.findLayerByName("conv1").get();
    ConvolutionLayer conv1r = (ConvolutionLayer) nn0.findLayerByName("conv1").get();
    System.out.println("org:" + Arrays.toString(conv1o.getFilter()));
    System.out.println("red:" + Arrays.toString(conv1r.getFilter()));
    double loss = IntStream.range(0, conv1o.getFilter().length)
            .mapToDouble(i -> (conv1o.getFilter()[i] - conv1r.getFilter()[i])
                    * (conv1o.getFilter()[i] - conv1r.getFilter()[i]))
            .sum();
    System.out.println(Math.sqrt(loss));

    NeuralNetwork v = NeuralNetwork.readFromJson(new StringReader("{\n" + "  \"weightDecay\" : 5.0E-4,\n"
            + "  \"miniBatch\" : 128,\n" + "  \"random\" : \"c3EAfgAAAT/wWGBKFyCXAAATnQ6sF654\",\n"
            + "  \"imageRandom\" : \"c3EAfgAAAAAAAAAAAAAAAAAABd7s70R4\",\n" + "  \"momentam\" : 0.9,\n"
            + "  \"layers\" : [ {\n" + "    \"InputLayer\" : {\n" + "      \"width\" : 250,\n"
            + "      \"height\" : 220,\n" + "      \"name\" : \"input\"\n" + "    }\n" + "  }, {\n"
            + "    \"ConvolutionLayer\" : {\n" + "      \"name\" : \"conv1\",\n" + "      \"filter\" : null,\n"
            + "      \"bias\" : [ 1.0, 1.0, 1.0 ],\n" + "      \"filterDelta\" : null,\n"
            + "      \"biasDelta\" : [ 0.0, 0.0, 0.0 ],\n" + "      \"stride\" : 2,\n"
            + "      \"filterSize\" : 7,\n" + "      \"useGpu\" : true\n" + "    }\n" + "  }, {\n"
            + "    \"MaxPoolingLayer\" : {\n" + "      \"name\" : \"pool\",\n" + "      \"size\" : 3,\n"
            + "      \"stride\" : 2\n" + "    }\n" + "  }, {\n" + "    \"MultiNormalizeLayer\" : {\n"
            + "      \"name\" : \"norm1\",\n" + "      \"size\" : 5,\n" + "      \"threshold\" : 1.0E-4,\n"
            + "      \"useGpu\" : true\n" + "    }\n" + "  }, {\n" + "    \"FullyConnect\" : {\n"
            + "      \"name\" : \"test\",\n" + "      \"outputSize\" : 3,\n"
            + "      \"weight\" : [ 0.0014115907, 0.0043465886, 0.01138472, -0.0013297468, "
            + "-0.0060525155, -0.0109255025, -0.015493984, 0.011872963, -0.0015145391 ],\n"
            + "      \"initBias\" : 0.5, " + "      \"bias\" : [ 0.0, 0.2, 0.4 ],\n"
            + "      \"weightDelta\" : [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ],\n"
            + "      \"biasDelta\" : [ 0.0, 0.0, 0.0 ],\n" + "      \"dropoutRate\" : 1.0,\n"
            + "      \"activation\" : \"LogisticFunction\",\n" + "      \"useGpu\" : true\n" + "    }\n"
            + "  } ],\n" + "  \"learningRate\" : 0.01\n" + "}"));
    System.out.println(nn.random.nextInt());
    System.out.println(v.random.nextInt());
    v.findLayerByName("test").ifPresent(layer -> {
        FullyConnect f = (FullyConnect) layer;
        System.out.println(f.getActivation().getClass());
        System.out.println(Arrays.toString(f.getBias()));
    });
    v.init();
    v.findLayerByName("test").ifPresent(layer -> {
        FullyConnect f = (FullyConnect) layer;
        System.out.println(f.getActivation().getClass());
        System.out.println(Arrays.toString(f.getBias()));
    });
}

From source file:com.arsdigita.util.parameter.ParameterPrinter.java

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

    CommandLine line = null;/*from w  w w.ja v a  2  s.c  o m*/
    try {
        line = new PosixParser().parse(OPTIONS, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    String[] outFile = line.getArgs();
    if (outFile.length != 1) {
        System.out.println("Usage: ParameterPrinter [--html] [--file config-list-file] output-file");
        System.exit(1);
    }
    if (line.hasOption("usage")) {
        System.out.println("Usage: ParameterPrinter [--html] [--file config-list-file] output-file");
        System.exit(0);
    }

    if (line.hasOption("file")) {
        String file = line.getOptionValue("file");
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String configClass;
            while ((configClass = reader.readLine()) != null) {
                register(configClass);
            }
        } catch (IOException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    } else {
        register("com.arsdigita.runtime.RuntimeConfig");
        register("com.arsdigita.web.WebConfig");
        register("com.arsdigita.templating.TemplatingConfig");
        register("com.arsdigita.kernel.KernelConfig");
        register("com.arsdigita.kernel.security.SecurityConfig");
        register("com.arsdigita.mail.MailConfig");
        register("com.arsdigita.versioning.VersioningConfig");
        register("com.arsdigita.search.SearchConfig");
        register("com.arsdigita.search.lucene.LuceneConfig");
        register("com.arsdigita.kernel.security.SecurityConfig");
        register("com.arsdigita.bebop.BebopConfig");
        register("com.arsdigita.dispatcher.DispatcherConfig");
        register("com.arsdigita.workflow.simple.WorkflowConfig");
        register("com.arsdigita.cms.ContentSectionConfig");
    }

    if (line.hasOption("html")) {
        final StringWriter sout = new StringWriter();
        final PrintWriter out = new PrintWriter(sout);

        writeXML(out);

        final XSLTemplate template = new XSLTemplate(
                ParameterPrinter.class.getResource("ParameterPrinter_html.xsl"));

        final Source source = new StreamSource(new StringReader(sout.toString()));
        final Result result = new StreamResult(new File(outFile[0]));

        template.transform(source, result);
    } else {
        final PrintWriter out = new PrintWriter(new FileWriter(outFile[0]));

        writeXML(out);
    }
}