Example usage for java.io Writer write

List of usage examples for java.io Writer write

Introduction

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

Prototype

public void write(String str) throws IOException 

Source Link

Document

Writes a string.

Usage

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doPut(URL endpoint, String postBody, Map<String, String> headers) throws Exception {
    HttpURLConnection urlConnection = null;
    try {// w ww.  j a va2s.c  o m
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("PUT");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
        }
        urlConnection.setDoOutput(true);

        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                urlConnection.setRequestProperty(key, headers.get(key));
            }
        }
        OutputStream out = urlConnection.getOutputStream();
        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            writer.write(postBody);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while puting data", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator();
        Map<String, String> responseHeaders = new HashMap();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                responseHeaders.put(key, urlConnection.getHeaderField(key));
            }
        }
        return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders);

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doPost(URL endpoint, String postBody, Map<String, String> headers) throws Exception {
    HttpURLConnection urlConnection = null;
    try {//w  ww .j  ava 2 s  .c o  m
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("POST");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
        }
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setAllowUserInteraction(false);

        // setting headers
        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                urlConnection.setRequestProperty(key, headers.get(key));
            }
        }

        OutputStream out = urlConnection.getOutputStream();
        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            writer.write(postBody);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while posting data", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator();
        Map<String, String> responseHeaders = new HashMap();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                responseHeaders.put(key, urlConnection.getHeaderField(key));
            }
        }
        return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders);

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:edu.cmu.cs.lti.ark.fn.evaluation.PrepareFullAnnotationJson.java

private static void writeJson(Multimap<Integer, RankedScoredRoleAssignment> predictions,
        List<String> tokenizedLines, Writer output) throws IOException {
    for (int i : xrange(tokenizedLines.size())) {
        final Collection<RankedScoredRoleAssignment> predictionsForSentence = predictions.get(i);
        final List<String> tokens = Arrays.asList(tokenizedLines.get(i).split(" "));
        final SemaforParseResult semaforParseResult = getSemaforParse(predictionsForSentence, tokens);
        output.write(semaforParseResult.toJson() + "\n");
    }//from   w  w w.ja  v  a  2 s. c o m
}

From source file:com.cisco.dvbu.ps.common.scriptutil.ScriptUtil.java

/**
 * Create a command file for UNIX or Windows from name value pairs strings constructed based on passed in xml content
 * @param xmlFilePath xml File Path//  w  ww . ja v  a2  s .  co  m
 * @param nodeName String return name values for passed in node name and node value. * is treated as all nodes
 * @param nodeValue String return name values for passed in node name and node value. * is treated as all node values
 * @param options additional options to return the node name or attributes such as "-noid -noattributes"
 * @param commandOutputFile The fully qualifed path of the command output file
 * @param commandHeader The command file header such as #!/bin/bash
 * @param commandType The type of command file [UNIX|WINDOWS] {use export for UNIX, use set for WINDOWS)
 *           UNIX: export name="value"
 *        WINDOWS: set name=value
 * usage createCommandFileFromXML xmlFilePath * * "-noid -noattributes" /Users/rthummal/mywork/clients/ps/CisDeployTool/resources/abc.sh #!/bin/bash UNIX
 * usage createCommandFileFromXML xmlFilePath hostname localhost "" C:\opt\pdtool/abc.bat "echo off"    WINDOWS
 * usage createCommandFileFromXML xmlFilePath hostname * "-noid" /opt/pdtool/abc.sh #!/bin/bash UNIX
 */
public static void createCommandFileFromXML(String xmlFilePath, String nodeName, String nodeValue,
        String options, String commandOutputFile, String commandHeader, String commandType) {
    boolean win = false;
    String cmdPrefix = "export ";
    if (commandType != null && commandType.equals("WINDOWS")) {
        win = true;
        cmdPrefix = "set ";
    }

    String nameValuePairs = XMLUtils.getNameValuePairsFromXML(xmlFilePath, null, null, nodeName, nodeValue,
            options);
    if (nameValuePairs != null) {
        StringBuffer sb = new StringBuffer();
        sb.append(commandHeader + "\n");
        StringTokenizer st = new StringTokenizer(nameValuePairs, "|");
        while (st.hasMoreTokens()) {
            sb.append(cmdPrefix);

            String nameValuePair = st.nextToken();

            if (!win) {
                nameValuePair = nameValuePair.replace("=", "=\"");
                nameValuePair += "\"";
            }
            sb.append(nameValuePair + "\n");
        }

        try {
            Writer out = new OutputStreamWriter(new FileOutputStream(commandOutputFile));
            out.write(sb.toString());
            out.flush();
        } catch (FileNotFoundException e) {
            logger.error("Could not wirte to command file " + commandOutputFile, e);
            throw new ValidationException(e.getMessage(), e);

        } catch (IOException e) {
            logger.error("Could not wirte to command file " + commandOutputFile, e);
            throw new ValidationException(e.getMessage(), e);
        }

    }

}

From source file:com.sun.faban.harness.webclient.Deployer.java

private static void writeHtml(HttpServletRequest request, Writer w, List<String> errHeaders,
        List<String> errDetails) throws IOException {
    w.write("<!DOCTYPE html\n");
    w.write("    PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n");
    w.write("    \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-" + "transitional.dtd\">\n");
    w.write("<html>\n");
    w.write("    <head>\n");
    w.write("        <title>" + Config.HARNESS_NAME + " Benchmark/Service Deployment</title>\n");
    w.write("<link rel=\"icon\" type=\"image/gif\" href=\"" + request.getContextPath() + "/img/faban.gif\">");
    w.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/style.css\" />");

    w.write("    </head>\n");
    w.write("    <body>\n");
    w.write("        <table BORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"0\" WIDTH=\"100%\" >\n");
    w.write("            <tr class=\"gradient\">\n");
    w.write("                <td align=\"left\" width=\"25%\" style=\"color:white; font-size:10px\">\n");
    w.write("                &nbsp;&nbsp;<img src=\"img/faban_large.png\" height=\"50\" width=\"58\"/><br></td>\n");
    w.write("                <td align=\"center\" width=\"50%\" style=\"color:white; font-size:10px\">\n");
    w.write("                <b>Benchmark/Service Deployment</b></td>\n");
    w.write("                <td align=\"right\" valign=\"bottom\" width=25% style=\"color:white\">");
    w.write(Config.HARNESS_NAME + "&nbsp;&nbsp;" + Config.HARNESS_VERSION + "&nbsp;</td>\n");
    w.write("            </tr>\n");
    w.write("        </table>");
    w.write("        <br><center><b>");
    for (String errHdr : errHeaders) {
        w.write("            ");
        w.write(errHdr);/*from   w ww. j  av a  2s.  c o m*/
        w.write("<br>\n");
    }
    w.write("        </b></center>");
    for (String errDetail : errDetails) {
        w.write("         <table border=\"0\" cellpadding=\"4\" cellspacing=\"3\" "
                + "style=\"padding: 2px; border: 2px solid #cccccc; text-align: left; width: 100%;\">\n");
        w.write("         <tbody><tr class=\"even\"><td><pre>");
        w.write(errDetail);
        w.write("</pre></td></tr></tbody></table>\n");
    }
    w.write("    </body>\n");
    w.write("</html>\n");
}

From source file:com.sun.faban.harness.webclient.Deployer.java

private static void writeText(Writer w, List<String> errHeaders, List<String> errDetails) throws IOException {
    for (String errHeader : errHeaders) {
        w.write(errHeader);
        w.write("\n");
    }/*  www .  j  a  v a 2s .c  om*/
    w.write("\n");
    for (String errDetail : errDetails) {
        w.write(errDetail);
        w.write("\n\n");
    }
}

From source file:com.android.email.mail.transport.Rfc822Output.java

/**
 * Write text (either as main body or inside a multipart), preceded by appropriate headers.
 *
 * Note this always uses base64, even when not required.  Slightly less efficient for
 * US-ASCII text, but handles all formats even when non-ascii chars are involved.  A small
 * optimization might be to prescan the string for safety and send raw if possible.
 *
 * @param writer the output writer/*from ww w  .  j a v a2 s  .  c  o m*/
 * @param out the output stream inside the writer (used for byte[] access)
 * @param text The original text of the message
 */
private static void writeTextWithHeaders(Writer writer, OutputStream out, String text) throws IOException {
    writeHeader(writer, "Content-Type", "text/plain; charset=utf-8");
    writeHeader(writer, "Content-Transfer-Encoding", "base64");
    writer.write("\r\n");
    byte[] bytes = text.getBytes("UTF-8");
    writer.flush();
    out.write(Base64.encode(bytes, Base64.CRLF));
}

From source file:com.joliciel.talismane.utils.PerformanceMonitor.java

/**
 * Write the performance measurements to a CSV file.
 * @param csvWriter/*  ww w  . j a v  a  2s. co m*/
 */
public static void writePerformanceCSV(Writer csvWriter) {
    if (!activated)
        return;
    Set<TaskStats> taskStatSet = new TreeSet<TaskStats>(taskStatMap.values());
    try {
        csvWriter.write(CSV.format("name") + CSV.format("call count") + CSV.format("total time (s)")
                + CSV.format("%") + CSV.format("average time (ms)") + CSV.format("total time with subtasks (s)")
                + CSV.format("%") + "\n");
        for (TaskStats stats : taskStatSet) {
            csvWriter.write(CSV.format(stats.name));
            csvWriter.write(CSV.format(stats.callCount));
            csvWriter.write(CSV.format((double) stats.totalTime / 1000));
            csvWriter.write(CSV.format(((double) stats.totalTime / (double) root.totalTime) * 100.0));
            csvWriter.write(CSV.format(((double) stats.totalTime / (double) stats.callCount)));
            csvWriter.write(CSV.format((double) stats.totalTimeWithSubTasks / 1000));
            csvWriter.write(
                    CSV.format(((double) stats.totalTimeWithSubTasks / (double) root.totalTime) * 100.0));
            csvWriter.write("\n");
        }
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
    }
}

From source file:com.netxforge.oss2.core.xml.CastorUtils.java

/**
 * Marshall to a string first, then write the string to the file. This
 * way the original config isn't lost if the xml from the marshall is hosed.
 *
 * FIXME: This could still stand to write to a temporary file and/or make a
 * temporary backup of the production configuration file.
 *
 * @param config a {@link java.lang.Object} object.
 * @param cfgFile a {@link java.io.File} object.
 * @throws org.exolab.castor.xml.MarshalException if any.
 * @throws org.exolab.castor.xml.ValidationException if any.
 * @throws java.io.IOException if any./*from  ww  w  .  ja  v a2s .  c o  m*/
 */
public static void marshalViaString(Object config, File cfgFile)
        throws MarshalException, ValidationException, IOException {
    StringWriter stringWriter = new StringWriter();

    marshal(config, stringWriter);

    Writer fileWriter = new OutputStreamWriter(new FileOutputStream(cfgFile), "UTF-8");
    fileWriter.write(stringWriter.toString());
    fileWriter.flush();
    fileWriter.close();
}

From source file:com.ibm.jaggr.core.test.TestUtils.java

static public File createTestFile(File dir, String name, String content) throws IOException {
    if (!dir.exists())
        dir.mkdirs();//  w  ww . j a v a2s .  c o  m
    String filename = name;
    if (!filename.contains("."))
        filename += ".js";
    File f = new File(dir, filename);
    Writer ow = new FileWriter(f);
    ow.write(content);
    ow.close();
    return f;
}