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:com.indeed.imhotep.web.QueryMetadata.java

/**
 * Serializes this object to the stream as JSON.
 * Closes the stream after.//w  w  w .j ava  2  s  . c o  m
 */
public void toStream(OutputStream outputStream) {
    final String stringSerialization = toJSON();
    try {
        final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                new BufferedOutputStream(outputStream), Charsets.UTF_8);
        outputStreamWriter.write(stringSerialization);
        outputStreamWriter.close();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:net.mindengine.oculus.frontend.web.controllers.trm.tasks.AjaxSuiteSearchController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    verifyPermissions(request);//from w ww .  ja v a2  s. c o  m

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

    String rId = request.getParameter("id");

    OutputStreamWriter w = new OutputStreamWriter(os);

    String rootId = rId;
    if (rId.equals("mytasks0"))
        rootId = "0";

    w.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    w.write("<tree id=\"" + rootId + "\" >");

    User user = getUser(request);

    List<TrmSuite> suites = null;
    if (rId.startsWith("mytasks")) {
        Long projectId = null;
        String strProjectId = request.getParameter("projectId");
        if (strProjectId != null) {
            projectId = Long.parseLong(strProjectId);
        }

        // Displaying a list of all user tasks
        List<TrmTask> tasks = trmDAO.getUserTasks(user.getId(), projectId);
        for (TrmTask task : tasks) {
            w.write("<item text=\"" + XmlUtils.escapeXml(task.getName()) + "\" " + "id=\"t" + task.getId()
                    + "\" " + "im0=\"iconTask.png\" im1=\"iconTask.png\" im2=\"iconTask.png\" child=\"1\" "
                    + " nocheckbox=\"1\" >");
            w.write("</item>");
        }
    } else if (rId.startsWith("t")) {
        Long taskId = Long.parseLong(rId.substring(1));
        suites = trmDAO.getTaskSuites(taskId);
    }

    if (suites != null) {
        for (TrmSuite suite : suites) {
            w.write("<item ");
            w.write("text=\"" + XmlUtils.escapeXml(suite.getName()) + "\" ");
            w.write("id=\"suite" + suite.getId() + "\" ");
            w.write("im0=\"workflow-icon-suite.png\" im1=\"workflow-icon-suite.png\" im2=\"workflow-icon-suite.png\" ");

            w.write(">");
            w.write("</item>");
        }
    }

    w.write("</tree>");
    w.flush();
    os.flush();
    os.close();
    return null;
}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesRetriever.java

private static JSONArray retrieveTimeSeriesPOST(String urlString, long startEpoch, long endEpoch, String metric,
        HashMap<String, String> tags) throws OpenTSDBException {

    urlString = urlString + API_METHOD;/* w  ww. j a va 2 s.  com*/
    String result = "";

    try {
        HttpURLConnection httpConnection = TimeSeriesUtility.openHTTPConnectionPOST(urlString);
        OutputStreamWriter wr = new OutputStreamWriter(httpConnection.getOutputStream());

        JSONObject mainObject = new JSONObject();
        mainObject.put("start", startEpoch);
        mainObject.put("end", endEpoch);

        JSONArray queryArray = new JSONArray();

        JSONObject queryParams = new JSONObject();
        queryParams.put("aggregator", "sum");
        queryParams.put("metric", metric);

        queryArray.put(queryParams);

        if (tags != null) {
            JSONObject queryTags = new JSONObject();

            Iterator<Entry<String, String>> entries = tags.entrySet().iterator();
            while (entries.hasNext()) {
                @SuppressWarnings("rawtypes")
                Map.Entry entry = (Map.Entry) entries.next();
                queryTags.put((String) entry.getKey(), (String) entry.getValue());
            }

            queryParams.put("tags", queryTags);
        }

        mainObject.put("queries", queryArray);
        String queryString = mainObject.toString();

        wr.write(queryString);
        wr.flush();
        wr.close();

        result = TimeSeriesUtility.readHttpResponse(httpConnection);

    } catch (IOException e) {
        throw new OpenTSDBException("Unable to connect to server", e);
    } catch (JSONException e) {
        throw new OpenTSDBException("Error on request data", e);
    }

    return TimeSeriesUtility.makeResponseJSONArray(result);
}

From source file:de.hybris.platform.marketplaceintegration.utils.impl.MarketplaceintegrationHttpUtilImpl.java

/**
 * Post data//ww w  . j a  v a2  s.  c o  m
 *
 * @param url
 * @param data
 * @return boolean
 * @throws IOException
 */
@Override
public boolean post(final String url, final String data) throws IOException {
    httpURL = new URL(url);
    final HttpURLConnection conn = (HttpURLConnection) httpURL.openConnection();
    conn.setDoOutput(true);
    initConnection(conn);
    OutputStreamWriter writer = null;
    try {
        writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(data);
        writer.flush();
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (final IOException ex) {
                LOG.error(ex.getMessage(), ex);
            }
        }
    }
    final int status = conn.getResponseCode();
    conn.disconnect();
    return status == HttpURLConnection.HTTP_OK;
}

From source file:de.rub.syssec.saaf.analysis.steps.reporting.STReportGenerator.java

private void writeToFile(File reportFile, String result) throws IOException {
    reportFile.createNewFile();/*from  w  w  w .j a  va  2s. co m*/
    FileOutputStream os = new FileOutputStream(reportFile);
    OutputStreamWriter writer = new OutputStreamWriter(os, Charset.forName("utf-8"));
    writer.write(result);
    writer.flush();
    writer.close();
}

From source file:de.liedtke.data.url.BasicDAOUrl.java

protected JSONObject requestUrl(final String daoName, final String methodName, final String jsonValue)
        throws JSONException {
    String jsonString = null;//  w w w  .j a  v a2  s  . com
    try {
        // Construct data
        final StringBuilder params = new StringBuilder();
        params.append(URLEncoder.encode("daoName", Constants.UTF8));
        params.append("=");
        params.append(URLEncoder.encode(daoName, Constants.UTF8));
        params.append("&");
        params.append(URLEncoder.encode("methodName", Constants.UTF8));
        params.append("=");
        params.append(URLEncoder.encode(methodName, Constants.UTF8));
        if (jsonValue != null) {
            params.append("&");
            params.append(URLEncoder.encode("jsonValue", Constants.UTF8));
            params.append("=");
            params.append(URLEncoder.encode(jsonValue, Constants.UTF8));
        }
        params.append("&");
        params.append(URLEncoder.encode("kind", Constants.UTF8));
        params.append("=");
        params.append(URLEncoder.encode(ResultKind.JSON.toString(), Constants.UTF8));

        // Send data
        URL url = new URL(address);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(params.toString());
        wr.flush();

        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final StringBuilder sBuilder = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sBuilder.append(line);
        }
        jsonString = sBuilder.toString();
        wr.close();
        rd.close();
    } catch (UnsupportedEncodingException e) {
        logger.warning("UnsupportedEncodingException occured: " + e.getMessage());
    } catch (IOException e) {
        logger.warning("IOException occured: " + e.getMessage());
    }
    JSONObject json = null;
    if (jsonString == null) {
        json = null;
    } else {
        json = new JSONObject(jsonString);
    }
    return json;
}

From source file:net.mindengine.oculus.frontend.web.controllers.test.AjaxParameterSearchController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

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

    String rId = request.getParameter("id");

    OutputStreamWriter w = new OutputStreamWriter(os);

    String rootId = rId;//from  w  ww .j  a v a 2  s.com
    w.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    w.write("<tree id=\"" + rootId + "\" >");

    List<Project> projects = null;
    List<TestGroup> groups = null;
    List<Test> tests = null;
    List<TestParameter> parameters = null;
    if (rId.equals("0")) {
        // Fetching a list of projects
        projects = projectDAO.getRootProjects();
    } else if (rId.startsWith("p")) {
        Long projectId = Long.parseLong(rId.substring(1));
        projects = projectDAO.getSubprojects(projectId);

        tests = testDAO.getTestsByProjectId(projectId, 0L);
        groups = testDAO.getProjectTestGroups(projectId);
    } else if (rId.startsWith("g")) {
        // g123_456 where 123 - id of a group and 456 - id of a project
        int dash = rId.indexOf("_");
        Long groupId = Long.parseLong(rId.substring(1, dash));
        Long projectId = Long.parseLong(rId.substring(dash + 1));

        tests = testDAO.getTestsByProjectId(projectId, groupId);
    } else if (rId.startsWith("t")) {
        Long testId = Long.parseLong(rId.substring(1));
        parameters = testDAO.getTestInputParameters(testId);
        parameters.addAll(testDAO.getTestOutputParameters(testId));
    }

    if (projects != null) {
        for (Project project : projects) {
            w.write("<item text=\"" + XmlUtils.escapeXml(project.getName()) + "\" " + "id=\"p" + project.getId()
                    + "\" im0=\"tombs.gif\" im1=\"tombs_open.gif\" im2=\"tombs.gif\" child=\"1\" "
                    + " nocheckbox=\"1\" >");
            w.write("</item>");
        }
    }
    if (groups != null) {
        for (TestGroup group : groups) {
            w.write("<item ");
            w.write("text=\"" + XmlUtils.escapeXml(group.getName()) + "\" ");
            w.write("id=\"g" + group.getId() + "_" + group.getProjectId() + "\" ");
            w.write("im0=\"folderClosed.gif\" im1=\"folderOpen.gif\" im2=\"folderClosed.gif\" ");
            w.write("child=\"1\" nocheckbox=\"1\"  >");
            w.write("</item>");
        }
    }
    if (tests != null) {
        for (Test test : tests) {
            w.write("<item ");
            w.write("text=\"" + XmlUtils.escapeXml(test.getName()) + "\" ");
            w.write("id=\"t" + test.getId() + "\" ");
            w.write("im0=\"iconTest.png\" im1=\"iconTest.png\" im2=\"iconTest.png\" ");
            w.write("child=\"1\" nocheckbox=\"1\"  >");
            w.write("</item>");
        }
    }
    if (parameters != null) {
        for (TestParameter parameter : parameters) {
            w.write("<item ");
            w.write("text=\"" + XmlUtils.escapeXml(parameter.getName()) + "\" ");
            w.write("id=\"tp" + parameter.getId() + "\" ");

            if (parameter.getType().equals(TestParameter.TYPE_INPUT)) {
                w.write("im0=\"iconParameterInput.png\" im1=\"iconParameterInput.png\" im2=\"iconParameterInput.png\" ");
            } else
                w.write("im0=\"iconParameterOutput.png\" im1=\"iconParameterOutput.png\" im2=\"iconParameterOutput.png\" ");
            w.write(" >");
            w.write("</item>");
        }
    }

    w.write("</tree>");
    w.flush();
    os.flush();
    os.close();
    return null;
}

From source file:com.adaptris.core.services.Utf8BomRemoverTest.java

private AdaptrisMessage create(boolean includeBom) throws Exception {
    AdaptrisMessage msg = new DefaultMessageFactory().newMessage();
    OutputStream out = msg.getOutputStream();
    OutputStreamWriter writer = null;
    try {//from  w w w.  jav  a 2 s  .com
        if (includeBom) {
            out.write(UTF_8_BOM);
            out.flush();
        }
        writer = new OutputStreamWriter(out);
        writer.write(PAYLOAD);
        writer.flush();
    } finally {
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(out);
    }

    return msg;
}

From source file:com.alternatecomputing.jschnizzle.renderer.WebSequenceRenderer.java

public BufferedImage render(Diagram diagram) {
    String script = diagram.getScript();
    if (script == null) {
        throw new RendererException("no script defined.");
    }//  w ww . j ava2 s  . c  o  m

    String style = diagram.getStyle().getValue();
    String baseURL = getBaseURL();

    try {
        // build parameter string
        String data = "style=" + style + "&format=svg&message=" + URLEncoder.encode(script, "UTF-8");

        // send the request
        URL url = new URL(baseURL);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        // write parameters
        writer.write(data);
        writer.flush();

        // get the response
        StringBuffer answer = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            answer.append(line);
        }
        writer.close();
        reader.close();

        JSONObject json = JSONObject.fromString(answer.toString());

        HttpClient client = new HttpClient();
        String proxyHost = System.getProperty("http.proxyHost");
        String proxyPort = System.getProperty("http.proxyPort");
        if (StringUtils.isNotBlank(proxyHost) && StringUtils.isNotBlank(proxyPort)) {
            client.getHostConfiguration().setProxy(proxyHost, Integer.parseInt(proxyPort));
        }
        String getURI = baseURL + json.getString("img");
        GetMethod getMethod = new GetMethod(getURI);
        client.executeMethod(getMethod);
        String svgContents = getMethod.getResponseBodyAsString();
        getMethod.releaseConnection();
        LOGGER.debug(svgContents);

        diagram.setEncodedImage(svgContents);
        TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(svgContents.getBytes()));
        BufferedImageTranscoder imageTranscoder = new BufferedImageTranscoder();
        imageTranscoder.transcode(input, null);

        // log any errors to the UI console
        JSONArray errors = json.getJSONArray("errors");
        for (int eIdx = 0; eIdx < errors.length(); ++eIdx) {
            LOGGER.error("JSON error: " + errors.getString(eIdx));
        }
        return imageTranscoder.getBufferedImage();

    } catch (MalformedURLException e) {
        throw new RendererException(e);
    } catch (IOException e) {
        throw new RendererException(e);
    } catch (TranscoderException e) {
        throw new RendererException(e);
    }
}

From source file:com.commonsware.android.tte.DocumentStorageService.java

private void save(Uri document, String text, boolean isClosing) {
    boolean isContent = ContentResolver.SCHEME_CONTENT.equals(document.getScheme());

    try {/*from   w ww .j  ava2s . com*/
        OutputStream os = getContentResolver().openOutputStream(document, "w");
        OutputStreamWriter osw = new OutputStreamWriter(os);

        try {
            osw.write(text);
            osw.flush();

            if (isClosing && isContent) {
                int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;

                getContentResolver().releasePersistableUriPermission(document, perms);
            }

            EventBus.getDefault().post(new DocumentSavedEvent(document));
        } finally {
            osw.close();
        }
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Exception saving " + document.toString(), e);
        EventBus.getDefault().post(new DocumentSaveErrorEvent(document, e));
    }
}