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.geowebcache.rest.layers.TileLayerRestlet.java

/**
 * We separate out the internal to make unit testing easier
 * /*w w w  .  j ava  2s .com*/
 * @param layerName
 * @param formatExtension
 * @param is
 * @return
 * @throws RestletException
 * @throws IOException
 */
protected TileLayer deserializeAndCheckLayerInternal(String layerName, String formatExtension, InputStream is)
        throws RestletException, IOException {

    XStream xs = xmlConfig.getConfiguredXStreamWithContext(new XStream(new DomDriver()), Context.REST);

    TileLayer newLayer;

    try {
        if (formatExtension.equalsIgnoreCase("xml")) {
            newLayer = (TileLayer) xs.fromXML(is);
        } else if (formatExtension.equalsIgnoreCase("json")) {
            HierarchicalStreamDriver driver = new JettisonMappedXmlDriver();
            HierarchicalStreamReader hsr = driver.createReader(is);
            // See http://jira.codehaus.org/browse/JETTISON-48
            StringWriter writer = new StringWriter();
            new HierarchicalStreamCopier().copy(hsr, new PrettyPrintWriter(writer));
            writer.close();
            newLayer = (TileLayer) xs.fromXML(writer.toString());
        } else {
            throw new RestletException("Unknown or missing format extension: " + formatExtension,
                    Status.CLIENT_ERROR_BAD_REQUEST);
        }
    } catch (ConversionException xstreamExceptionWrapper) {
        Throwable cause = xstreamExceptionWrapper.getCause();
        if (cause instanceof Error) {
            throw (Error) cause;
        }
        if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
        }
        if (cause != null) {
            throw new RestletException(cause.getMessage(), Status.SERVER_ERROR_INTERNAL, (Exception) cause);
        } else {
            throw new RestletException(xstreamExceptionWrapper.getMessage(), Status.SERVER_ERROR_INTERNAL,
                    xstreamExceptionWrapper);
        }
    }

    if (!newLayer.getName().equals(layerName)) {
        throw new RestletException(
                "There is a mismatch between the name of the "
                        + " layer in the submission and the URL you specified.",
                Status.CLIENT_ERROR_BAD_REQUEST);
    }

    // Check that the parameter filters deserialized correctly
    if (newLayer.getParameterFilters() != null) {
        try {
            for (@SuppressWarnings("unused")
            ParameterFilter filter : newLayer.getParameterFilters()) {
                // Don't actually need to do anything here.  Just iterate over the elements 
                // casting them into ParameterFilter
            }
        } catch (ClassCastException ex) {
            // By this point it has already been turned into a POJO, so the XML is no longer 
            // available.  Otherwise it would be helpful to include in the error message.
            throw new RestletException(
                    "parameterFilters contains an element that is not " + "a known ParameterFilter",
                    Status.CLIENT_ERROR_BAD_REQUEST);
        }
    }

    return newLayer;
}

From source file:siddur.solidtrust.insurancehelper.InsuranceService.java

public int saveRecordsFromFile(File file, boolean replace, List<String> exceptions) throws Exception {
    if (replace) {
        //delete old ones
        String ql = "truncate table InsuranceCar";
        int rows = persister.executeNativeQuery(ql);
        log4j.info("clean " + rows + " overdue rows");
    }/*  w  w  w  .jav a2s .  c o m*/

    InputStream is = new FileInputStream(file);
    Reader br = new InputStreamReader(is);
    StringWriter ws = new StringWriter((int) file.length());

    int bufSize = 1024 * 8;
    char[] buf = new char[bufSize];
    int len = 0;
    while ((len = br.read(buf)) > 0) {
        ws.write(buf, 0, len);
    }

    br.close();
    ws.close();

    int batch = 5000;
    List<InsuranceCar> cars = new ArrayList<InsuranceCar>(batch);
    int i = 0;
    StringTokenizer st = new StringTokenizer(ws.toString());
    while (st.hasMoreTokens()) {
        String s = st.nextToken().trim();
        if (s.length() != 6) {
            exceptions.add(s);
            continue;
        }
        i++;
        InsuranceCar car = new InsuranceCar();
        car.setLicensePlate(s);
        car.setTableName(tables[0]); // Marktplaats
        cars.add(car);
        if (i % batch == 0) {
            if (replace) {
                persister.persist(cars);
            } else {
                persister.merge(cars);
            }
            log4j.info("Saved " + cars.size() + " records");
            cars = new ArrayList<InsuranceCar>(batch);
        }
    }

    if (replace) {
        persister.persist(cars);
    } else {
        persister.merge(cars);
    }
    log4j.info("Saved " + cars.size() + " records");
    log4j.info("Totally saved " + i + " records");

    log4j.info("Save parralel records of other tables");
    for (int j = 1; j < tables.length; j++) {
        String table = tables[j];
        String ql = "insert into InsuranceCar(licensePlate, tableName, stadagen, status)"
                + " select licensePlate, '" + table + "', 0, 0 from InsuranceCar" + " where tableName='"
                + tables[0] + "'";
        int rows = persister.executeNativeQuery(ql);
        log4j.info("Duplicate '" + table + "' from '" + tables[0] + "': " + rows);
    }
    return i;
}

From source file:com.lucidtechnics.blackboard.util.error.ErrorManager.java

public void warnException(Throwable _throwable, Log _logger) {
    PrintWriter printWriter = null;
    StringWriter stringWriter = null;

    try {/*from w  ww  . j  a  v  a 2 s  . c om*/
        _logger.warn("Encountered exception with message: " + _throwable.getMessage());
        _logger.warn("WITH JAVA STACK TRACE:\n");

        stringWriter = new StringWriter();
        printWriter = new PrintWriter(stringWriter);

        _throwable.printStackTrace(printWriter);

        _logger.error(stringWriter.toString());
    } catch (Exception e) {

    } finally {
        if (stringWriter != null) {
            try {
                stringWriter.close();
            } catch (Exception e) {
            }
        }
        if (printWriter != null) {
            try {
                printWriter.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.lucidtechnics.blackboard.util.error.ErrorManager.java

public void logException(Throwable _throwable, Log _logger) {
    PrintWriter printWriter = null;
    StringWriter stringWriter = null;

    try {//from  w ww.  j a  v a 2  s.  c  om
        _logger.error("Encountered exception with message: " + _throwable.getMessage());
        _logger.error("WITH JAVA STACK TRACE:\n");

        stringWriter = new StringWriter();
        printWriter = new PrintWriter(stringWriter);

        _throwable.printStackTrace(printWriter);

        _logger.error(stringWriter.toString());
    } catch (Exception e) {

    } finally {
        if (stringWriter != null) {
            try {
                stringWriter.close();
            } catch (Exception e) {
            }
        }
        if (printWriter != null) {
            try {
                printWriter.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:org.rhq.enterprise.server.rest.AbstractRestBean.java

/**
 * Renders the passed object with the help of a freemarker template into a string. Freemarket templates
 * are searched in the class path in a directory called "/rest_templates". In the usual Maven tree structure,
 * this is below src/main/resources/.//from ww w  . j  a  va  2  s. c om
 *
 * @param templateName Template to use for rendering. If the template name does not end in .ftl, .ftl is appended.
 * @param objectToRender Object to render via template
 * @return Template filled with data from objectToRender
 */
protected String renderTemplate(String templateName, Object objectToRender) {
    try {
        freemarker.template.Configuration config = new Configuration();

        // XXX fall-over to ClassTL after failure in FTL seems not to work
        // FileTemplateLoader ftl = new FileTemplateLoader(new File("src/main/resources"));
        ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), "/rest_templates/");
        TemplateLoader[] loaders = new TemplateLoader[] { ctl };
        MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);

        config.setTemplateLoader(mtl);

        if (!templateName.endsWith(".ftl"))
            templateName = templateName + ".ftl";
        Template template = config.getTemplate(templateName);

        StringWriter out = new StringWriter();
        try {
            Map<String, Object> root = new HashMap<String, Object>();
            root.put("var", objectToRender);
            template.process(root, out);
            return out.toString();
        } finally {
            out.close();
        }
    } catch (IOException ioe) {
        log.error(ioe);
    } catch (TemplateException te) {
        log.error(te.getMessage());
    }
    return null;
}

From source file:gpms.utils.PolicyTestUtil.java

/**
 * This creates the XACML request from a file
 *
 * @param rootDirectory//from  w ww  .  j  av a 2s  .c om
 *            root directory of the request files
 * @param versionDirectory
 *            version directory of the request files
 * @param requestId
 *            request file name
 * @return String or null if any error
 */
public static String createRequest(String rootDirectory, String versionDirectory, String requestId) {

    File file = new File(".");
    StringWriter writer = null;
    try {
        String filePath = file.getCanonicalPath() + File.separator + TestConstants.RESOURCE_PATH
                + File.separator + rootDirectory + File.separator + versionDirectory + File.separator
                + TestConstants.REQUEST_DIRECTORY + File.separator + requestId;

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);
        DocumentBuilder db = factory.newDocumentBuilder();
        Document doc = db.parse(new FileInputStream(filePath));
        DOMSource domSource = new DOMSource(doc);
        writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        return writer.toString();
    } catch (Exception e) {
        log.error("Error while reading expected response from file ", e);
        // ignore any exception and return null
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                log.error("Error closing stream ", e);
                // ignore any exception and return null
            }
        }
    }
    return null;
}

From source file:com.comcast.cqs.util.Util.java

public static String decompress(String compressed) throws IOException {
    if (compressed == null || compressed.equals("")) {
        return compressed;
    }// w w w . j a  va2  s  .  c om
    Reader reader = null;
    StringWriter writer = null;
    try {
        if (!compressed.startsWith("H4sIA")) {
            String prefix = compressed;
            if (compressed.length() > 100) {
                prefix = prefix.substring(0, 99);
            }
            logger.warn("event=content_does_not_appear_to_be_zipped message=" + prefix);
            return compressed;
        }
        byte[] unencodedEncrypted = Base64.decodeBase64(compressed);
        ByteArrayInputStream in = new ByteArrayInputStream(unencodedEncrypted);
        GZIPInputStream gzip = new GZIPInputStream(in);
        reader = new InputStreamReader(gzip, "UTF-8");
        writer = new StringWriter();
        char[] buffer = new char[10240];
        for (int length = 0; (length = reader.read(buffer)) > 0;) {
            writer.write(buffer, 0, length);
        }
    } finally {
        if (writer != null) {
            writer.close();
        }
        if (reader != null) {
            reader.close();
        }
    }
    String decompressed = writer.toString();
    logger.info("event=decompressed from=" + compressed.length() + " to=" + decompressed.length());
    return decompressed;
}

From source file:com.bizosys.hsearch.index.DocMeta.java

@Override
public String toString() {
    StringWriter writer = new StringWriter();
    try {//from   w w w  . j  av a2 s.co m
        toXml(writer);
        writer.close();
        return writer.toString();
        //   Closing a StringWriter has no effect.
    } catch (Exception ex) {
        IndexLog.l.fatal(ex);
        return ex.getMessage();
    }
}

From source file:de.dfki.resc28.flapjack.services.BaseService.java

@GET
@Produces({ MediaType.TEXT_HTML, Constants.CT_IMAGE_SVG_XML })
public Response getSVG() {
    IResource r = getResourceManager().get(getCanonicalURL(fRequestUrl.getRequestUri()));

    if (r == null) {
        return Response.status(Status.NOT_FOUND).build();
    }//w  w  w . j a  v  a 2 s  .  co m

    try {
        String syntax = "RDF/XML";
        StringWriter out = new StringWriter();
        r.getModel().write(out, syntax);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(
                new BasicNameValuePair("rules", "http://rhizomik.net/html/redefer/rdf2svg/showgraph.jrule"));
        urlParameters.add(new BasicNameValuePair("format", "RDF/XML"));
        urlParameters.add(new BasicNameValuePair("rdf", out.toString()));
        out.close();

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://rhizomik.net/redefer-services/render");
        httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));

        HttpResponse response = client.execute(httpPost);

        InputStream in = response.getEntity().getContent();
        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        return Response.ok(writer.toString()).type("image/svg+xml").build();
    } catch (Exception e) {
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }
}

From source file:com.redhat.jenkins.plugins.ci.integration.FedMsgMessagingPluginIntegrationTest.java

private Process logProcessBuilderIssues(ProcessBuilder pb, String commandName)
        throws InterruptedException, IOException {
    String dir = "";
    if (pb.directory() != null) {
        dir = pb.directory().getAbsolutePath();
    }/*from www  .j a v  a2 s. c  o m*/
    System.out.println("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);
        System.out.println("Issue occurred during command \"" + commandName + "\":\n" + writer.toString());
        writer.close();
    }
    return processToRun;
}