Example usage for java.io OutputStreamWriter close

List of usage examples for java.io OutputStreamWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:pl.maciejwalkowiak.plist.spring.PlistHttpMessageConverter.java

@Override
protected void writeInternal(Object o, HttpOutputMessage httpOutputMessage)
        throws IOException, HttpMessageNotWritableException {

    Charset charset = getCharset(httpOutputMessage.getHeaders());
    OutputStreamWriter writer = new OutputStreamWriter(httpOutputMessage.getBody(), charset);

    String result = addHeader ? plistSerializer.toXmlPlist(o) : plistSerializer.serialize(o);

    writer.write(result);/*from  ww w  . j a va  2s.  com*/
    writer.close();
}

From source file:org.talend.components.webtest.JsonIo2HttpMessageConverter.java

/**
 * Serializes specified Object and writes JSON to HTTP message body 
 * //  w  w  w  .  j av  a 2 s .  c om
 * @param t Object to serialize
 * @param outputMessage the HTTP output message to write to
 */
@Override
protected void writeInternal(Object t, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputMessage.getBody());
    String objectToJson = JsonWriter.objectToJson(t);
    outputStreamWriter.write(objectToJson);
    outputStreamWriter.flush();
    outputStreamWriter.close();
}

From source file:com.twinsoft.convertigo.engine.print.PrintHTML.java

@Override
public String print(String location) throws IOException, EngineException, SAXException,
        TransformerFactoryConfigurationError, TransformerException, ParserConfigurationException {
    super.print(location);
    out.close();//from ww  w .j a v  a 2s . c  om

    updateStatus("Create Ressources Directory", 70);

    //get the dom
    Document fopResult = XMLUtils.parseDOM(outputFile);
    Element root = fopResult.getDocumentElement();
    String templateFileName = Engine.TEMPLATES_PATH + "/doc/doc.html.xsl";
    File htmlFile = new File(templateFileName);
    Source xsltSrc = new StreamSource(new FileInputStream(htmlFile), localizedDir);

    //create the ressources repository               
    String ressourcesFolder = outputFolder + "/ressources";
    File repository = new File(ressourcesFolder);
    if (!repository.exists()) {
        repository.mkdir();
    }

    //export images
    NodeList images = fopResult.getElementsByTagName("image");
    Node image;
    String attrImg, attrImgName;
    InputStream imagesIn;
    OutputStream imagesOut;
    for (int i = 0; i < images.getLength(); i++) {
        image = images.item(i);
        attrImg = image.getAttributes().getNamedItem("url").getTextContent();
        attrImgName = attrImg.replaceAll("(.*)/", "");
        image.getAttributes().getNamedItem("url").setTextContent(attrImgName);
        imagesIn = new FileInputStream(attrImg);
        imagesOut = new FileOutputStream(ressourcesFolder + "/" + attrImgName);
        org.apache.commons.io.IOUtils.copy(imagesIn, imagesOut);
        imagesIn.close();
        imagesOut.close();
    }

    //export css
    FileInputStream cssIn = new FileInputStream(Engine.TEMPLATES_PATH + "/doc/style.css");
    FileOutputStream cssOut = new FileOutputStream(ressourcesFolder + "/style.css");
    org.apache.commons.io.IOUtils.copy(cssIn, cssOut);
    cssIn.close();
    cssOut.close();

    updateStatus("HTML Transformation", 85);

    // transformation of the dom
    Transformer xslt = TransformerFactory.newInstance().newTransformer(xsltSrc);
    Element xsl = fopResult.createElement("xsl");
    xslt.transform(new DOMSource(fopResult), new DOMResult(xsl));
    fopResult.removeChild(root);
    fopResult.appendChild(xsl.getFirstChild());

    //write the dom
    String newOutputFileName = outputFolder + "/" + projectName + ".html";
    outputFile = new File(newOutputFileName);
    out = new FileOutputStream(outputFile);
    out = new java.io.BufferedOutputStream(out);
    OutputStreamWriter output = new OutputStreamWriter(out);
    output.write(XMLUtils.prettyPrintDOM(fopResult));
    output.close();

    //remove the temp file
    new File(outputFileName).delete();

    updateStatus("Printing finished", 100);

    return newOutputFileName;
}

From source file:ch.sdi.SocialDataImporterRunner.java

/**
 * Runs the SocialDataImporter application.
 * <p>/*w  w  w  .  j  a  v a2 s .c o m*/
 * @param args
 * @throws SdiException
 */
public void run(String[] args) throws SdiException {
    initialize(args);

    try {
        PersonKey.initCustomKeys(myEnv);

        mySdiReporter.reset();

        Collection<? extends Person<?>> inputPersons = myCollectorExecutor.execute();

        if (myLog.isDebugEnabled()) {
            myLog.debug("collected persons: " + inputPersons);
        } // if myLog.isDebugEnabled()

        myTargetExecutor.execute(inputPersons);

    } finally {
        String report = mySdiReporter.getReport();
        myLog.debug("Generated report:\n" + report);
        File outputDir = myEnv.getProperty(ConfigUtils.KEY_PROP_OUTPUT_DIR, File.class);
        if (outputDir != null) {
            File reportFile = new File(outputDir, "SdiReport.txt");
            try {
                OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(reportFile), "UTF-8");
                osw.write(report);
                osw.close();
            } catch (IOException t) {
                myLog.warn("Unable to write report file: " + reportFile.getPath(), t);
            }
        } // if outputDir != null

    }

}

From source file:com.twilio.sdk.TwilioRestClient.java

@Override
public TwilioRestResponse request(String path, String method, Map<String, String> vars)
        throws TwilioRestException {

    String encoded = "";
    if (vars != null && !vars.isEmpty()) {
        for (String key : vars.keySet()) {
            try {
                encoded += "&" + key + "=" + URLEncoder.encode(vars.get(key), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new TwilioRestException(e);
            }/*from  w w w. j  a  va  2s. c  o  m*/
        }
        encoded = encoded.substring(1);
    }

    // construct full url
    String url = this.endpoint + path;

    // if GET and vars, append them
    if (method.toUpperCase().equals("GET"))
        url += ((path.indexOf('?') == -1) ? "?" : "&") + encoded;

    try {
        HttpURLConnection con = openConnection(url);
        String userpass = this.accountSid + ":" + this.authToken;
        String encodeuserpass = new String(Base64.encodeBase64(userpass.getBytes()));

        con.setRequestProperty("Authorization", "Basic " + encodeuserpass);

        con.setDoOutput(true);

        // initialize a new curl object            
        if (method.toUpperCase().equals("GET")) {
            con.setRequestMethod("GET");
        } else if (method.toUpperCase().equals("POST")) {
            con.setRequestMethod("POST");
            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
            out.write(encoded);
            out.close();
        } else if (method.toUpperCase().equals("PUT")) {
            con.setRequestMethod("PUT");
            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
            out.write(encoded);
            out.close();
        } else if (method.toUpperCase().equals("DELETE")) {
            con.setRequestMethod("DELETE");
        } else {
            throw new TwilioRestException("Unknown method " + method);
        }

        BufferedReader in = null;
        try {
            if (con.getInputStream() != null) {
                in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            }
        } catch (IOException e) {
            if (con.getErrorStream() != null) {
                in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            }
        }

        if (in == null) {
            throw new TwilioRestException("Unable to read response from server");
        }

        StringBuilder decodedString = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            decodedString.append(line);
        }
        in.close();

        // get result code
        int responseCode = con.getResponseCode();

        return new TwilioRestResponse(url, decodedString.toString(), responseCode);
    } catch (MalformedURLException e) {
        throw new TwilioRestException(e);
    } catch (IOException e) {
        throw new TwilioRestException(e);
    }
}

From source file:com.google.wave.api.oauth.impl.OpenSocialHttpClient.java

/**
 * Executes a request and writes all data in the request's body to the
 * output stream.//  w  w  w.j a  va2  s  .com
 *
 * @param method
 * @param url
 * @param body
 * @return Response message
 */
private OpenSocialHttpResponseMessage send(String method, OpenSocialUrl url, String contentType, String body)
        throws IOException {
    HttpURLConnection connection = null;
    try {
        connection = getConnection(method, url, contentType);
        if (body != null) {
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
            out.write(body);
            out.flush();
            out.close();
        }

        return new OpenSocialHttpResponseMessage(method, url, connection.getInputStream(),
                connection.getResponseCode());
    } catch (IOException e) {
        throw new IOException(
                "Container returned status " + connection.getResponseCode() + " \"" + e.getMessage() + "\"");
    }
}

From source file:com.stratio.explorer.interpreter.InterpreterFactory.java

private void saveToFile(String file, String path) throws IOException {
    File settingFile = new File(path);
    if (!settingFile.exists()) {
        settingFile.createNewFile();/*  w w w . ja v a 2s.  c o m*/
    }
    FileOutputStream fos = new FileOutputStream(settingFile, false);
    OutputStreamWriter out = new OutputStreamWriter(fos);
    out.append(file);
    out.close();
    fos.close();
}

From source file:JLabelDragSource.java

public Object getTransferData(DataFlavor fl) {
    if (!isDataFlavorSupported(fl)) {
        return null;
    }// www  .j av a  2s. c  om

    if (fl.equals(DataFlavor.stringFlavor)) {
        // String - return the text as a String
        return label.getText() + " (DataFlavor.stringFlavor)";
    } else if (fl.equals(jLabelFlavor)) {
        // The JLabel itself - just return the label.
        return label;
    } else {
        // Plain text - return an InputStream
        try {
            String targetText = label.getText() + " (plain text flavor)";
            int length = targetText.length();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            OutputStreamWriter w = new OutputStreamWriter(os);
            w.write(targetText, 0, length);
            w.flush();
            byte[] bytes = os.toByteArray();
            w.close();
            return new ByteArrayInputStream(bytes);
        } catch (IOException e) {
            return null;
        }
    }
}

From source file:com.thoughtworks.acceptance.EncodingTestSuite.java

private void test(final HierarchicalStreamDriver driver, final String encoding) throws IOException {
    final String headerLine = encoding != null ? "<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>\n" : "";
    final String xmlData = headerLine // force code format
            + "<test>\n" + "  <data>J\u00f6rg</data>\n" + "</test>";

    final XStream xstream = new XStream(driver);
    xstream.allowTypes(TestObject.class);
    xstream.alias("test", TestObject.class);
    final TestObject obj = new TestObject();
    obj.data = "J\u00f6rg";

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final OutputStreamWriter writer = encoding != null ? new OutputStreamWriter(bos, encoding)
            : new OutputStreamWriter(bos);
    xstream.toXML(obj, writer);//from  ww  w  .  ja  v a  2s . co m
    writer.close();

    final String generated = encoding != null ? bos.toString(encoding) : bos.toString();
    Assert.assertTrue("'" + obj.data + "' was not found", generated.indexOf(obj.data) > 0);

    final Object restored = xstream.fromXML(
            new ByteArrayInputStream(encoding != null ? xmlData.getBytes(encoding) : xmlData.getBytes()));
    Assert.assertEquals(obj, restored);
}

From source file:edu.mayo.cts2.framework.webapp.rest.converter.MappingGsonHttpMessageConverter.java

@Override
protected void writeInternal(Object t, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {
    String json = this.jsonConverter.toJson(t);

    OutputStreamWriter writer = null;
    try {//from   w  ww .  j  av a  2 s .  c  o m
        writer = new OutputStreamWriter(outputMessage.getBody());

        writer.write(json);

        writer.flush();
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}