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.webkruscht.wmt.WebmasterTools.java

/**
 * Download search query data and write it to out
 * @param path/*from  w  w w  .j  a v  a 2 s .  c  om*/
 * @param out
 * @throws Exception
 */
public void downloadData(String path, OutputStreamWriter out) throws Exception {
    String data;
    URL url = _getUrl(path);
    GDataRequest req = svc.createRequest(RequestType.QUERY, url, ContentType.TEXT_PLAIN);
    req.execute();
    BufferedReader in = new BufferedReader(new InputStreamReader(req.getResponseStream()));
    while ((data = in.readLine()) != null) {
        out.write(data + "\n");
    }
}

From source file:fi.hip.sicx.store.HIPStoreClient.java

@Override
public boolean deleteFile(String cloudFile, StorageClientObserver sco) {

    boolean ok = false;
    HttpURLConnection conn = null;
    try {/*from  w  w  w .j  a v  a2s .  c o  m*/
        String data = URLEncoder.encode("path", "UTF-8") + "=" + URLEncoder.encode(cloudFile, "UTF-8");

        conn = getConnection("/store/erase");
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        ok = true;
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }

    closeConnection(conn);
    return ok;
}

From source file:com.cellbots.logger.localServer.LocalHttpServer.java

public void handle(final HttpServerConnection conn, final HttpContext context)
        throws HttpException, IOException {
    HttpRequest request = conn.receiveRequestHeader();
    HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK");

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

    // Get the requested target. This is the string after the domain name in
    // the URL. If the full URL was http://mydomain.com/test.html, target
    // will be /test.html.
    String target = request.getRequestLine().getUri();
    // Log.w(TAG, "*** Request target: " + target);

    // Gets the requested resource name. For example, if the full URL was
    // http://mydomain.com/test.html?x=1&y=2, resource name will be
    // test.html
    final String resName = getResourceNameFromTarget(target);
    UrlParams params = new UrlParams(target);
    // Log.w(TAG, "*** Request LINE: " +
    // request.getRequestLine().toString());
    // Log.w(TAG, "*** Request resource: " + resName);
    if (method.equals("POST") || method.equals("PUT")) {
        byte[] entityContent = null;
        // Gets the content if the request has an entity.
        if (request instanceof HttpEntityEnclosingRequest) {
            conn.receiveRequestEntity((HttpEntityEnclosingRequest) request);
            HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
            if (entity != null) {
                entityContent = EntityUtils.toByteArray(entity);
            }
        }
        response.setStatusCode(HttpStatus.SC_OK);
        if (serverListener != null) {
            serverListener.onRequest(resName, params.keys, params.values, entityContent);
        }
    } else if (dataMap.containsKey(resName)) { // The requested resource is
                                               // a byte array
        response.setStatusCode(HttpStatus.SC_OK);
        response.setHeader("Content-Type", dataMap.get(resName).contentType);
        response.setEntity(new ByteArrayEntity(dataMap.get(resName).resource));
    } else { // Return sensor readings
        String contentType = resourceMap.containsKey(resName) ? resourceMap.get(resName).contentType
                : "text/html";
        response.setStatusCode(HttpStatus.SC_OK);
        EntityTemplate body = new EntityTemplate(new ContentProducer() {
            @Override
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                writer.write(serverListener.getLoggerStatus());
                writer.flush();
            }
        });
        body.setContentType(contentType);
        response.setEntity(body);
    }
    conn.sendResponseHeader(response);
    conn.sendResponseEntity(response);
    conn.flush();
    conn.shutdown();
}

From source file:hudson.Util.java

/**
 * Escapes non-ASCII characters in URL.// w  w w  .  jav  a  2s. c om
 *
 * <p>
 * Note that this methods only escapes non-ASCII but leaves other URL-unsafe characters,
 * such as '#'.
 * {@link #rawEncode(String)} should generally be used instead, though be careful to pass only
 * a single path component to that method (it will encode /, but this method does not).
 */
public static String encode(String s) {
    try {
        boolean escaped = false;

        StringBuilder out = new StringBuilder(s.length());

        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        OutputStreamWriter w = new OutputStreamWriter(buf, "UTF-8");

        for (int i = 0; i < s.length(); i++) {
            int c = s.charAt(i);
            if (c < 128 && c != ' ') {
                out.append((char) c);
            } else {
                // 1 char -> UTF8
                w.write(c);
                w.flush();
                for (byte b : buf.toByteArray()) {
                    out.append('%');
                    out.append(toDigit((b >> 4) & 0xF));
                    out.append(toDigit(b & 0xF));
                }
                buf.reset();
                escaped = true;
            }
        }

        return escaped ? out.toString() : s;
    } catch (IOException e) {
        throw new Error(e); // impossible
    }
}

From source file:AIR.Common.Web.HttpWebHelper.java

public String getResponse(String urlString, String postRequestParams, String contentMimeType) throws Exception {
    try {//ww w.j a  v  a 2s . com
        URL url = new URL(urlString);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setRequestProperty("Content-Type",
                String.format("application/%s; charset=UTF-8", contentMimeType));
        urlConn.setUseCaches(false);

        // the request will return a response
        urlConn.setDoInput(true);

        // set request method to POST
        urlConn.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream());
        writer.write(postRequestParams);
        writer.flush();

        // reads response, store line by line in an array of Strings
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

        StringBuffer bfr = new StringBuffer();

        String line = "";
        while ((line = reader.readLine()) != null) {
            bfr.append(line + "\n");
        }

        reader.close();
        writer.close();
        urlConn.disconnect();
        return bfr.toString();

    } catch (Exception exp) {
        StringWriter strn = new StringWriter();
        exp.printStackTrace(new PrintWriter(strn));
        _logger.error(strn.toString());
        exp.printStackTrace();
        throw new Exception(exp);
    }
}

From source file:dbf.parser.pkg2.handler.java

private void sendPost(String json) throws Exception {
    System.out.println("Adding url ..");
    String url = "http://shorewindowcleaning:withwindows@ironside.ddns.net:5984/shorewindowcleaning/_bulk_docs";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    //con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept", "application/json");
    con.setRequestProperty("Content-Type", "application/json");
    String basicAuth = "Basic " + new String(new Base64().encode(obj.getUserInfo().getBytes()));
    con.setRequestProperty("Authorization", basicAuth);

    //String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
    System.out.println("Adding output ..");
    // Send post request
    con.setDoOutput(true);//www.  j a  va2  s. com
    OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
    wr.write(json);
    wr.flush();
    wr.close();
    System.out.println("geting content ..");
    // System.out.println(con.getResponseMessage());
    int responseCode = con.getResponseCode();
    System.out.println("Adding checking response ..");
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + json);
    System.out.println("Response Code : " + responseCode);
    System.out.println(con.getResponseMessage());
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());

}

From source file:fi.hip.sicx.store.HIPStoreClient.java

@Override
public boolean checkFile(String cloudFile, StorageClientObserver sco) {

    boolean ok = false;
    HttpURLConnection conn = null;
    try {/* ww w  . j a va 2  s. c  o  m*/
        String data = URLEncoder.encode("path", "UTF-8") + "=" + URLEncoder.encode(cloudFile, "UTF-8");

        conn = getConnection("/store/list");
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        String inp = readInput(conn);
        JSONObject json = new JSONObject(inp);
        if (inp.length() > 10)
            ok = true;

        JSONArray arr = json.getJSONArray("elements");
        for (int i = 0; !ok && i < arr.length(); i++) {
            JSONObject o = arr.getJSONObject(i);
            if (o.getString("path").equals(cloudFile))
                ok = true;
        }

    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }

    closeConnection(conn);
    return ok;
}

From source file:minikbextractor.SparqlProxy.java

public boolean storeData(StringBuilder query, boolean makeQuery) {
    boolean ret = true;
    if (makeQuery)
        query = SparqlProxy.makeQuery(query);
    HttpURLConnection connection = null;
    try {/*from w w  w.  j  a v a 2  s  .co m*/
        String urlParameters = "update=" + URLEncoder.encode(query.toString(), "UTF-8");
        URL url = new URL(this.urlServer + "update");
        //Create connection
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");

        connection.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

        writer.write(urlParameters);
        writer.flush();

        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String rep = "";
        while ((line = reader.readLine()) != null) {
            rep += line;
        }
        writer.close();
        reader.close();
    } catch (Exception e) {
        System.err.println("ERROR UPDATE : " + e);
        SparqlProxy.saveQueryOnFile("Query.sparql", query.toString());
        ret = false;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return ret;
}

From source file:de.akquinet.engineering.vaadinator.timesheet.service.AbstractCouchDbService.java

protected JSONObject putCouch(String urlPart, JSONObject content)
        throws IOException, MalformedURLException, JSONException {
    HttpURLConnection couchConn = null;
    BufferedReader couchRead = null;
    OutputStreamWriter couchWrite = null;
    try {/*from w w  w .  ja va  2  s .c o  m*/
        couchConn = (HttpURLConnection) (new URL(couchUrl + (couchUrl.endsWith("/") ? "" : "/") + urlPart))
                .openConnection();
        couchConn.setRequestMethod("PUT");
        couchConn.setDoInput(true);
        couchConn.setDoOutput(true);
        couchWrite = new OutputStreamWriter(couchConn.getOutputStream());
        couchWrite.write(content.toString());
        couchWrite.flush();
        couchRead = new BufferedReader(new InputStreamReader(couchConn.getInputStream()));
        StringBuffer jsonBuf = new StringBuffer();
        String line = couchRead.readLine();
        while (line != null) {
            jsonBuf.append(line);
            line = couchRead.readLine();
        }
        JSONObject couchObj = new JSONObject(jsonBuf.toString());
        return couchObj;
    } finally {
        if (couchRead != null) {
            couchRead.close();
        }
        if (couchWrite != null) {
            couchWrite.close();
        }
        if (couchConn != null) {
            couchConn.disconnect();
        }
    }
}

From source file:fi.hip.sicx.store.HIPStoreClient.java

/**
 * Gets a file stored in the cloud and saves to a local disk.
 * //w w  w .j  ava 2 s .co  m
 * @param cloudFile The file in the cloud that is to be saved.
 * @param localOutFile The saved file name.
 * @return true if file saved successfully, otherwise false
 */
@Override
public boolean getFile(String cloudFile, String localOutFile, StorageClientObserver sco) {

    boolean ok = false;
    HttpURLConnection conn = null;
    try {
        String data = URLEncoder.encode("path", "UTF-8") + "=" + URLEncoder.encode(cloudFile, "UTF-8");

        conn = getConnection("/store/fetch");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        if (conn.getResponseCode() == 200) {

            InputStream in = conn.getInputStream();

            long total = conn.getContentLength();
            long sent = 0;

            System.out.println("content len is " + total);

            FileOutputStream out = new FileOutputStream(localOutFile);
            byte[] buf = new byte[1024 * 64];
            int r = 0;
            while ((r = in.read(buf)) > -1) {
                out.write(buf, 0, r);
                sent += r;
                sco.progressMade((int) ((sent * 100) / total));
            }
            out.close();
            ok = true;
        }

    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }

    closeConnection(conn);
    return ok;
}