Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:io.openvidu.server.utils.CustomFileManager.java

private void writeAndCloseOnOutputStreamWriter(FileOutputStream fos, String text) throws IOException {
    OutputStreamWriter osw = null;
    try {//from   w  ww  .  j  av a 2s  . co  m
        osw = new OutputStreamWriter(fos);
        osw.write(text);
    } finally {
        osw.close();
        fos.close();
    }
}

From source file:com.sfs.jbtimporter.JBTImporter.java

/**
 * Transform the issues to the new XML format.
 *
 * @param jbt the jbt processor/*from   w  w w . j  a v  a2  s.com*/
 * @param issues the issues
 */
private static void transformIssues(final JBTProcessor jbt, final List<JBTIssue> issues) {

    final File xsltFile = new File(jbt.getXsltFileName());

    final Source xsltSource = new StreamSource(xsltFile);
    final TransformerFactory transFact = TransformerFactory.newInstance();
    Transformer trans = null;

    try {
        final Templates cachedXSLT = transFact.newTemplates(xsltSource);
        trans = cachedXSLT.newTransformer();
    } catch (TransformerConfigurationException tce) {
        System.out.println("ERROR configuring XSLT engine: " + tce.getMessage());
    }
    // Enable indenting and UTF8 encoding
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    if (trans != null) {
        for (JBTIssue issue : issues) {
            System.out.println("Processing Issue ID: " + issue.getId());
            System.out.println("Filename: " + issue.getFullFileName());

            // Read the XML file
            final File xmlFile = new File(issue.getFullFileName());
            final File tempFile = new File(issue.getFullFileName() + ".tmp");
            final File originalFile = new File(issue.getFullFileName() + ".old");

            Source xmlSource = null;
            if (originalFile.exists()) {
                // The original file exists, use that as the XML source
                xmlSource = new StreamSource(originalFile);
            } else {
                // No backup exists, use the .xml file.
                xmlSource = new StreamSource(xmlFile);
            }

            // Transform the XML file
            try {
                trans.transform(xmlSource, new StreamResult(tempFile));

                if (originalFile.exists()) {
                    // Delete the .xml file as it needs to be replaced
                    xmlFile.delete();
                } else {
                    // Rename the existing file with the .old extension
                    xmlFile.renameTo(originalFile);
                }
            } catch (TransformerException te) {
                System.out.println("ERROR transforming XML: " + te.getMessage());
            }

            // Read the xmlFile and convert the special characters

            OutputStreamWriter out = null;
            try {

                final BufferedReader in = new BufferedReader(
                        new InputStreamReader(new FileInputStream(tempFile), "UTF8"));

                out = new OutputStreamWriter(new FileOutputStream(xmlFile), "UTF-8");

                int ch = -1;
                ch = in.read();
                while (ch != -1) {
                    final char c = (char) ch;

                    if (jbt.getSpecialCharacterMap().containsKey(c)) {
                        // System.out.println("Replacing character: " + c 
                        //        + ", " + jbt.getSpecialCharacterMap().get(c));
                        out.write(jbt.getSpecialCharacterMap().get(c));
                    } else {
                        out.write(c);
                    }
                    ch = in.read();
                }
            } catch (IOException ie) {
                System.out.println("ERROR converting special characters: " + ie.getMessage());
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException ie) {
                    System.out.println("ERROR closing the XML file: " + ie.getMessage());
                }
                // Delete the temporary file
                tempFile.delete();
            }

            System.out.println("-------------------------------------");
        }
    }
}

From source file:com.packpublishing.asynchronousandroid.chapter7.SyncTask.java

private void uploadJsonToServer(HttpURLConnection urlConn, String body) throws Exception {
    OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream());
    writer.write(body);
    writer.flush();//from ww w .j a va 2s .c  o  m
    writer.close();
    int resultCode = urlConn.getResponseCode();
    if (resultCode != HttpURLConnection.HTTP_OK) {
        throw new Exception("Failed to sync with server :" + resultCode);
    }
}

From source file:general.Client.java

public void sendJSON(JSONObject jsonObject) {
    try {/*  www . j  a  va  2s.co m*/
        OutputStreamWriter out = new OutputStreamWriter(sock.getOutputStream(), StandardCharsets.UTF_8);
        out.write(jsonObject.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.pentaho.chart.plugin.openflashchart.outputs.OpenFlashChartOutput.java

public OutputStream persistChart(OutputStream outputStream, IOutput.OutputTypes fileType, int width, int height)
        throws PersistenceException {
    if (outputStream == null) {
        outputStream = new ByteArrayOutputStream();
    }/*w  ww.  ja  v  a2 s  .  c o  m*/
    try {
        outputStream.flush();
    } catch (IOException e1) {
        throw new PersistenceException(e1);
    }
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "utf-8"); //$NON-NLS-1$
        outputStreamWriter.write(chart.toString());
        outputStreamWriter.flush();
    } catch (UnsupportedEncodingException e) {
        throw new PersistenceException(e);
    } catch (OFCException e) {
        throw new PersistenceException(e);
    } catch (IOException e) {
        throw new PersistenceException(e);
    }
    return outputStream;
}

From source file:com.example.appengine.UrlFetchServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

    String id = req.getParameter("id");
    String text = req.getParameter("text");

    if (id == null || text == null || id == "" || text == "") {
        req.setAttribute("error", "invalid input");
        req.getRequestDispatcher("/main.jsp").forward(req, resp);
        return;/*from  w  w  w  . ja v a 2s .  co  m*/
    }

    JSONObject jsonObj = new JSONObject().put("userId", 33).put("id", id).put("title", text).put("body", text);

    // [START complex]
    URL url = new URL("http://jsonplaceholder.typicode.com/posts/" + id);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("PUT");

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(URLEncoder.encode(jsonObj.toString(), "UTF-8"));
    writer.close();

    int respCode = conn.getResponseCode(); // New items get NOT_FOUND on PUT
    if (respCode == HttpURLConnection.HTTP_OK || respCode == HttpURLConnection.HTTP_NOT_FOUND) {
        req.setAttribute("error", "");
        StringBuffer response = new StringBuffer();
        String line;

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        req.setAttribute("response", response.toString());
    } else {
        req.setAttribute("error", conn.getResponseCode() + " " + conn.getResponseMessage());
    }
    // [END complex]
    req.getRequestDispatcher("/main.jsp").forward(req, resp);
}

From source file:edu.isi.karma.webserver.ExtractSpatialInformationFromWikimapiaServiceHandler.java

protected void outputToOSM(String url) throws SQLException, ClientProtocolException, IOException {
    //String url = "http://api.wikimapia.org/?function=box&count=100&lon_min=-118.29244&lat_min=34.01794&lon_max=-118.28&lat_max=34.02587&key=156E90A4-57B03618-05BDBEA0-ED9C6E97-DD2116A6-A5229FEC-091E312A-2856C8BA";      
    this.url = "http://api.wikimapia.org/?function=box&count=100" + url
            + "&key=156E90A4-57B03618-05BDBEA0-ED9C6E97-DD2116A6-A5229FEC-091E312A-2856C8BA";
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(this.url);
    HttpResponse response = client.execute(get);
    HttpEntity entity = response.getEntity();
    String result = EntityUtils.toString(entity);
    FileOutputStream fout = new FileOutputStream(osmFile_path);
    OutputStream bout = new BufferedOutputStream(fout);
    OutputStreamWriter out = new OutputStreamWriter(bout, "UTF8");
    out.write(result);
    out.close();//from   w w w .  ja v a 2 s . co  m
}

From source file:net.mindengine.oculus.frontend.web.controllers.project.ProjectAjaxBrowseController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String id = request.getParameter("id");
    if (id == null || !id.startsWith("p"))
        throw new InvalidRequest();
    Long projectId = Long.parseLong(id.substring(1));

    boolean asRoot = false;
    if (request.getParameter("asRoot") != null) {
        asRoot = true;//  w ww  .  j a  v  a  2 s.  c  o m
    }
    List<Project> projects = projectDAO.getSubprojects(projectId);
    List<Test> tests = testDAO.getTestsByProjectId(projectId);

    OutputStream os = response.getOutputStream();
    response.setContentType("text/xml");
    OutputStreamWriter w = new OutputStreamWriter(os);

    w.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    w.write("<tree id=\"");
    if (projectId.equals(0L) || asRoot) {
        w.write("0");
    } else
        w.write(id);
    w.write("\">");
    for (Project project : projects) {
        w.write("<item text=\"");
        w.write(StringEscapeUtils.escapeXml(project.getName()));
        w.write("\" id=\"p");
        w.write(Long.toString(project.getId()));
        w.write("\" im0=\"tombs.gif\" im1=\"tombs_open.gif\" im2=\"tombs.gif\" ");
        if (project.getSubprojectsCount() > 0 || project.getTestsCount() > 0) {
            w.write(" child=\"1\" ");
        }
        w.write("></item>");
    }

    for (Test test : tests) {
        w.write("<item text=\"");
        w.write(StringEscapeUtils.escapeXml(test.getName()));
        w.write("\" id=\"t");
        w.write(Long.toString(test.getId()));
        w.write("\" im0=\"iconTest.png\" im1=\"iconTest.png\" im2=\"iconTest.png\" ");
        w.write("></item>");
    }
    w.write("</tree>");

    w.flush();
    w.close();
    return null;
}

From source file:com.mobilis.android.nfc.activities.MagTekFragment.java

public static void WriteSettings(Context context, String data, String file) throws IOException {
    FileOutputStream fos = null;/*from   w  w  w  .  j a v a 2 s .  co m*/
    OutputStreamWriter osw = null;
    fos = context.openFileOutput(file, Context.MODE_PRIVATE);
    osw = new OutputStreamWriter(fos);
    osw.write(data);
    osw.close();
    fos.close();
}

From source file:com.baqr.baqrcam.http.ModInternationalization.java

public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {

    final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }/*from w  ww  .j a v a  2  s  .c  o m*/

    final EntityTemplate body = new EntityTemplate(new ContentProducer() {
        public void writeTo(final OutputStream outstream) throws IOException {
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
            writer.write(mJSON);
            writer.flush();
        }
    });

    response.setStatusCode(HttpStatus.SC_OK);
    body.setContentType("text/json; charset=UTF-8");
    response.setEntity(body);

}