Example usage for java.io Writer toString

List of usage examples for java.io Writer toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.apache.hadoop.yarn.logaggregation.TestAggregatedLogFormat.java

private void testReadAcontainerLog(boolean logUploadedTime) throws Exception {
    Configuration conf = new Configuration();
    UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
    File workDir = new File(testWorkDir, "testReadAcontainerLogs1");
    Path remoteAppLogFile = new Path(workDir.getAbsolutePath(), "aggregatedLogFile");
    Path srcFileRoot = new Path(workDir.getAbsolutePath(), "srcFiles");
    Path srcFileUser = new Path(srcFileRoot, ugi.getShortUserName());
    ContainerId testContainerId = TestContainerId.newContainerId(1, 1, 1, 1);
    Path t = new Path(srcFileUser, testContainerId.getApplicationAttemptId().getApplicationId().toString());
    Path srcFilePath = new Path(t, testContainerId.toString());

    int numChars = 80000;

    // create a sub-folder under srcFilePath
    // and create file logs in this sub-folder.
    // We only aggregate top level files.
    // So, this log file should be ignored.
    Path subDir = new Path(srcFilePath, "subDir");
    fs.mkdirs(subDir);//from ww w.  j  ava  2s  .c  o  m
    writeSrcFile(subDir, "logs", numChars);

    // create file stderr and stdout in containerLogDir
    writeSrcFile(srcFilePath, "stderr", numChars);
    writeSrcFile(srcFilePath, "stdout", numChars);

    try (LogWriter logWriter = new LogWriter()) {
        logWriter.initialize(conf, remoteAppLogFile, ugi);
        LogKey logKey = new LogKey(testContainerId);
        LogValue logValue = new LogValue(Collections.singletonList(srcFileRoot.toString()), testContainerId,
                ugi.getShortUserName(), ugi.getShortUserName());

        // When we try to open FileInputStream for stderr, it will throw out an
        // IOException. Skip the log aggregation for stderr.
        LogValue spyLogValue = spy(logValue);
        File errorFile = new File((new Path(srcFilePath, "stderr")).toString());
        doThrow(new IOException("Mock can not open FileInputStream")).when(spyLogValue)
                .secureOpenFile(errorFile);

        logWriter.append(logKey, spyLogValue);
    }

    // make sure permission are correct on the file
    FileStatus fsStatus = fs.getFileStatus(remoteAppLogFile);
    Assert.assertEquals("permissions on log aggregation file are wrong",
            FsPermission.createImmutable((short) 0640), fsStatus.getPermission());

    LogReader logReader = new LogReader(conf, remoteAppLogFile);
    LogKey rLogKey = new LogKey();
    DataInputStream dis = logReader.next(rLogKey);
    Writer writer = new StringWriter();

    if (logUploadedTime) {
        LogReader.readAcontainerLogs(dis, writer, System.currentTimeMillis());
    } else {
        LogReader.readAcontainerLogs(dis, writer);
    }

    // We should only do the log aggregation for stdout.
    // Since we could not open the fileInputStream for stderr, this file is not
    // aggregated.
    String s = writer.toString();
    int expectedLength = "LogType:stdout".length()
            + (logUploadedTime ? ("\nLog Upload Time:" + Times.format(System.currentTimeMillis())).length() : 0)
            + ("\nLogLength:" + numChars).length() + "\nLog Contents:\n".length() + numChars + "\n".length()
            + "End of LogType:stdout\n".length();
    Assert.assertTrue("LogType not matched", s.contains("LogType:stdout"));
    Assert.assertTrue("log file:stderr should not be aggregated.", !s.contains("LogType:stderr"));
    Assert.assertTrue("log file:logs should not be aggregated.", !s.contains("LogType:logs"));
    Assert.assertTrue("LogLength not matched", s.contains("LogLength:" + numChars));
    Assert.assertTrue("Log Contents not matched", s.contains("Log Contents"));

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < numChars; i++) {
        sb.append(filler);
    }
    String expectedContent = sb.toString();
    Assert.assertTrue("Log content incorrect", s.contains(expectedContent));

    Assert.assertEquals(expectedLength, s.length());
}

From source file:net.cloudkit.enterprises.infrastructure.utilities.FreemarkerHelper.java

/**
 * Process Template/*from  ww  w  .  j ava2  s .c  om*/
 *
 * @param templateName
 * @param model
 * @param writer
 * @return
 */
public static String process(String templateName, Map<String, ?> model, Writer writer) {

    /*
    // Where you initialize the cfg *singleton* (happens just once in the application life-cycle):
    cfg = new Configuration(Configuration.VERSION_2_3_22);
    ...
    cfg.setObjectWrapper(new MyAppObjectWrapper(cfg.getIncompatibleImprovements()));
    */

    Configuration cfg = null;
    ApplicationContext localApplicationContext = SpringHelper.getApplicationContext();
    if (localApplicationContext != null) {
        FreeMarkerConfigurer freeMarkerConfigurer = (FreeMarkerConfigurer) SpringHelper
                .getBean("freeMarkerConfigurer", FreeMarkerConfigurer.class);
        if (freeMarkerConfigurer != null) {
            cfg = freeMarkerConfigurer.getConfiguration();
        }
    }
    try {
        // cfg.setDirectoryForTemplateLoading(new File(filePath));
        cfg.setObjectWrapper(new BeansWrapper(Configuration.VERSION_2_3_22));
        Template template = cfg.getTemplate(templateName);
        // template.setEncoding("UTF-8");
        template.process(model, writer);
        // new Template("template", new StringReader(template), cfg).process(model, writer);
    } catch (TemplateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        logger.error(e.getMessage());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        logger.error(e.getMessage());
    }
    return writer.toString();
}

From source file:ddf.security.pdp.xacml.processor.BalanaPdp.java

/**
 * Marshalls the XACML request to a string.
 * /* ww  w .  j a v  a2s.  com*/
 * @param xacmlRequestType
 *            The XACML request to marshal.
 * @return A string representation of the XACML request.
 */
private String marshal(RequestType xacmlRequestType) throws PdpException {
    ObjectFactory objectFactory = new ObjectFactory();
    Writer writer = new StringWriter();
    JAXBElement<RequestType> xacmlRequestTypeElement = objectFactory.createRequest(xacmlRequestType);

    Marshaller marshaller = null;
    String xacmlRequest = null;

    try {
        marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(xacmlRequestTypeElement, writer);

        xacmlRequest = writer.toString();
    } catch (JAXBException e) {
        String message = "Unable to marshal XACML request.";
        LOGGER.error(message);
        throw new PdpException(message, e);
    }

    LOGGER.debug("\nXACML 3.0 Request:\n{}", xacmlRequest);

    return xacmlRequest;
}

From source file:org.apache.ambari.server.orm.helpers.dbms.GenericDbmsHelper.java

@Override
public String getDropFKConstraintStatement(String tableName, String constraintName) {
    Writer writer = new StringWriter();

    ForeignKeyConstraint foreignKeyConstraint = new ForeignKeyConstraint();
    foreignKeyConstraint.setName(constraintName);
    foreignKeyConstraint.setTargetTable(tableName);

    TableDefinition tableDefinition = new TableDefinition();
    tableDefinition.setName(tableName);/*from  ww  w  .  j  a va 2  s .co  m*/
    tableDefinition.buildConstraintDeletionWriter(createStubAbstractSessionFromPlatform(databasePlatform),
            foreignKeyConstraint, writer);

    return writer.toString();
}

From source file:org.bedework.notifier.outbound.email.EmailAdaptor.java

private List<TemplateResult> applyTemplates(final Action action) throws NoteException {
    final Note note = action.getNote();
    final NotificationType nt = note.getNotification();
    final EmailSubscription sub = EmailSubscription.rewrap(action.getSub());

    List<TemplateResult> results = new ArrayList<TemplateResult>();
    try {//www .j ava  2 s .  co m
        String prefix = nt.getParsed().getDocumentElement().getPrefix();

        if (prefix == null) {
            prefix = "default";
        }

        final String abstractPath = Util.buildPath(false, Note.DeliveryMethod.email.toString(), "/", prefix,
                "/", nt.getNotification().getElementName().getLocalPart());

        File templateDir = new File(Util.buildPath(false, globalConfig.getTemplatesPath(), "/", abstractPath));
        if (templateDir.isDirectory()) {

            Map<String, Object> root = new HashMap<String, Object>();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(nt.toXml(true))));
            Element el = doc.getDocumentElement();
            NodeModel.simplify(el);
            NodeModel.useJaxenXPathSupport();
            root.put("notification", el);

            HashSet<String> recipients = new HashSet<String>();
            for (String email : sub.getEmails()) {
                recipients.add(MAILTO + email);
            }
            root.put("recipients", recipients);

            if (globalConfig.getCardDAVHost() != null && globalConfig.getCardDAVPort() != 0
                    && globalConfig.getCardDAVContextPath() != null) {
                HashMap<String, Object> vcards = new HashMap<String, Object>();
                BasicHttpClient client;
                try {
                    ArrayList<Header> hdrs = new ArrayList<Header>();
                    BasicHeader h = new BasicHeader(HEADER_ACCEPT, globalConfig.getVCardContentType());
                    hdrs.add(h);

                    client = new BasicHttpClient(globalConfig.getCardDAVHost(), globalConfig.getCardDAVPort(),
                            null, 15 * 1000);

                    XPathExpression exp = xPath.compile("//*[local-name() = 'href']");
                    NodeList nl = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);

                    HashSet<String> vcardLookups = new HashSet<String>();
                    for (int i = 0; i < nl.getLength(); i++) {
                        Node n = nl.item(i);
                        String text = n.getTextContent();

                        text = pMailto.matcher(text).replaceFirst(MAILTO);
                        if (text.startsWith(MAILTO)
                                || text.startsWith(globalConfig.getCardDAVPrincipalsPath())) {
                            vcardLookups.add(text);
                        }
                    }

                    // Get vCards for recipients too. They may not be referenced in the notification.
                    vcardLookups.addAll(recipients);

                    for (String lookup : vcardLookups) {
                        String path = Util.buildPath(false,
                                globalConfig.getCardDAVContextPath() + "/" + lookup.replace(':', '/'));

                        final InputStream is = client.get(path + VCARD_SUFFIX, "application/text", hdrs);
                        if (is != null) {
                            ObjectMapper om = new ObjectMapper();
                            @SuppressWarnings("unchecked")
                            ArrayList<Object> hm = om.readValue(is, ArrayList.class);
                            vcards.put(lookup, hm);
                        }
                    }
                    root.put("vcards", vcards);
                } catch (final Throwable t) {
                    error(t);
                }
            }

            if (nt.getNotification() instanceof ResourceChangeType) {
                ResourceChangeType chg = (ResourceChangeType) nt.getNotification();
                BedeworkConnectorConfig cfg = ((BedeworkConnector) action.getConn()).getConnectorConfig();
                BasicHttpClient cl = getClient(cfg);
                List<Header> hdrs = getHeaders(cfg, new BedeworkSubscription(action.getSub()));

                String href = null;
                if (chg.getCreated() != null) {
                    href = chg.getCreated().getHref();
                } else if (chg.getDeleted() != null) {
                    href = chg.getDeleted().getHref();
                } else if (chg.getUpdated() != null && chg.getUpdated().size() > 0) {
                    href = chg.getUpdated().get(0).getHref();
                }

                if (href != null) {
                    if (chg.getDeleted() == null) {
                        // We only have an event for the templates on a create or update, not on delete.
                        ObjectMapper om = new ObjectMapper();
                        final InputStream is = cl.get(cfg.getSystemUrl() + href, null, hdrs);
                        JsonNode a = om.readValue(is, JsonNode.class);

                        // Check for a recurrence ID on this notification.
                        XPathExpression exp = xPath.compile("//*[local-name() = 'recurrenceid']/text()");
                        String rid = exp.evaluate(doc);
                        if (rid != null && !rid.isEmpty()) {
                            Calendar rcal = Calendar.getInstance();
                            recurIdFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                            rcal.setTime(recurIdFormat.parse(rid));

                            // Find the matching recurrence ID in the JSON, and make that the only vevent object.
                            Calendar c = Calendar.getInstance();
                            ArrayNode vevents = (ArrayNode) a.get(2);
                            for (JsonNode vevent : vevents) {
                                if (vevent.size() > 1 && vevent.get(1).size() > 1) {
                                    JsonNode n = vevent.get(1).get(0);
                                    if (n.get(0).asText().equals("recurrence-id")) {
                                        if (n.get(1).size() > 0 && n.get(1).get("tzid") != null) {
                                            jsonIdFormatTZ.setTimeZone(
                                                    TimeZone.getTimeZone(n.get(1).get("tzid").asText()));
                                            c.setTime(jsonIdFormatTZ.parse(n.get(3).asText()));
                                        } else {
                                            jsonIdFormatUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
                                            c.setTime(jsonIdFormatUTC.parse(n.get(3).asText()));
                                        }
                                        if (rcal.compareTo(c) == 0) {
                                            vevents.removeAll();
                                            vevents.add(vevent);
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        root.put("vevent", (ArrayList<Object>) om.convertValue(a, ArrayList.class));
                    }

                    // TODO: Provide some calendar information to the templates. This is currently the publisher's
                    // calendar, but needs to be fixed to be the subscriber's calendar.
                    String chref = href.substring(0, href.lastIndexOf("/"));
                    hdrs.add(new BasicHeader(HEADER_DEPTH, "0"));
                    int rc = cl.sendRequest("PROPFIND", cfg.getSystemUrl() + chref, hdrs, "text/xml",
                            CALENDAR_PROPFIND.length(), CALENDAR_PROPFIND.getBytes());
                    if (rc == HttpServletResponse.SC_OK || rc == SC_MULTISTATUS) {
                        Document d = builder.parse(new InputSource(cl.getResponseBodyAsStream()));
                        HashMap<String, String> hm = new HashMap<String, String>();
                        XPathExpression exp = xPath.compile("//*[local-name() = 'href']/text()");
                        hm.put("href", exp.evaluate(d));
                        exp = xPath.compile("//*[local-name() = 'displayname']/text()");
                        hm.put("name", (String) exp.evaluate(d));
                        exp = xPath.compile("//*[local-name() = 'calendar-description']/text()");
                        hm.put("description", (String) exp.evaluate(d));
                        root.put("calendar", hm);
                    }
                }
            }

            if (note.getExtraValues() != null) {
                root.putAll(note.getExtraValues());
            }

            DefaultObjectWrapper wrapper = new DefaultObjectWrapperBuilder(
                    Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS).build();
            root.put("timezone", (TemplateHashModel) wrapper.getStaticModels().get("java.util.TimeZone"));

            // Sort files so the user can control the order of content types/body parts of the email by template file name.
            File[] templates = templateDir.listFiles(templateFilter);
            Arrays.sort(templates);
            for (File f : templates) {
                Template template = fmConfig.getTemplate(Util.buildPath(false, abstractPath, "/", f.getName()));
                Writer out = new StringWriter();
                Environment env = template.createProcessingEnvironment(root, out);
                env.process();

                TemplateResult r = new TemplateResult(f.getName(), out.toString(), env);
                if (!r.getBooleanVariable("skip")) {
                    results.add(new TemplateResult(f.getName(), out.toString(), env));
                }
            }
        }
    } catch (final Throwable t) {
        throw new NoteException(t);
    }
    return results;
}

From source file:gtu.youtube.JavaYoutubeVideoUrlHandler.java

private String getStringFromInputStream(String encoding, InputStream instream)
        throws UnsupportedEncodingException, IOException {
    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    try {/*from   www .  java 2  s  .c  o  m*/
        Reader reader = new BufferedReader(new InputStreamReader(instream, encoding));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        instream.close();
    }
    String result = writer.toString();
    return result;
}

From source file:io.datalayer.conf.IniConfigurationTest.java

/**
 * Test of save method, of class {@link INIConfiguration}.
 *//*from   www  .j  a va 2s .c  o  m*/
@Test
public void testSave() throws Exception {
    Writer writer = new StringWriter();
    INIConfiguration instance = new INIConfiguration();
    instance.addProperty("section1.var1", "foo");
    instance.addProperty("section1.var2", "451");
    instance.addProperty("section2.var1", "123.45");
    instance.addProperty("section2.var2", "bar");
    instance.addProperty("section3.var1", "true");
    instance.addProperty("section3.interpolated", "${section3.var1}");
    instance.addProperty("section3.multi", "foo");
    instance.addProperty("section3.multi", "bar");
    instance.save(writer);

    assertEquals("Wrong content of ini file", INI_DATA, writer.toString());
}

From source file:edu.ku.brc.specify.tasks.services.CollectingEventLocalityKMLGenerator.java

private String XMLtoString(Element el) {
    OutputFormat format = OutputFormat.createPrettyPrint();
    Writer writer = new StringWriter();
    try {/*from   w w  w. j a  v a 2s .c o m*/
        new XMLWriter(writer, format).write(el);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return writer.toString();
}

From source file:ninja.ResultTest.java

@Test
public void testRenderRaw() throws Exception {

    String stringToRender = "{\"user\" : \"john@woo.com\"}";

    // Construct a new result via Results.
    Result result = Results.json().renderRaw(stringToRender);

    // Setup some stuff to catch the output that gets written to the
    // output stream.
    Writer writer = new StringWriter();
    when(context.finalizeHeaders(result)).thenReturn(responseStreams);
    when(responseStreams.getWriter()).thenReturn(writer);

    Renderable renderable = (Renderable) result.getRenderable();

    // Now issue a "render": 
    renderable.render(context, result);/*from   w w w. j  a  v  a 2  s.  co  m*/

    // make sure we called the finalizeHeaders
    verify(context).finalizeHeaders(result);

    // make sure we did render the string to the OutputStream.
    assertEquals(writer.toString(), stringToRender);

    // also make sure the content type is set correctly.
    assertEquals(Result.APPLICATON_JSON, result.getContentType());

}

From source file:it.infn.ct.aleph_portlet.java

public static String convertStreamToString(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        try {/*from w w w.  j  a  v  a  2  s .c o  m*/
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);

            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {
        return "";
    }
}