Example usage for java.io OutputStreamWriter OutputStreamWriter

List of usage examples for java.io OutputStreamWriter OutputStreamWriter

Introduction

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

Prototype

public OutputStreamWriter(OutputStream out) 

Source Link

Document

Creates an OutputStreamWriter that uses the default character encoding.

Usage

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

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    verifyPermissions(request);//from  w  w  w. j  a  v  a2  s  .c om

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

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

    OutputStreamWriter w = new OutputStreamWriter(os);

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

    if (rId.equals("0")) {
        w.write("<item text=\"My Tasks\" " + "id=\"mytasks\" "
                + "im0=\"tombs.gif\" im1=\"tombs_open.gif\" im2=\"tombs.gif\" child=\"1\" "
                + " nocheckbox=\"1\" >");
        w.write("</item>");
        w.write("<item text=\"Shared Tasks\" " + "id=\"shared\" "
                + "im0=\"tombs.gif\" im1=\"tombs_open.gif\" im2=\"tombs.gif\" child=\"1\" "
                + " nocheckbox=\"1\" >");
        w.write("</item>");
    } else {
        User user = getUser(request);

        Collection<TrmTask> tasks = null;
        Long projectId = null;
        String strProject = request.getParameter("projectId");
        if (strProject != null) {
            projectId = Long.parseLong(strProject);
        }

        if (rId.equals("mytasks")) {
            tasks = trmDAO.getUserTasks(user.getId(), projectId);

        } else if (rId.equals("shared")) {
            Collection<User> users = trmDAO.getUsersWithSharedTasks(user.getId(), projectId);
            for (User u : users) {
                w.write("<item text=\"" + XmlUtils.escapeXml(u.getName()) + "\" " + "id=\"u" + u.getId() + "\" "
                        + "im0=\"workflow-icon-user.png\" im1=\"workflow-icon-user.png\" im2=\"workflow-icon-user.png\" child=\"1\" "
                        + " nocheckbox=\"1\" >");
                w.write("</item>");
            }
        } else if (rId.startsWith("u")) {
            Long userId = Long.parseLong(rId.substring(1));
            tasks = trmDAO.getUserSharedTasks(userId, projectId);
        }

        if (tasks != null) {
            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=\"0\" "
                        + " >");
                w.write("</item>");
            }
        }

    }

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

From source file:com.thoughtworks.go.util.ProcessWrapper.java

ProcessWrapper(Process process, ProcessTag processTag, String command, ConsoleOutputStreamConsumer consumer,
        String encoding, String errorPrefix) {
    this.process = process;
    this.processTag = processTag;
    this.command = command;
    this.startTime = System.currentTimeMillis();
    this.processOutputStream = StreamPumper.pump(process.getInputStream(), new OutputConsumer(consumer), "",
            encoding);//w ww  .j  ava2  s .c o m
    this.processErrorStream = StreamPumper.pump(process.getErrorStream(), new ErrorConsumer(consumer),
            errorPrefix, encoding);
    this.processInputStream = new PrintWriter(new OutputStreamWriter(process.getOutputStream()));
}

From source file:jp.go.aist.six.util.core.web.spring.ReaderRequestCallback.java

public void doWithRequest(final ClientHttpRequest request) throws IOException {
    HttpHeaders headers = request.getHeaders();
    headers.setContentType(_mediaType);//from w  w  w.j  a v a2s  .c o  m

    long size = IoUtil.copy(_input, new OutputStreamWriter(request.getBody()));
    headers.setContentLength(size);
}

From source file:gr.uoc.nlp.opinion.analysis.suggestion.ElasticSearchIntegration.java

/**
 *
 * @param commentID/*  w  w w  . j a va 2s  . co  m*/
 * @param sentenceID
 * @param document
 */
public void sendToElasticSearch(String commentID, String sentenceID, String document) {

    try {
        //fix uri
        String url = elasticSearchURI + commentID + "_" + sentenceID;

        //open connection
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("PUT");

        //append data to http packet
        String data = "{\"comment\": \"" + commentID + "\"," + " \"sentence\": \"" + sentenceID + "\","
                + " \"document\": \"" + document + "\"}";

        //write data to http socket
        try (OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream())) {
            out.write(data);
            out.close();
        }

        //get response data
        String line = "";
        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {

            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

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  .j  a  va  2  s  .  co  m
        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.aylien.textapi.HttpSender.java

public String post(String url, Map<String, String> parameters, Map<String, String> headers)
        throws IOException, TextAPIException {
    try {//from  ww  w  .j ava 2s . c o m
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        for (Map.Entry<String, String> header : headers.entrySet()) {
            connection.setRequestProperty(header.getKey(), header.getValue());
        }
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", USER_AGENT);

        StringBuilder payload = new StringBuilder();
        for (Map.Entry<String, String> e : parameters.entrySet()) {
            if (payload.length() > 0) {
                payload.append('&');
            }
            payload.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=')
                    .append(URLEncoder.encode(e.getValue(), "UTF-8"));
        }

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(payload.toString());
        writer.close();

        responseHeaders = connection.getHeaderFields();

        InputStream inputStream = connection.getResponseCode() == 200 ? connection.getInputStream()
                : connection.getErrorStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        if (connection.getResponseCode() >= 300) {
            extractTextAPIError(response.toString());
        }

        return response.toString();
    } catch (MalformedURLException e) {
        throw new IOException(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);/*  w  ww  .  ja  va  2 s .  com*/

    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:Transform.java

/**
 * Asks the TransformerFactory to try to load a precompiled version of
 * the translet from the class path to construct a Transformer object.
 * The translet performs the transformation on behalf of the
 * Transformer.transform() method./*from   w w  w  . ja v a  2s . c om*/
 */
public void run(String[] args) {
    String xml = args[0];
    String transletURI = args[1];

    try {
        // Set XSLTC's TransformerFactory implementation as the default
        System.setProperty("javax.xml.transform.TransformerFactory",
                "org.apache.xalan.xsltc.trax.TransformerFactoryImpl");

        TransformerFactory tf = TransformerFactory.newInstance();
        tf.setAttribute("use-classpath", Boolean.TRUE);
        Transformer transformer = tf.newTransformer(new StreamSource(transletURI));

        StreamSource document = new StreamSource(xml);
        StreamResult result = new StreamResult(new OutputStreamWriter(System.out));
        transformer.transform(document, result);
    } catch (Exception e) {
        System.err.println("Exception: " + e);
        e.printStackTrace();
    }
    System.exit(0);
}

From source file:de.mas.telegramircbot.utils.images.ImgurUploader.java

public static String uploadImageAndGetLink(String clientID, byte[] image) throws IOException {
    URL url;//from  w  w w .j a v a  2s .  c om
    url = new URL(Settings.IMGUR_API_URL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    String dataImage = Base64.getEncoder().encodeToString(image);
    String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(dataImage, "UTF-8");

    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Client-ID " + clientID);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    conn.connect();
    StringBuilder stb = new StringBuilder();
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        stb.append(line).append("\n");
    }
    wr.close();
    rd.close();

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(ImgurResponse.class, new ImgurResponseDeserializer());
    Gson gson = gsonBuilder.create();

    // The JSON data
    try {
        ImgurResponse response = gson.fromJson(stb.toString(), ImgurResponse.class);
        return response.getLink();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return stb.toString();
}

From source file:net.daboross.bukkitdev.skywars.gist.GistReport.java

public static String gistText(Logger logger, String text) {
    URL postUrl;/*  w  ww.  j  av a2s. c om*/
    try {
        postUrl = new URL("https://api.github.com/gists");
    } catch (MalformedURLException ex) {
        logger.log(Level.FINE, "Non severe error encoding api.github.com URL", ex);
        return null;
    }
    URLConnection connection;
    try {
        connection = postUrl.openConnection();
    } catch (IOException ex) {
        logger.log(Level.FINE, "Non severe error opening api.github.com connection", ex);
        return null;
    }
    connection.setDoOutput(true);
    connection.setDoInput(true);
    JSONStringer outputJson = new JSONStringer();
    try {
        outputJson.object().key("description").value("SkyWars debug").key("public").value("false").key("files")
                .object().key("report.md").object().key("content").value(text).endObject().endObject()
                .endObject();
    } catch (JSONException ex) {
        logger.log(Level.FINE, "Non severe error while writing report", ex);
        return null;
    }
    String jsonOuptutString = outputJson.toString();
    try (OutputStream outputStream = connection.getOutputStream()) {
        try (OutputStreamWriter requestWriter = new OutputStreamWriter(outputStream)) {
            requestWriter.append(jsonOuptutString);
            requestWriter.close();
        }
    } catch (IOException ex) {
        logger.log(Level.FINE, "Non severe error writing report", ex);
        return null;
    }

    JSONObject inputJson;
    try {
        inputJson = new JSONObject(readConnection(connection));
    } catch (JSONException | IOException unused) {
        logger.log(Level.FINE, "Non severe error while reading response for report.", unused);
        return null;
    }
    String resultUrl = inputJson.optString("html_url", null);
    return resultUrl == null ? null : shortenURL(logger, resultUrl);
}