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:com.webcohesion.enunciate.modules.java_json_client.JavaJSONClientModule.java

/**
 * Processes the specified template with the given model.
 *
 * @param templateURL The template URL./*from   w w w. j ava  2 s.com*/
 * @param model       The root model.
 */
public String processTemplate(URL templateURL, Object model) throws IOException, TemplateException {
    debug("Processing template %s.", templateURL);
    Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);

    configuration.setTemplateLoader(new URLTemplateLoader() {
        protected URL getURL(String name) {
            try {
                return new URL(name);
            } catch (MalformedURLException e) {
                return null;
            }
        }
    });

    configuration.setTemplateExceptionHandler(new TemplateExceptionHandler() {
        public void handleTemplateException(TemplateException templateException, Environment environment,
                Writer writer) throws TemplateException {
            throw templateException;
        }
    });

    configuration.setLocalizedLookup(false);
    configuration.setDefaultEncoding("UTF-8");
    configuration.setObjectWrapper(new JavaJSONClientObjectWrapper());
    Template template = configuration.getTemplate(templateURL.toString());
    StringWriter unhandledOutput = new StringWriter();
    template.process(model, unhandledOutput);
    unhandledOutput.close();
    return unhandledOutput.toString();
}

From source file:com.flexive.faces.messages.FxFacesMessage.java

/**
 * Gets the stacktrace as a string from a throwable.
 *
 * @param th the throwable/*from w w  w.  j  a  v  a  2  s.  c  om*/
 * @return the stacktrace as string
 */
private String getStackTrace(Throwable th) {
    StringWriter sw = null;
    PrintWriter pw = null;
    try {
        sw = new StringWriter();
        pw = new PrintWriter(sw);
        th.printStackTrace(pw);
        return sw.toString();
    } catch (Throwable t) {
        return "n/a";
    } finally {
        try {
            if (sw != null)
                sw.close();
        } catch (Throwable t) {
            /*ignore*/}
        try {
            if (pw != null)
                pw.close();
        } catch (Throwable t) {
            /*ignore*/}
    }
}

From source file:org.eclipse.packagedrone.utils.deb.build.DebianPackageWriter.java

protected ContentProvider createChecksumContent() throws IOException {
    if (this.checkSums.isEmpty()) {
        return ContentProvider.NULL_CONTENT;
    }/*from   ww w  .  j  a  v a 2  s  . c om*/

    final StringWriter sw = new StringWriter();

    for (final Map.Entry<String, String> entry : this.checkSums.entrySet()) {
        final String filename = entry.getKey().substring(2); // without the leading dot and slash

        sw.append(entry.getValue());
        sw.append("  ");
        sw.append(filename);
        sw.append('\n');
    }

    sw.close();

    return new StaticContentProvider(sw.toString());
}

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

public void evaluate(Template template, Map<String, Object> context, Writer writer) {
    try {/*from   www .j av a2  s .c  om*/
        context.put("currentDate", new java.util.Date());
        StringWriter out = new StringWriter();
        Reader reader = new BufferedReader(new StringReader(template.getContent()));
        freemarker.template.Template t = new freemarker.template.Template(template.getDataFile(), reader,
                configuration);
        long startTime = System.currentTimeMillis();
        t.process(context, out);
        long endTime = System.currentTimeMillis();
        long renderTime = (endTime - startTime);

        logger.debug("Rendered [" + template.getTemplateId() + "] in " + renderTime + " milliseconds");
        out.flush();
        out.close();
        String text = out.toString();
        writer.write(text);
    } catch (Exception ex) {
        logger.debug("error template:" + template.getDataFile());
        throw new RuntimeException(ex);
    }
}

From source file:com.cts.ptms.tracking.UPSTracking.java

@Override
public CustomTrackingResponse getTrackingDetails(CustomTrackingRequest customTrackingRequest)
        throws TrackingException {

    CustomTrackingResponse customTrackingResponse = null;
    try {/*from ww  w  .j  a va  2s  . co m*/
        com.cts.ptms.model.gls.AccessRequest accessRequest = null;
        com.cts.ptms.model.ups.generated.trackrequest.TrackRequest trackRequest = null;
        com.cts.ptms.model.ups.generated.trackresponse.TrackResponse trackResponse = null;

        //Create JAXBContext and marshaller for AccessRequest object                 
        JAXBContext accessRequestJAXBC = JAXBContext.newInstance(AccessRequest.class.getPackage().getName());
        Marshaller accessRequestMarshaller = accessRequestJAXBC.createMarshaller();
        com.cts.ptms.model.gls.ObjectFactory accessRequestObjectFactory = new com.cts.ptms.model.gls.ObjectFactory();
        accessRequest = accessRequestObjectFactory.createAccessRequest();

        AccessRequest receivedAccessReq = customTrackingRequest.getAccessRequest();

        //Populate the access request
        accessRequest.setAccessLicenseNumber(receivedAccessReq.getAccessLicenseNumber());
        accessRequest.setUserId(receivedAccessReq.getUserId());
        accessRequest.setPassword(receivedAccessReq.getPassword());

        TrackRequestDetails inputRequestDtls = customTrackingRequest.getTrackRequestDetails();
        if (inputRequestDtls == null || inputRequestDtls.getTrackingNumber() == null) {
            throw new TrackingException("No Tracking Tracking number found in the request.");
        }

        //Create JAXBContext and marshaller for TrackRequest object
        JAXBContext trackRequestJAXBC = JAXBContext.newInstance(
                com.cts.ptms.model.ups.generated.trackrequest.TrackRequest.class.getPackage().getName());
        Marshaller trackRequestMarshaller = trackRequestJAXBC.createMarshaller();
        com.cts.ptms.model.ups.generated.trackrequest.ObjectFactory requestObjectFactory = new com.cts.ptms.model.ups.generated.trackrequest.ObjectFactory();

        trackRequest = requestObjectFactory.createTrackRequest();
        //Populate the Track request
        com.cts.ptms.model.ups.generated.trackrequest.Request request = new com.cts.ptms.model.ups.generated.trackrequest.Request();
        com.cts.ptms.model.ups.generated.trackrequest.TransactionReference transReference = new com.cts.ptms.model.ups.generated.trackrequest.TransactionReference();
        transReference.setCustomerContext("Tracking customer shipment Details");
        request.setTransactionReference(transReference);
        request.setRequestAction("Track");
        request.getRequestOption().addAll(inputRequestDtls.getRequestOptions());
        trackRequest.setRequest(request);
        trackRequest.setTrackingNumber(inputRequestDtls.getTrackingNumber());

        //Get String out of access request and track request objects.
        StringWriter strWriter = new StringWriter();
        accessRequestMarshaller.marshal(accessRequest, strWriter);
        trackRequestMarshaller.marshal(trackRequest, strWriter);
        strWriter.flush();
        strWriter.close();

        System.out.println("Request: " + strWriter.getBuffer().toString());

        if (properties == null) {
            throw new TrackingException("Error while loading the ups properties.");
        }
        URLConnection httpUrlConnection = ShipmentCommonUtilities.contactService(
                strWriter.getBuffer().toString(), new URL(properties.getProperty("INTEGRATION_URL")));
        String strResults = null;
        if (httpUrlConnection != null) {
            strResults = ShipmentCommonUtilities.readURLConnection(httpUrlConnection);
        } else
            throw new TrackingException("Exception occured while contacting the service..");

        //Parse response object
        JAXBContext trackResponseJAXBC = JAXBContext.newInstance(TrackResponse.class.getPackage().getName());
        Unmarshaller trackUnmarshaller = trackResponseJAXBC.createUnmarshaller();
        ByteArrayInputStream input = new ByteArrayInputStream(strResults.getBytes());
        Object objResponse = trackUnmarshaller.unmarshal(input);
        trackResponse = (com.cts.ptms.model.ups.generated.trackresponse.TrackResponse) objResponse;

        List<TrackingError> trackingErrors = null;
        if (trackResponse.getResponse() != null) {

            String responseCode = trackResponse.getResponse().getResponseStatusCode();
            customTrackingResponse = populateResponse(trackResponse);
            if (responseCode != null && responseCode.equals("1")) {

                System.out.println("Response Status: " + trackResponse.getResponse().getResponseStatusCode());
                System.out.println("Response Status Description: "
                        + trackResponse.getResponse().getResponseStatusDescription());
            } else if (responseCode != null && responseCode.equals("0")) {
                trackingErrors = new ArrayList<TrackingError>(0);
                List<com.cts.ptms.model.ups.generated.trackresponse.Error> resErrors = trackResponse
                        .getResponse().getError();
                if (resErrors != null && !resErrors.isEmpty()) {
                    for (com.cts.ptms.model.ups.generated.trackresponse.Error resError : resErrors) {
                        TrackingError trackingError = new TrackingError();
                        trackingError.setErrorSeverity(resError.getErrorSeverity());
                        trackingError.setErrorCode(resError.getErrorCode());
                        trackingError.setErrorDescription(resError.getErrorDescription());
                        trackingErrors.add(trackingError);
                    }
                }
                customTrackingResponse.setError(trackingErrors);
            }
        }

    } catch (TrackingException e) {
        System.out.println("Exception occurred at : " + e.getMessage());
    } catch (Exception e) {
        System.out.println("Exception occurred at : " + e.getMessage());
        throw new TrackingException(e.getMessage());
    }
    return customTrackingResponse;
}

From source file:com.webcohesion.enunciate.modules.objc_client.ObjCXMLClientModule.java

/**
 * Processes the specified template with the given model.
 *
 * @param templateURL The template URL./*from   w w  w  . j  a  v  a  2s .  c  o m*/
 * @param model       The root model.
 */
public String processTemplate(URL templateURL, Object model) throws IOException, TemplateException {
    debug("Processing template %s.", templateURL);
    Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);

    configuration.setTemplateLoader(new URLTemplateLoader() {
        protected URL getURL(String name) {
            try {
                return new URL(name);
            } catch (MalformedURLException e) {
                return null;
            }
        }
    });

    configuration.setTemplateExceptionHandler(new TemplateExceptionHandler() {
        public void handleTemplateException(TemplateException templateException, Environment environment,
                Writer writer) throws TemplateException {
            throw templateException;
        }
    });

    configuration.setLocalizedLookup(false);
    configuration.setDefaultEncoding("UTF-8");
    configuration.setObjectWrapper(new ObjCXMLClientObjectWrapper());
    Template template = configuration.getTemplate(templateURL.toString());
    StringWriter unhandledOutput = new StringWriter();
    template.process(model, unhandledOutput);
    unhandledOutput.close();
    return unhandledOutput.toString();
}

From source file:nl.b3p.viewer.stripes.ArcQueryUtilActionBean.java

@DefaultHandler
public Resolution arcXML() throws JSONException {
    JSONObject json = new JSONObject();

    try {/*  w w  w  . java2  s  . c om*/
        AxlSpatialQuery aq = new AxlSpatialQuery();
        FilterToArcXMLSQL visitor = new FilterToArcXMLSQL(aq);

        Filter filter = CQL.toFilter(cql);
        String where = visitor.encodeToString(filter);

        if (whereOnly) {
            json.put("where", where);
        } else {
            if (where.trim().length() > 0 && !where.trim().equals("1=1")) {
                aq.setWhere(where);
            }

            StringWriter sw = new StringWriter();

            Marshaller m = ArcXML.getJaxbContext().createMarshaller();
            m.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8");
            m.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.setProperty(javax.xml.bind.Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
            m.marshal(new JAXBElement(new QName(null, "SPATIALQUERY"), AxlSpatialQuery.class, aq), sw);
            sw.close();

            json.put("SPATIALQUERY", sw.toString());
        }
        json.put("success", true);
    } catch (Exception e) {
        json.put("success", false);

        String message = "Fout bij maken spatial query: " + e.toString();
        Throwable cause = e.getCause();
        while (cause != null) {
            message += "; " + cause.toString();
            cause = cause.getCause();
        }
        json.put("error", message);
    }

    return new StreamingResolution("application/json", new StringReader(json.toString(4)));
}

From source file:org.wso2.am.admin.clients.mediation.SynapseConfigAdminClient.java

/**
 * Get the String value form Document object
 *
 * @param doc - Document object the need to  retrieve the string value
 * @return String -  String value of the Document object provided.
 * @throws TransformerException for the newTransformer()  and transform() method calls in Transformer
 */// ww w.ja  va  2 s  .c om
private String getStringFromDocument(Document doc) throws TransformerException {
    StringWriter writer = null;
    try {
        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();
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                log.warn("Exception when closing the StringWriter.", e);
            }
        }
    }
}

From source file:org.guanxi.sp.engine.service.saml2.WebBrowserSSOAuthConsumerService.java

/**
 * This is the handler for the initial /s2/wbsso/acs page. This receives the
 * browser after it has visited the IdP.
 *
 * @param request ServletRequest//www .  ja va2 s  .c  o m
 * @param response ServletResponse
 * @throws java.io.IOException if an error occurs
 * @throws org.guanxi.common.GuanxiException if an error occurs
 * @throws java.security.KeyStoreException if an error occurs
 * @throws java.security.NoSuchAlgorithmException if an error occurs
 * @throws java.security.cert.CertificateException if an error occurs
 */
public void acs(HttpServletRequest request, HttpServletResponse response)
        throws IOException, GuanxiException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
    String guardSession = request.getParameter("RelayState");
    String b64SAMLResponse = request.getParameter("SAMLResponse");

    if ((getServletContext().getAttribute(guardSession.replaceAll("GUARD", "ENGINE")) == null)) {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("Metadata error<br /><br />");
        out.println("Not a valid session");
        out.flush();
        out.close();
        return;
    }

    // We previously changed the Guard session ID to an Engine one...
    EntityDescriptorType guardEntityDescriptor = (EntityDescriptorType) getServletContext()
            .getAttribute(guardSession.replaceAll("GUARD", "ENGINE"));
    // ...so now change it back as it will be passed to the Guard
    guardSession = guardSession.replaceAll("ENGINE", "GUARD");

    try {
        // Decode and unmarshall the response from the IdP
        ResponseDocument responseDocument = null;
        if (request.getMethod().equalsIgnoreCase("post")) {
            responseDocument = ResponseDocument.Factory
                    .parse(new StringReader(Utils.decodeBase64(b64SAMLResponse)));
        } else {
            byte[] decodedRequest = Utils.decodeBase64b(b64SAMLResponse);
            responseDocument = ResponseDocument.Factory
                    .parse(Utils.inflate(decodedRequest, Utils.RFC1951_NO_WRAP));
        }
        String idpProviderId = responseDocument.getResponse().getIssuer().getStringValue();

        HashMap<String, String> namespaces = new HashMap<String, String>();
        namespaces.put(SAML.NS_SAML_20_PROTOCOL, SAML.NS_PREFIX_SAML_20_PROTOCOL);
        namespaces.put(SAML.NS_SAML_20_ASSERTION, SAML.NS_PREFIX_SAML_20_ASSERTION);
        XmlOptions xmlOptions = new XmlOptions();
        xmlOptions.setSavePrettyPrint();
        xmlOptions.setSavePrettyPrintIndent(2);
        xmlOptions.setUseDefaultNamespace();
        xmlOptions.setSaveAggressiveNamespaces();
        xmlOptions.setSaveSuggestedPrefixes(namespaces);
        xmlOptions.setSaveNamespacesFirst();

        if (logResponse) {
            logger.info("=======================================================");
            logger.info("IdP response from providerId " + idpProviderId);
            logger.info("");
            StringWriter sw = new StringWriter();
            responseDocument.save(sw, xmlOptions);
            logger.info(sw.toString());
            sw.close();
            logger.info("");
            logger.info("=======================================================");
        }

        // Do the trust
        if (responseDocument.getResponse().getSignature() != null) {
            if (!TrustUtils.verifySignature(responseDocument)) {
                throw new GuanxiException("Trust failed");
            }
            EntityFarm farm = (EntityFarm) getServletContext()
                    .getAttribute(Guanxi.CONTEXT_ATTR_ENGINE_ENTITY_FARM);
            EntityManager manager = farm.getEntityManagerForID(idpProviderId);
            X509Certificate x509 = TrustUtils.getX509CertFromSignature(responseDocument);
            if (x509 != null) {
                Metadata idpMetadata = manager.getMetadata(idpProviderId);
                if (!manager.getTrustEngine().trustEntity(idpMetadata, x509)) {
                    throw new GuanxiException("Trust failed");
                }
            } else {
                throw new GuanxiException("No X509 from signature");
            }
        }

        /* Load up the Guard's private key. We need this to decrypt the secret key
         * which was used to encrypt the attributes.
         */
        KeyStore guardKeystore = KeyStore.getInstance("JKS");
        GuardRoleDescriptorExtensions guardNativeMetadata = Util.getGuardNativeMetadata(guardEntityDescriptor);
        FileInputStream fis = new FileInputStream(guardNativeMetadata.getKeystore());
        guardKeystore.load(fis, guardNativeMetadata.getKeystorePassword().toCharArray());
        fis.close();
        PrivateKey guardPrivateKey = (PrivateKey) guardKeystore.getKey(guardEntityDescriptor.getEntityID(),
                guardNativeMetadata.getKeystorePassword().toCharArray());

        // Decrypt the response if required
        if (isEncrypted(responseDocument)) {
            try {
                responseDocument = decryptResponse(responseDocument, xmlOptions, guardPrivateKey);
            } catch (GuanxiException ge) {
                response.setContentType("text/html");
                PrintWriter out = response.getWriter();
                out.println("Decryption error<br /><br />");
                out.println(ge.getMessage());
                out.flush();
                out.close();
                return;
            }
        }

        Config config = (Config) getServletContext().getAttribute(Guanxi.CONTEXT_ATTR_ENGINE_CONFIG);
        processGuardConnection(guardNativeMetadata.getAttributeConsumerServiceURL(),
                guardEntityDescriptor.getEntityID(), guardNativeMetadata.getKeystore(),
                guardNativeMetadata.getKeystorePassword(), config.getTrustStore(),
                config.getTrustStorePassword(), responseDocument, guardSession);

        /* Stop replay attacks.
         * If another message comes in with the same RelayState we won't be able
         * to find the Guard metadata it refers to as we've deleted it.
         */
        getServletContext().removeAttribute(guardSession.replaceAll("GUARD", "ENGINE"));

        response.sendRedirect(guardNativeMetadata.getPodderURL() + "?id=" + guardSession);
    } catch (XmlException xe) {
        logger.error(xe);
    } catch (Exception e) {
        logger.error(e);
    }
}

From source file:org.rapla.rest.gwtjsonrpc.server.JsonServlet.java

private String formatResult(final ActiveCall call) throws UnsupportedEncodingException, IOException {
    final GsonBuilder gb = createGsonBuilder();

    gb.registerTypeAdapter(call.getClass(), new JsonSerializer<ActiveCall>() {
        @Override/*from  ww  w .java  2 s. c om*/
        public JsonElement serialize(final ActiveCall src, final Type typeOfSrc,
                final JsonSerializationContext context) {
            if (call.externalFailure != null) {
                final String msg;
                if (call.method != null) {
                    msg = "Error  in " + call.method.getName();
                } else {
                    msg = "Error";
                }
                logger.error(msg, call.externalFailure);
            }

            Throwable failure = src.externalFailure != null ? src.externalFailure : src.internalFailure;
            Object result = src.result;
            if (result instanceof FutureResult) {
                try {
                    result = ((FutureResult) result).get();
                } catch (Exception e) {
                    failure = e;
                }
            }

            final JsonObject r = new JsonObject();
            if (src.versionName == null || src.versionValue == null) {
                r.add("jsonrpc", new JsonPrimitive("2.0"));
            } else {
                r.add(src.versionName, src.versionValue);
            }
            if (src.id != null) {
                r.add("id", src.id);
            }
            if (failure != null) {
                final int code = to2_0ErrorCode(src);
                final JsonObject error = getError(src.versionName, code, failure, gb);
                r.add("error", error);
            } else {
                r.add("result", context.serialize(result));
            }
            return r;
        }

    });
    Gson create = gb.create();
    final StringWriter o = new StringWriter();

    create.toJson(call, o);
    o.close();
    String string = o.toString();
    return string;
}