Example usage for java.io StringWriter close

List of usage examples for java.io StringWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closing a StringWriter has no effect.

Usage

From source file:org.wso2.carbon.identity.idp.metadata.saml2.builder.DefaultIDPMetadataBuilder.java

public String marshallDescriptor(EntityDescriptor entityDescriptor) throws MetadataException {

    DocumentBuilderFactory factory = IdentityUtil.getSecuredDocumentBuilderFactory();
    DocumentBuilder builder;/*  w  w  w.  j a  v  a2s . c o m*/
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new MetadataException("Error while creating the document.", e);
    }

    if (log.isDebugEnabled()) {
        log.debug("Marshalling the metadata element contents");
    }
    Document document = builder.newDocument();
    Marshaller out = org.opensaml.xml.Configuration.getMarshallerFactory().getMarshaller(entityDescriptor);

    try {
        out.marshall(entityDescriptor, document);
    } catch (MarshallingException e) {
        throw new MetadataException("Error while marshalling the descriptor.", e);
    }

    if (log.isDebugEnabled()) {
        log.debug("Marshalling metadata completed.");
    }
    org.apache.xml.security.Init.init();

    Transformer transformer;
    StreamResult streamResult;
    StringWriter stringWriter = new StringWriter();
    try {
        transformer = TransformerFactory.newInstance().newTransformer();

        streamResult = new StreamResult(stringWriter);
        DOMSource source = new DOMSource(document);
        transformer.transform(source, streamResult);
        stringWriter.close();
        return stringWriter.toString();
    } catch (TransformerConfigurationException e) {
        log.error("Error Occurred while creating XML transformer", e);
    } catch (IOException e) {
        log.error("Error Occurred while creating XML transformer", e);
    } catch (TransformerException e) {
        log.error("Error Occurred while creating XML transformer", e);
    }

    return stringWriter.toString();
}

From source file:org.unitime.timetable.events.EventEmail.java

private String message() throws IOException, TemplateException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_0);
    cfg.setClassForTemplateLoading(EventEmail.class, "");
    cfg.setLocale(Localization.getJavaLocale());
    cfg.setOutputEncoding("utf-8");
    Template template = cfg.getTemplate("confirmation.ftl");
    Map<String, Object> input = new HashMap<String, Object>();
    input.put("msg", MESSAGES);
    input.put("const", CONSTANTS);
    input.put("subject", subject());
    input.put("event", event());
    input.put("operation", request().getOperation() == null ? "NONE" : request().getOperation().name());
    if (response().hasCreatedMeetings())
        input.put("created", EventInterface.getMultiMeetings(response().getCreatedMeetings(), true));
    if (response().hasDeletedMeetings())
        input.put("deleted", EventInterface.getMultiMeetings(response().getDeletedMeetings(), true));
    if (response().hasCancelledMeetings())
        input.put("cancelled", EventInterface.getMultiMeetings(response().getCancelledMeetings(), true));
    if (response().hasUpdatedMeetings())
        input.put("updated", EventInterface.getMultiMeetings(response().getUpdatedMeetings(), true));
    if (request().hasMessage())
        input.put("message", request().getMessage());
    if (request().getEvent().getId() != null) {
        if (event().hasMeetings())
            input.put("meetings", EventInterface.getMultiMeetings(event().getMeetings(), true));
        else/*from w  w w.ja  v  a2 s .com*/
            input.put("meetings", new TreeSet<MultiMeetingInterface>());
    }
    input.put("version", MESSAGES.pageVersion(Constants.getVersion(), Constants.getReleaseDate()));
    input.put("ts", new Date());
    input.put("link", ApplicationProperty.UniTimeUrl.value());
    input.put("sessionId", iRequest.getSessionId());

    StringWriter s = new StringWriter();
    template.process(input, new PrintWriter(s));
    s.flush();
    s.close();

    return s.toString();
}

From source file:org.wso2.carbon.appfactory.repository.provider.common.AbstractRepositoryProvider.java

protected byte[] getRepositoryAsString(Repository repo) throws RepositoryMgtException {
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMElement repository = factory.createOMElement(REPOSITORY_XML_ROOT_ELEMENT, null);
    OMElement name = factory.createOMElement(REPOSITORY_NAME_ELEMENT, null);
    name.setText(repo.getName());//from w  w  w. j av a 2  s .c  o  m
    repository.addChild(name);
    OMElement type = factory.createOMElement(REPOSITORY_TYPE_ELEMENT, null);
    type.setText(repo.getType());
    repository.addChild(type);

    for (Permission perm : repo.getPermissions()) {

        OMElement permission = factory.createOMElement(PERMISSION_XML_ROOT_ELEMENT, null);
        OMElement groupPermission = factory.createOMElement(PERMISSION_GROUP_PERMISSION_ELEMENT, null);
        groupPermission.setText(String.valueOf(perm.getGroupPermission()));
        permission.addChild(groupPermission);

        OMElement permName = factory.createOMElement(PERMISSION_NAME_ELEMENT, null);
        permName.setText(perm.getName());
        OMElement permType = factory.createOMElement(PERMISSION_TYPE_ELEMENT, null);
        permType.setText(perm.getType().toString());

        permission.addChild(permName);
        permission.addChild(permType);
        repository.addChild(permission);
    }
    StringWriter writer = new StringWriter();
    try {
        repository.serialize(writer);
    } catch (XMLStreamException e) {
        String msg = "Error while serializing the payload";
        log.error(msg, e);
        throw new RepositoryMgtException(msg, e);
    } finally {
        try {
            writer.close();
        } catch (IOException e) {
            String msg = "Error while closing the reader";
            log.error(msg, e);
        }
    }
    return writer.toString().getBytes();
}

From source file:com.rossjourdain.XeroClientLive.java

public String getTrackingCategoryOutput() throws XeroClientException, XeroClientUnexpectedException {
    try {//  www .  j  a  v  a  2 s  .co m
        String url = endpointUrl + "TrackingCategories";
        OAuthMessage oResponse = getClient().invoke(getAccessor(), OAuthMessage.GET, url, null);
        final InputStream stream = oResponse.getBodyAsStream();
        StringWriter strWriter = new StringWriter();
        IOUtils.copy(stream, strWriter, "UTF-8");
        final String output = strWriter.toString();
        strWriter.close();
        return output;
    } catch (OAuthProblemException ex) {
        if (ex.getHttpStatusCode() == 404) {
            log.debug("Server responded with 'not found' for contact search");
            return null;
        } else {
            log.error(ex.getMessage(), ex);
            throw new XeroClientException("Error getting contacts", ex);
        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        throw new XeroClientUnexpectedException(ex.getMessage(), ex);
    }
}

From source file:Repackage.java

StringBuffer readInputStream(InputStream is) throws IOException {
    Reader r = new InputStreamReader(is);
    StringWriter w = new StringWriter();

    copy(r, w);//from www.  ja v  a2s .  c o m

    w.close();
    r.close();

    return w.getBuffer();
}

From source file:com.jaeksoft.searchlib.scheduler.task.TaskQueryXsltPost.java

@Override
public void execute(Client client, TaskProperties properties, Variables variables, TaskLog taskLog)
        throws SearchLibException {

    taskLog.setInfo("Query check");

    String searchTemplate = properties.getValue(propSearchTemplate);
    String queryString = properties.getValue(propQueryString);
    String xsl = properties.getValue(propXsl);
    String url = properties.getValue(propUrl);
    String httpLogin = properties.getValue(propHttpLogin);
    String httpPassword = properties.getValue(propHttpPassword);
    String contentType = properties.getValue(propHttpContentType);
    boolean useProxy = Boolean.TRUE.toString().equals(properties.getValue(propUseProxy));

    URI uri;/*from www . j a v  a2 s. com*/
    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        throw new SearchLibException(e);
    }

    AbstractSearchRequest searchRequest = (AbstractSearchRequest) client.getNewRequest(searchTemplate);
    if (searchRequest == null)
        throw new SearchLibException("Request template  " + searchTemplate + " not found");
    searchRequest.setQueryString(queryString);
    taskLog.setInfo("Execute request " + searchTemplate);
    AbstractResultSearch resultSearch = (AbstractResultSearch) client.request(searchRequest);

    StringWriter sw = null;
    PrintWriter pw = null;
    StringReader sr = null;

    try {

        sw = new StringWriter();
        pw = new PrintWriter(sw);
        taskLog.setInfo("Render XML");
        new RenderSearchXml(resultSearch).render(pw);
        pw.close();
        pw = null;
        sw.close();
        String content = sw.toString();
        sw = null;

        sr = new StringReader(content);

        if (!StringUtils.isEmpty(xsl)) {
            taskLog.setInfo("XSL transformation");
            content = DomUtils.xslt(new StreamSource(sr), xsl);
            if (content == null)
                throw new SearchLibException("XSL transformation failed");
        }

        CredentialItem credentialItem = null;
        if (!StringUtils.isEmpty(httpLogin) && !StringUtils.isEmpty(httpPassword))
            credentialItem = new CredentialItem(CredentialType.BASIC_DIGEST, null, httpLogin, httpPassword,
                    null, null);
        HttpDownloader downloader = client.getWebCrawlMaster().getNewHttpDownloader(true, null, useProxy);

        List<HeaderItem> headerItems = null;
        if (!StringUtils.isEmpty(contentType)) {
            headerItems = new ArrayList<HeaderItem>(1);
            headerItems.add(new HeaderItem("Content-Type", contentType));
        }

        taskLog.setInfo("Uploading " + FileUtils.byteCountToDisplaySize(content.length()));
        DownloadItem downloadItem = downloader.post(uri, credentialItem, headerItems, null,
                new StringEntity(content));
        downloadItem.checkNoErrorRange(200, 201);
        taskLog.setInfo("Done");
    } catch (Exception e) {
        throw new SearchLibException(e);
    } finally {
        IOUtils.close(pw, sw, sr);
    }

}

From source file:Repackage.java

StringBuffer readFile(File f) throws IOException {
    InputStream in = new FileInputStream(f);
    Reader r = new InputStreamReader(in);
    StringWriter w = new StringWriter();

    copy(r, w);/*from  ww  w  .  j av a  2 s  . co m*/

    w.close();
    r.close();
    in.close();

    return w.getBuffer();
}

From source file:io.dataapps.chlorine.hive.JsonConverter.java

@Override
public Object convert(Object arg0) {
    try {/*from w  ww.  j  av  a  2  s .  c  o m*/
        StringWriter writer = new StringWriter();
        JsonGenerator gen = jsonFactory.createJsonGenerator(writer);
        inspHandle.generateJson(gen, arg0);
        gen.close();
        writer.close();
        return new Text(writer.toString());
    } catch (IOException e) {
        LOG.error(e);
        return null;
    }
}

From source file:com.cloudera.lib.service.instrumentation.TestInstrumentationService.java

@Test
public void timer() throws Exception {
    InstrumentationService.Timer timer = new InstrumentationService.Timer(2);
    InstrumentationService.Cron cron = new InstrumentationService.Cron();

    long ownStart;
    long ownEnd;//from   ww w .  jav  a 2s.  co m
    long totalStart;
    long totalEnd;
    long ownDelta;
    long totalDelta;
    long avgTotal;
    long avgOwn;

    cron.start();
    ownStart = System.currentTimeMillis();
    totalStart = ownStart;
    ownDelta = 0;
    sleep(100);

    cron.stop();
    ownEnd = System.currentTimeMillis();
    ownDelta += ownEnd - ownStart;
    sleep(100);

    cron.start();
    ownStart = System.currentTimeMillis();
    sleep(100);

    cron.stop();
    ownEnd = System.currentTimeMillis();
    ownDelta += ownEnd - ownStart;
    totalEnd = ownEnd;
    totalDelta = totalEnd - totalStart;

    avgTotal = totalDelta;
    avgOwn = ownDelta;

    timer.addCron(cron);
    long[] values = timer.getValues();
    Assert.assertEquals(values[InstrumentationService.Timer.LAST_TOTAL], totalDelta, 20);
    Assert.assertEquals(values[InstrumentationService.Timer.LAST_OWN], ownDelta, 20);
    Assert.assertEquals(values[InstrumentationService.Timer.AVG_TOTAL], avgTotal, 20);
    Assert.assertEquals(values[InstrumentationService.Timer.AVG_OWN], avgOwn, 20);

    cron = new InstrumentationService.Cron();

    cron.start();
    ownStart = System.currentTimeMillis();
    totalStart = ownStart;
    ownDelta = 0;
    sleep(200);

    cron.stop();
    ownEnd = System.currentTimeMillis();
    ownDelta += ownEnd - ownStart;
    sleep(200);

    cron.start();
    ownStart = System.currentTimeMillis();
    sleep(200);

    cron.stop();
    ownEnd = System.currentTimeMillis();
    ownDelta += ownEnd - ownStart;
    totalEnd = ownEnd;
    totalDelta = totalEnd - totalStart;

    avgTotal = (avgTotal * 1 + totalDelta) / 2;
    avgOwn = (avgOwn * 1 + ownDelta) / 2;

    timer.addCron(cron);
    values = timer.getValues();
    Assert.assertEquals(values[InstrumentationService.Timer.LAST_TOTAL], totalDelta, 20);
    Assert.assertEquals(values[InstrumentationService.Timer.LAST_OWN], ownDelta, 20);
    Assert.assertEquals(values[InstrumentationService.Timer.AVG_TOTAL], avgTotal, 20);
    Assert.assertEquals(values[InstrumentationService.Timer.AVG_OWN], avgOwn, 20);

    avgTotal = totalDelta;
    avgOwn = ownDelta;

    cron = new InstrumentationService.Cron();

    cron.start();
    ownStart = System.currentTimeMillis();
    totalStart = ownStart;
    ownDelta = 0;
    sleep(300);

    cron.stop();
    ownEnd = System.currentTimeMillis();
    ownDelta += ownEnd - ownStart;
    sleep(300);

    cron.start();
    ownStart = System.currentTimeMillis();
    sleep(300);

    cron.stop();
    ownEnd = System.currentTimeMillis();
    ownDelta += ownEnd - ownStart;
    totalEnd = ownEnd;
    totalDelta = totalEnd - totalStart;

    avgTotal = (avgTotal * 1 + totalDelta) / 2;
    avgOwn = (avgOwn * 1 + ownDelta) / 2;

    cron.stop();
    timer.addCron(cron);
    values = timer.getValues();
    Assert.assertEquals(values[InstrumentationService.Timer.LAST_TOTAL], totalDelta, 20);
    Assert.assertEquals(values[InstrumentationService.Timer.LAST_OWN], ownDelta, 20);
    Assert.assertEquals(values[InstrumentationService.Timer.AVG_TOTAL], avgTotal, 20);
    Assert.assertEquals(values[InstrumentationService.Timer.AVG_OWN], avgOwn, 20);

    JSONObject json = (JSONObject) new JSONParser().parse(timer.toJSONString());
    Assert.assertEquals(json.size(), 4);
    Assert.assertEquals(json.get("lastTotal"), values[InstrumentationService.Timer.LAST_TOTAL]);
    Assert.assertEquals(json.get("lastOwn"), values[InstrumentationService.Timer.LAST_OWN]);
    Assert.assertEquals(json.get("avgTotal"), values[InstrumentationService.Timer.AVG_TOTAL]);
    Assert.assertEquals(json.get("avgOwn"), values[InstrumentationService.Timer.AVG_OWN]);

    StringWriter writer = new StringWriter();
    timer.writeJSONString(writer);
    writer.close();
    json = (JSONObject) new JSONParser().parse(writer.toString());
    Assert.assertEquals(json.size(), 4);
    Assert.assertEquals(json.get("lastTotal"), values[InstrumentationService.Timer.LAST_TOTAL]);
    Assert.assertEquals(json.get("lastOwn"), values[InstrumentationService.Timer.LAST_OWN]);
    Assert.assertEquals(json.get("avgTotal"), values[InstrumentationService.Timer.AVG_TOTAL]);
    Assert.assertEquals(json.get("avgOwn"), values[InstrumentationService.Timer.AVG_OWN]);
}

From source file:org.glite.slcs.pki.bouncycastle.PKCS10.java

/**
 * @return The PEM encoded string representation.
 *///  w w  w .j  a v  a2  s . c  o  m
public String getPEMEncoded() {
    StringWriter sw = new StringWriter();
    PEMWriter pem = new PEMWriter(sw);
    try {
        pem.writeObject(this.bcPKCS10_);
    } catch (IOException e) {
        LOG.warn("Failed to write PKCS10 in PEM format", e);
        return null;
    } finally {
        try {
            pem.close();
            sw.close();
        } catch (IOException e) {
            // ignored
        }
    }
    return sw.toString();
}