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:es.tid.cep.esperanza.Utils.java

public static boolean DoHTTPPost(String urlStr, String content) {
    try {//from   w w  w.  j  a v  a  2 s  .com
        URL url = new URL(urlStr);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        OutputStreamWriter printout = new OutputStreamWriter(urlConn.getOutputStream(),
                Charset.forName("UTF-8"));
        printout.write(content);
        printout.flush();
        printout.close();

        int code = urlConn.getResponseCode();
        String message = urlConn.getResponseMessage();
        logger.debug("action http response " + code + " " + message);
        if (code / 100 == 2) {
            InputStream input = urlConn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            for (String line; (line = reader.readLine()) != null;) {
                logger.debug("action response body: " + line);
            }
            input.close();
            return true;

        } else {
            logger.error("action response is not OK: " + code + " " + message);
            InputStream error = urlConn.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(error));
            for (String line; (line = reader.readLine()) != null;) {
                logger.error("action error response body: " + line);
            }
            error.close();
            return false;
        }
    } catch (MalformedURLException me) {
        logger.error("exception MalformedURLException: " + me.getMessage());
        return false;
    } catch (IOException ioe) {
        logger.error("exception IOException: " + ioe.getMessage());
        return false;
    }
}

From source file:com.mingsoft.weixin.http.HttpClientConnectionManager.java

/**
 * ?/*  www .  ja  v  a 2 s  .co  m*/
 * @param postUrl ?
 * @param param ?
 * @param method 
 * @return null
 */
public static String request(String postUrl, String param, String method) {
    URL url;
    try {
        url = new URL(postUrl);

        HttpURLConnection conn;
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(30000); // ??)
        conn.setReadTimeout(30000); // ????)
        conn.setDoOutput(true); // post??http?truefalse
        conn.setDoInput(true); // ?httpUrlConnectiontrue
        conn.setUseCaches(false); // Post ?
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestMethod(method);// "POST"GET
        conn.setRequestProperty("Content-Length", param.length() + "");
        String encode = "utf-8";
        OutputStreamWriter out = null;
        out = new OutputStreamWriter(conn.getOutputStream(), encode);
        out.write(param);
        out.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return null;
        }
        // ??
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line = "";
        StringBuffer strBuf = new StringBuffer();
        while ((line = in.readLine()) != null) {
            strBuf.append(line).append("\n");
        }
        in.close();
        out.close();
        return strBuf.toString();
    } catch (MalformedURLException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Create a new dataset// www  . ja va 2s  . c  o m
 * 
 * @param dataSetName
 * @throws IOException
 * @throws HttpException
 */
public static void createDataSet(@NonNull String dataSetName) throws IOException, HttpException {
    logger.info("create dataset: " + dataSetName);

    URL url = new URL(HOST + "/$/datasets");
    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // set content
    httpConnection.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
    out.write("dbName=" + URLEncoder.encode(dataSetName, "UTF-8") + "&dbType=mem");
    out.close();

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_OK:
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }
}

From source file:Main.java

public static int doShellCommand(String cmd, StringBuilder log, boolean runAsRoot, boolean waitFor)
        throws Exception {

    Process proc = null;//from w  w w. ja v a 2s  . c  om
    int exitCode = -1;

    if (runAsRoot)
        proc = Runtime.getRuntime().exec("su");
    else
        proc = Runtime.getRuntime().exec("sh");

    OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream());

    //   TorService.logMessage("executing shell cmd: " + cmds[i] + "; runAsRoot=" + runAsRoot + ";waitFor=" + waitFor);

    out.write(cmd);
    out.write("\n");

    out.flush();
    out.write("exit\n");
    out.flush();

    if (waitFor) {

        final char buf[] = new char[10];

        // Consume the "stdout"
        InputStreamReader reader = new InputStreamReader(proc.getInputStream());
        int read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        // Consume the "stderr"
        reader = new InputStreamReader(proc.getErrorStream());
        read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        exitCode = proc.waitFor();

    }

    return exitCode;

}

From source file:Main.java

private static void saveStr(String path, String xml, boolean isAppend) {
    OutputStream out = null;/* w w w  .  j  a  va2s . com*/
    OutputStreamWriter outwriter = null;
    try {
        File file = new File(path);
        if (!file.exists()) {
            file.createNewFile();
        }
        out = new FileOutputStream(path, isAppend);
        outwriter = new OutputStreamWriter(out, "UTF-8");
        outwriter.write(xml);
        outwriter.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (outwriter != null) {
                outwriter.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Upload ontology content on specified dataset. Graph used is the default
 * one except if specified// w  ww. j  a v a2  s  .  c o  m
 * 
 * @param ontology
 * @param datasetName
 * @param graphName
 * @throws IOException
 * @throws HttpException
 */
public static void uploadOntology(InputStream ontology, String datasetName, @Nullable String graphName)
        throws IOException, HttpException {
    graphName = Strings.emptyToNull(graphName);

    logger.info("upload ontology in dataset: " + datasetName + " graph:" + Strings.nullToEmpty(graphName));

    boolean createGraph = (graphName != null) ? true : false;
    String dataSetEncoded = URLEncoder.encode(datasetName, "UTF-8");
    String graphEncoded = createGraph ? URLEncoder.encode(graphName, "UTF-8") : null;

    URL url = new URL(HOST + '/' + dataSetEncoded + "/data" + (createGraph ? "?graph=" + graphEncoded : ""));

    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

    String boundary = "------------------" + System.currentTimeMillis()
            + Long.toString(Math.round(Math.random() * 1000));

    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    httpConnection.setRequestProperty("Connection", "keep-alive");
    httpConnection.setRequestProperty("Cache-Control", "no-cache");

    // set content
    httpConnection.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
    out.write(BOUNDARY_DECORATOR + boundary + EOL);
    out.write("Content-Disposition: form-data; name=\"files[]\"; filename=\"ontology.owl\"" + EOL);
    out.write("Content-Type: application/octet-stream" + EOL + EOL);
    out.write(CharStreams.toString(new InputStreamReader(ontology)));
    out.write(EOL + BOUNDARY_DECORATOR + boundary + BOUNDARY_DECORATOR + EOL);
    out.close();

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_CREATED:
        checkState(createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    case HttpURLConnection.HTTP_OK:
        checkState(!createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }

}

From source file:Main.java

public static int doShellCommand(String[] cmds, StringBuilder log, boolean runAsRoot, boolean waitFor)
        throws Exception {

    Process proc = null;//from   w w w . j av a  2  s .  c o  m
    int exitCode = -1;

    if (runAsRoot) {
        proc = Runtime.getRuntime().exec("su");
    } else {
        proc = Runtime.getRuntime().exec("sh");
    }

    OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream());

    for (int i = 0; i < cmds.length; i++) {
        // TorService.logMessage("executing shell cmd: " + cmds[i] +
        // "; runAsRoot=" + runAsRoot + ";waitFor=" + waitFor);

        out.write(cmds[i]);
        out.write("\n");
    }

    out.flush();
    out.write("exit\n");
    out.flush();

    if (waitFor) {

        final char buf[] = new char[10];

        // Consume the "stdout"
        InputStreamReader reader = new InputStreamReader(proc.getInputStream());
        int read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null) {
                log.append(buf, 0, read);
            }
        }

        // Consume the "stderr"
        reader = new InputStreamReader(proc.getErrorStream());
        read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null) {
                log.append(buf, 0, read);
            }
        }

        exitCode = proc.waitFor();

    }

    return exitCode;

}

From source file:com.shvet.poi.util.HexDump.java

/**
 * dump an array of bytes to an OutputStream
 *
 * @param data   the byte array to be dumped
 * @param offset its offset, whatever that might mean
 * @param stream the OutputStream to which the data is to be
 *               written//w ww .  j ava 2s .c o  m
 * @param index  initial index into the byte array
 * @param length number of characters to output
 * @throws IOException                    is thrown if anything goes wrong writing
 *                                        the data to stream
 * @throws ArrayIndexOutOfBoundsException if the index is
 *                                        outside the data array's bounds
 * @throws IllegalArgumentException       if the output stream is
 *                                        null
 */
public static void dump(final byte[] data, final long offset, final OutputStream stream, final int index,
        final int length) throws IOException, ArrayIndexOutOfBoundsException, IllegalArgumentException {
    if (stream == null) {
        throw new IllegalArgumentException("cannot write to nullstream");
    }

    OutputStreamWriter osw = new OutputStreamWriter(stream, UTF8);
    osw.write(dump(data, offset, index, length));
    osw.flush();
}

From source file:com.denimgroup.threadfix.importer.cli.CommandLineMigration.java

private static void convert(String inputScript, String outputScript) {
    File file = new File(inputScript);

    LOGGER.info("Converting threadfix script to mySql script " + outputScript + " ...");

    File outputFile = new File(outputScript);

    FileOutputStream fos = null;// w  w w. j  a  v a  2s  .c  om
    try {
        fos = new FileOutputStream(outputFile);

        OutputStreamWriter osw = new OutputStreamWriter(fos);

        List<String> lines = FileUtils.readLines(file);

        osw.write("SET FOREIGN_KEY_CHECKS=0;\n");

        String table;
        for (String line : lines) {
            if (line != null && line.toUpperCase().startsWith("CREATE MEMORY TABLE ")) {
                table = RegexUtils.getRegexResult(line, TABLE_PATTERN);
                System.out.println("Create new table:" + table);
                String[] tableName = table.split("\\(", 2);
                if (tableName.length == 2) {
                    List<String> fieldList = list();
                    String[] fields = tableName[1].trim().replace("(", "").replace(")", "").split(",");
                    for (int i = 0; i < fields.length; i++) {
                        if (!"CONSTRAINT".equalsIgnoreCase(fields[i].trim().split(" ")[0])) {
                            String field = fields[i].trim().split(" ")[0].replace("\"", "");
                            if (!fieldList.contains(field))
                                fieldList.add(field);
                        }
                    }
                    String fieldsStr = org.apache.commons.lang3.StringUtils.join(fieldList, ",");
                    tableMap.put(tableName[0].toUpperCase(), "(" + fieldsStr + ")");
                }
            } else if (line != null && line.toUpperCase().startsWith("INSERT INTO ")) {
                table = RegexUtils.getRegexResult(line, INSERT_PATTERN).toUpperCase();
                if (tableMap.get(table) != null) {
                    line = line.replaceFirst(" " + table + " ", " " + table + tableMap.get(table) + " ");
                    if (line.contains(ACUNETIX_ESCAPE)) {
                        line = line.replace(ACUNETIX_ESCAPE, ACUNETIX_ESCAPE_REPLACE);
                    }
                    line = escapeString(line) + ";\n";

                    osw.write(line);
                }
            }
        }
        osw.write("SET FOREIGN_KEY_CHECKS=1;\n");
        osw.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.akquinet.android.androlog.reporter.PostReporter.java

/**
 * Executes the given request as a HTTP POST action.
 *
 * @param url//from   www  .ja  va  2  s .c o  m
 *            the url
 * @param params
 *            the parameter
 * @return the response as a String.
 * @throws IOException
 *             if the server cannot be reached
 */
public static void post(URL url, String params) throws IOException {
    URLConnection conn = url.openConnection();
    if (conn instanceof HttpURLConnection) {
        ((HttpURLConnection) conn).setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
    }
    OutputStreamWriter writer = null;
    try {
        conn.setDoOutput(true);
        writer = new OutputStreamWriter(conn.getOutputStream(), Charset.forName("UTF-8"));
        // write parameters
        writer.write(params);
        writer.flush();
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}