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.metamorfosis.template.directive.freemarker.JFileSection.java

@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) {
    log.debug("Ejecutando <@" + getDirectiveName() + " .../>");

    if (loopVars.length != 0) {
        throw new DirectiveException("<@" + getDirectiveName() + " .../> doesn't allow loop variables.");
    }// w  w w.j a va 2s .com

    // If there is non-empty nested content:
    if (body != null) {
        try {
            String test = null;
            Set<Entry<String, SimpleScalar>> entrySet = params.entrySet();
            for (Entry<String, SimpleScalar> entry : entrySet) {
                String key = entry.getKey();
                SimpleScalar value = entry.getValue();
                if (key.equals("test")) {
                    test = value.getAsString();
                } else {
                    throw new DirectiveException(
                            "<@" + getDirectiveName() + " .../> doesn't allow " + key + " parameter");
                }
            }
            // Executes the nested body. Same as <#nested> in FTL, except
            // that we use our own writer instead of the current output writer.
            // write the file
            StringWriter sw = new StringWriter();
            BufferedWriter bw = new BufferedWriter(sw);
            body.render(bw);
            env.getOut().flush();
            bw.flush();
            sw.flush();
            bw.close();
            sw.close();

            JProject project = (JProject) SpringUtils.getProject();
            String srcPath = project.getSrcPath();
            if ("true".equalsIgnoreCase(test)) {
                srcPath = project.getTestPath();
            }

            String jFileName = JFileSection.getJFileName(sw.toString());
            String jPackagePath = JFileSection.getPackagePath(sw.toString());

            String outputFolder = File.separator + srcPath + File.separator + jPackagePath;
            TemplateProcessed tp = new TemplateProcessed(outputFolder, jFileName, sw.toString());

            super.setChanged();
            super.notifyObservers(tp);

        } catch (TemplateException ex) {
            throw new DirectiveException("Error al ejecutar la directiva '" + getDirectiveName() + "'", ex);
        } catch (IOException ex) {
            throw new DirectiveException("Error al ejecutar la directiva '" + getDirectiveName() + "'", ex);
        }
    } else {
        throw new DirectiveException("missing body");
    }
}

From source file:org.broadleafcommerce.vendor.amazon.s3.S3FileServiceProviderTest.java

/**
 * Differs from {@link #checkTestFileExists(String)} in that this uses the S3 client directly and does
 * not go through the Broadleaf file service API. This will create a test file, upload it to S3 via the
 * Broadleaf file service API, verify that the file exists via the raw S3 client, and then delete the file
 * from the bucket via the file service API again
 * // w  ww  . j  av a2s  . c  om
 * @param filename the name of the file to upload
 * @param directoryName directory that the file should be stored in on S3
 */
protected void verifyFileUploadRaw(String filename, String directoryName) throws IOException {
    propService.setProperty("aws.s3.bucketSubDirectory", directoryName);

    boolean ok = uploadTestFileTestOk(filename);
    assertTrue("File added to s3 with no exception.", ok);

    // Use the S3 client directly to ensure that it was uploaded to the sub-directory
    S3Configuration s3config = configService.lookupS3Configuration();
    AmazonS3Client s3 = s3FileProvider.getAmazonS3Client(s3config);
    s3.setRegion(RegionUtils.getRegion(s3config.getDefaultBucketRegion()));
    String s3Key = s3FileProvider.getSiteSpecificResourceName(filename);
    if (StringUtils.isNotEmpty(directoryName)) {
        s3Key = directoryName + "/" + s3Key;
    }

    // Replace the starting slash and remove the double-slashes if the directory ended with a slash
    s3Key = s3Key.startsWith("/") ? s3Key.substring(1) : s3Key;
    s3Key = FilenameUtils.normalize(s3Key);

    S3Object object = s3.getObject(new GetObjectRequest(s3config.getDefaultBucketName(), s3Key));

    InputStream inputStream = object.getObjectContent();
    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, "UTF-8");
    String fileContents = writer.toString();
    inputStream.close();
    writer.close();

    assertEquals("Retrieved the file successfully from S3", fileContents, TEST_FILE_CONTENTS);

    ok = deleteTestFile(filename);
    assertTrue("File removed from s3 with no exception.", ok);
}

From source file:org.jbpm.formModeler.service.bb.mvc.controller.ControllerServlet.java

protected void initError() {
    // Write some data to file, allowing external checking of what went wrong.
    File outputFile = new File(Application.lookup().getBaseAppDirectory() + "/ControllerError.txt");
    FileWriter writer = null;/*  w ww .j  a va2  s .  c  om*/
    try {
        StringWriter sw = new StringWriter();
        initException.printStackTrace(new PrintWriter(sw));
        writer = new FileWriter(outputFile);
        writer.write(initException.getMessage() + "\n" + sw.toString());
        outputFile.deleteOnExit();
        sw.close();
    } catch (IOException e1) {
        log.error("Error writing to log file: ", e1);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e2) {
                log.error("Error closing log file: ", e2);
            }
        }
    }
}

From source file:org.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 = FastMap.newInstance();
    }// w w w .j a v a 2 s .  co  m
    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:plugins.GerritTriggerTest.java

private Process logProcessBuilderIssues(ProcessBuilder pb, String commandName)
        throws InterruptedException, IOException {
    String dir = "";
    if (pb.directory() != null) {
        dir = pb.directory().getAbsolutePath();
    }//from w  w w .  j a v a 2s .co m
    LOGGER.info("Running : " + pb.command() + " => directory: " + dir);
    Process processToRun = pb.start();
    int result = processToRun.waitFor();
    if (result != 0) {
        StringWriter writer = new StringWriter();
        IOUtils.copy(processToRun.getErrorStream(), writer);
        LOGGER.severe("Issue occurred during command \"" + commandName + "\":\n" + writer.toString());
        writer.close();
    }
    return processToRun;
}

From source file:de.dennishoersch.web.css.parser.ParserTest.java

@Test
public void testCompressRulesSimple() throws Exception {

    StringWriter merged = new StringWriter();

    String css = getFileContent("simpleTest.css");

    Stylesheet stylesheet = Parser.parse(css);

    for (Rule rule : stylesheet.getRules()) {
        IOUtils.write(rule.toString() + "\n", merged);
    }/* w w  w .  j a  va2s . c o m*/

    merged.flush();
    merged.close();

    //        System.out.println();
    //        System.out.println(merged);
    //        System.out.println();

    // The overriding removes the 'yellow' definition
    assertThat(merged.toString(), not(containsString("yellow")));

    // Vendor prefixes in values do not override
    assertThat(merged.toString(), containsString("-moz"));
    assertThat(merged.toString(), containsString("-webkit"));

    // was ist besser oder effizienter?

    // .paddingAll, .paddingWithMarginTop {padding: 20px;}
    // .paddingWithMarginTop {margin-top: 10px;}

    // vs:
    // .paddingAll{padding:20px;}
    // .paddingWithMarginTop{padding:20px;margin-top:10px;}
}

From source file:org.apache.tiles.impl.BasicTilesContainerTest.java

/**
 * Tests is attributes are rendered correctly according to users roles.
 *
 * @throws IOException If a problem arises during rendering or writing in the writer.
 *///w  w w .ja va  2 s  .c  o m
public void testAttributeCredentials() throws IOException {
    TilesRequestContext request = EasyMock.createMock(TilesRequestContext.class);
    EasyMock.expect(request.isUserInRole("myrole")).andReturn(Boolean.TRUE);
    StringWriter writer = new StringWriter();
    EasyMock.expect(request.getWriter()).andReturn(writer);
    EasyMock.replay(request);
    Attribute attribute = new Attribute((Object) "This is the value", "myrole");
    attribute.setRenderer("string");
    container.render(attribute, request);
    writer.close();
    assertEquals("The attribute should have been rendered", "This is the value", writer.toString());
    EasyMock.reset(request);
    request = EasyMock.createMock(TilesRequestContext.class);
    EasyMock.expect(request.isUserInRole("myrole")).andReturn(Boolean.FALSE);
    EasyMock.replay(request);
    writer = new StringWriter();
    container.render(attribute, request);
    writer.close();
    assertNotSame("The attribute should have not been rendered", "This is the value", writer);
}

From source file:org.tequila.template.directive.freemarker.JFileSection.java

@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) {
    log.debug("Executing <@" + getDirectiveName() + " .../>");

    if (loopVars.length != 0) {
        throw new DirectiveException("<@" + getDirectiveName() + " .../> doesn't allow loop variables.");
    }//from w w  w .  ja  v a 2  s  . co  m

    // If there is non-empty nested content:
    if (body != null) {
        try {
            String test = null;
            Set<Entry<String, SimpleScalar>> entrySet = params.entrySet();
            for (Entry<String, SimpleScalar> entry : entrySet) {
                String key = entry.getKey();
                SimpleScalar value = entry.getValue();
                if (key.equals("test")) {
                    test = value.getAsString();
                } else {
                    throw new DirectiveException(
                            "<@" + getDirectiveName() + " .../> doesn't allow " + key + " parameter");
                }
            }
            // Executes the nested body. Same as <#nested> in FTL, except
            // that we use our own writer instead of the current output writer.
            // write the file
            StringWriter sw = new StringWriter();
            BufferedWriter bw = new BufferedWriter(sw);
            body.render(bw);
            env.getOut().flush();
            bw.flush();
            sw.flush();
            bw.close();
            sw.close();

            JProject project = (JProject) projectHolder.getProject();
            String srcPath = project.getSrcPath();
            if ("true".equalsIgnoreCase(test)) {
                srcPath = project.getTestPath();
            }

            String jFileName = JFileSection.getJFileName(sw.toString());
            String jPackagePath = JFileSection.getPackagePath(sw.toString());

            TemplateProcessed tp = new TemplateProcessed();
            tp.setOutputFolder(File.separator + srcPath + File.separator + jPackagePath);
            tp.setOutputFileName(jFileName);
            tp.setTemplateResult(sw.toString());

            super.setChanged();
            super.notifyObservers(tp);

        } catch (TemplateException ex) {
            throw new DirectiveException("Error al ejecutar la directiva '" + getDirectiveName() + "'", ex);
        } catch (IOException ex) {
            throw new DirectiveException("Error al ejecutar la directiva '" + getDirectiveName() + "'", ex);
        }
    } else {
        throw new DirectiveException("missing body");
    }
}

From source file:org.apache.axis.deployment.wsdd.WSDDDocument.java

/**
 * get the deployment as a DOM.//from  w  w w.  j av  a  2 s.c  o m
 * Requires that the deployment member variable is not null.
 * @return
 * @throws ConfigurationException
 */
public Document getDOMDocument() throws ConfigurationException {
    StringWriter writer = new StringWriter();
    SerializationContext context = new SerializationContext(writer);
    context.setPretty(true);
    try {
        deployment.writeToContext(context);
    } catch (Exception e) {
        log.error(Messages.getMessage("exception00"), e);
    }
    try {
        writer.close();
        return XMLUtils.newDocument(new InputSource(new StringReader(writer.getBuffer().toString())));
    } catch (Exception e) {
        return null;
    }
}

From source file:edu.emory.bmi.aiw.i2b2export.output.ValueColumnOutputFormatterTest.java

String formatStringTestFormatEmpty(ValueColumnOutputFormatter formatter) throws IOException {
    StringWriter sw = new StringWriter();
    boolean succeeded = false;
    try {//w  ww  .ja  v  a 2  s .com
        try (BufferedWriter w = new BufferedWriter(sw)) {
            formatter.format(new ArrayList<Observation>(), w, 0);
        }
        sw.close();
        succeeded = true;
    } finally {
        if (!succeeded) {
            try {
                sw.close();
            } catch (IOException ignore) {
            }
        }
    }
    return sw.toString();
}