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.codelibs.fess.api.BaseJsonApiManager.java

protected void writeJsonResponse(final int status, final String body, final Throwable t) {
    if (t == null) {
        writeJsonResponse(status, body, (String) null);
        return;//w  w  w .j a v  a2 s  . c  o m
    }

    if (t instanceof InvalidAccessTokenException) {
        final InvalidAccessTokenException e = (InvalidAccessTokenException) t;
        final HttpServletResponse response = LaResponseUtil.getResponse();
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setHeader("WWW-Authenticate", "Bearer error=\"" + e.getType() + "\"");
    }

    final StringBuilder sb = new StringBuilder();
    if (StringUtil.isBlank(t.getMessage())) {
        sb.append(t.getClass().getName());
    } else {
        sb.append(t.getMessage());
    }
    final StringWriter sw = new StringWriter();
    t.printStackTrace(new PrintWriter(sw));
    sb.append(" [ ").append(sw.toString()).append(" ]");
    try {
        sw.close();
    } catch (final IOException ignore) {
    }
    writeJsonResponse(status, body, sb.toString());
}

From source file:com.glaf.template.engine.FreemarkerTemplateEngine.java

public void evaluate(String name, String content, Map<String, Object> context, Writer writer) {
    try {//from w  w  w .ja  va 2  s .com
        long startTime = System.currentTimeMillis();
        StringWriter out = new StringWriter();

        freemarker.template.Template t = freemarker.template.Template.getPlainTextTemplate(name, content,
                configuration);
        t.process(context, out);
        out.flush();
        out.close();
        String text = out.toString();
        writer.write(text);
        long endTime = System.currentTimeMillis();
        long renderTime = (endTime - startTime);

        logger.debug("Rendered [" + name + "] in " + renderTime + " milliseconds");
        logger.debug(text);
    } catch (Exception ex) {
        logger.debug("error template content:" + content);
        throw new RuntimeException(ex);
    }
}

From source file:org.apache.ofbiz.content.data.DataResourceWorker.java

public static void writeDataResourceText(GenericValue dataResource, String mimeTypeId, Locale locale,
        Map<String, Object> templateContext, Delegator delegator, Appendable out, boolean cache)
        throws IOException, GeneralException {
    Map<String, Object> context = UtilGenerics.checkMap(templateContext.get("context"));
    if (context == null) {
        context = new HashMap<String, Object>();
    }//from  ww w.  j  a  v  a  2 s  .c  om
    String webSiteId = (String) templateContext.get("webSiteId");
    if (UtilValidate.isEmpty(webSiteId)) {
        if (context != null)
            webSiteId = (String) context.get("webSiteId");
    }

    String https = (String) templateContext.get("https");
    if (UtilValidate.isEmpty(https)) {
        if (context != null)
            https = (String) context.get("https");
    }

    String rootDir = (String) templateContext.get("rootDir");
    if (UtilValidate.isEmpty(rootDir)) {
        if (context != null)
            rootDir = (String) context.get("rootDir");
    }

    String dataResourceId = dataResource.getString("dataResourceId");
    String dataResourceTypeId = dataResource.getString("dataResourceTypeId");

    // default type
    if (UtilValidate.isEmpty(dataResourceTypeId)) {
        dataResourceTypeId = "SHORT_TEXT";
    }

    // text types
    if ("SHORT_TEXT".equals(dataResourceTypeId) || "LINK".equals(dataResourceTypeId)) {
        String text = dataResource.getString("objectInfo");
        writeText(dataResource, text, templateContext, mimeTypeId, locale, out);
    } else if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)) {
        GenericValue electronicText = EntityQuery.use(delegator).from("ElectronicText")
                .where("dataResourceId", dataResourceId).cache(cache).queryOne();
        if (electronicText != null) {
            String text = electronicText.getString("textData");
            writeText(dataResource, text, templateContext, mimeTypeId, locale, out);
        }

        // object types
    } else if (dataResourceTypeId.endsWith("_OBJECT")) {
        String text = (String) dataResource.get("dataResourceId");
        writeText(dataResource, text, templateContext, mimeTypeId, locale, out);

        // resource type
    } else if (dataResourceTypeId.equals("URL_RESOURCE")) {
        String text = null;
        URL url = FlexibleLocation.resolveLocation(dataResource.getString("objectInfo"));

        if (url.getHost() != null) { // is absolute
            InputStream in = url.openStream();
            int c;
            StringWriter sw = new StringWriter();
            while ((c = in.read()) != -1) {
                sw.write(c);
            }
            sw.close();
            text = sw.toString();
        } else {
            String prefix = DataResourceWorker.buildRequestPrefix(delegator, locale, webSiteId, https);
            String sep = "";
            if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
                sep = "/";
            }
            String fixedUrlStr = prefix + sep + url.toString();
            URL fixedUrl = new URL(fixedUrlStr);
            text = (String) fixedUrl.getContent();
        }
        out.append(text);

        // file types
    } else if (dataResourceTypeId.endsWith("_FILE_BIN")) {
        writeText(dataResource, dataResourceId, templateContext, mimeTypeId, locale, out);
    } else if (dataResourceTypeId.endsWith("_FILE")) {
        String dataResourceMimeTypeId = dataResource.getString("mimeTypeId");
        String objectInfo = dataResource.getString("objectInfo");

        if (dataResourceMimeTypeId == null || dataResourceMimeTypeId.startsWith("text")) {
            renderFile(dataResourceTypeId, objectInfo, rootDir, out);
        } else {
            writeText(dataResource, dataResourceId, templateContext, mimeTypeId, locale, out);
        }
    } else {
        throw new GeneralException("The dataResourceTypeId [" + dataResourceTypeId
                + "] is not supported in renderDataResourceAsText");
    }
}

From source file:com.moviejukebox.themoviedb.tools.WebBrowser.java

public static String request(URL url) throws MovieDbException {
    StringWriter content = null;

    try {//  w  w w. j  a  v  a 2s  .  co m
        content = new StringWriter();

        BufferedReader in = null;
        URLConnection cnx = null;
        try {
            cnx = openProxiedConnection(url);

            sendHeader(cnx);
            readHeader(cnx);

            in = new BufferedReader(new InputStreamReader(cnx.getInputStream(), getCharset(cnx)));
            String line;
            while ((line = in.readLine()) != null) {
                content.write(line);
            }
        } finally {
            if (in != null) {
                in.close();
            }

            if (cnx instanceof HttpURLConnection) {
                ((HttpURLConnection) cnx).disconnect();
            }
        }
        return content.toString();
    } catch (IOException ex) {
        throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR, null, ex);
    } finally {
        if (content != null) {
            try {
                content.close();
            } catch (IOException ex) {
                LOGGER.debug("Failed to close connection: " + ex.getMessage());
            }
        }
    }
}

From source file:org.apache.taverna.activities.interaction.InteractionActivityRunnable.java

private String processTemplate(final Template template, final VelocityContext context) throws IOException {
    final StringWriter resultWriter = new StringWriter();
    template.merge(context, resultWriter);
    resultWriter.close();
    return resultWriter.toString();
}

From source file:com.sangupta.pep.Generator.java

private String render() throws IOException {
    final String template = FileUtils.readFileToString(new File("./themes/default/base.html"));

    Slide[] slides = fetchContents();/*from  www.ja v a 2 s.  com*/
    Map<String, Object> contextVariables = getTemplateVariables(slides);

    VelocityContext context = new VelocityContext();
    if (contextVariables != null) {
        for (Entry<String, Object> entry : contextVariables.entrySet()) {
            context.put(entry.getKey(), entry.getValue());
        }
    }

    StringWriter writer = new StringWriter();
    Velocity.evaluate(context, writer, "landslide", template);

    writer.close();

    String html = writer.toString();
    return HtmlUtils.tidyHtml(html);
}

From source file:nl.ru.cmbi.vase.web.rest.JobRestResource.java

@MethodMapping(value = "/status/{jobid}", httpMethod = HttpMethod.GET, produces = RestMimeTypes.TEXT_PLAIN)
public String status(String jobid) {

    if (Config.isXmlOnly() || !Config.hsspPdbCacheEnabled()) {

        log.warn("rest/status was requested, but not enabled");

        // hssp job submission is not allowed if hssp is turned off
        throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_NOT_FOUND);
    }//  w w w. java  2s. c om

    try {
        URL url = new URL(hsspRestURL + "/status/pdb_file/hssp_stockholm/" + jobid + "/");

        StringWriter writer = new StringWriter();
        IOUtils.copy(url.openStream(), writer);
        writer.close();

        JSONObject output = new JSONObject(writer.toString());

        return output.getString("status");

    } catch (Exception e) {

        log.error(e.getMessage(), e);
        throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
}

From source file:com.github.xmltopdf.JasperPdfGenerator.java

private String applyVelocityTemplate(String templateData) throws Exception {
    Properties properties = new Properties();
    properties.setProperty("resource.loader", "string");
    properties.setProperty("string.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.StringResourceLoader");
    properties.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");
    properties.setProperty("userdirective",
            "com.github.xmltopdf.MoneyUAHDirective," + "com.github.xmltopdf.MoneyToStrDirective,"
                    + "com.github.xmltopdf.DateDirective," + "com.github.xmltopdf.UkrToLatinDirective");
    Velocity.init(properties);/*from   ww w  .  j av  a  2 s .c o  m*/

    StringResourceRepository repo = StringResourceLoader.getRepository();
    repo.putStringResource("template", templateData);
    Template template = Velocity.getTemplate("template", "UTF-8");
    StringWriter writer = new StringWriter();
    VelocityContext context = new VelocityContext();
    context.put("xml", xmlTag);
    template.merge(context, writer);
    writer.flush();
    writer.close();
    return writer.toString();
}

From source file:com.agc.tmdb.Util.URLFetcher.java

/**
 * Can be used to Fetch the URL, where URL is Java.net.URL.
 * @param url/*from   w w  w  . j  a v  a 2 s.c o  m*/
 * @return
 * @throws TMDbException
 */
public static String fetch(URL url) throws TMDbException {
    System.out.println("URL: " + url);
    StringWriter content = null;

    try {
        content = new StringWriter();

        BufferedReader in = null;
        URLConnection connectionObject = null;
        try {
            connectionObject = openConnection(url);
            setBrowserProperties(connectionObject);

            in = new BufferedReader(
                    new InputStreamReader(connectionObject.getInputStream(), getCharset(connectionObject)));
            String line;
            while ((line = in.readLine()) != null) {
                content.write(line);
            }
        } finally {
            if (in != null) {
                in.close();
            }

            if (connectionObject instanceof HttpURLConnection) {
                ((HttpURLConnection) connectionObject).disconnect();
            }
        }
        return content.toString();
    } catch (IOException ex) {
        throw new TMDbException(TMDbExceptionTypes.EXCEPTION_CONNECTION_ERROR, null, ex);
    } finally {
        if (content != null) {
            try {
                content.close();
            } catch (IOException ex) {
                throw new TMDbException(TMDbExceptionTypes.EXCEPTION_CONNECTION_ERROR,
                        "Failed to Close the connection.", ex);
            }
        }
    }
}