Example usage for java.io OutputStreamWriter flush

List of usage examples for java.io OutputStreamWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:cgeo.geocaching.cgBase.java

public static void postTweet(cgeoapplication app, cgSettings settings, String status, final Geopoint coords) {
    if (app == null) {
        return;/*from www  . j av a2 s.co m*/
    }
    if (settings == null || StringUtils.isBlank(settings.tokenPublic)
            || StringUtils.isBlank(settings.tokenSecret)) {
        return;
    }

    try {
        Map<String, String> parameters = new HashMap<String, String>();

        parameters.put("status", status);
        if (coords != null) {
            parameters.put("lat", String.format("%.6f", coords.getLatitude()));
            parameters.put("long", String.format("%.6f", coords.getLongitude()));
            parameters.put("display_coordinates", "true");
        }

        final String paramsDone = cgOAuth.signOAuth("api.twitter.com", "/1/statuses/update.json", "POST", false,
                parameters, settings.tokenPublic, settings.tokenSecret);

        HttpURLConnection connection = null;
        try {
            final StringBuffer buffer = new StringBuffer();
            final URL u = new URL("http://api.twitter.com/1/statuses/update.json");
            final URLConnection uc = u.openConnection();

            uc.setRequestProperty("Host", "api.twitter.com");

            connection = (HttpURLConnection) uc;
            connection.setReadTimeout(30000);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(true);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            final OutputStream out = connection.getOutputStream();
            final OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write(paramsDone);
            wr.flush();
            wr.close();

            Log.i(cgSettings.tag,
                    "Twitter.com: " + connection.getResponseCode() + " " + connection.getResponseMessage());

            InputStream ins;
            final String encoding = connection.getContentEncoding();

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }

            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            br.close();
            ins.close();
            inr.close();
            connection.disconnect();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgBase.postTweet.IO: " + connection.getResponseCode() + ": "
                    + connection.getResponseMessage() + " ~ " + e.toString());

            final InputStream ins = connection.getErrorStream();
            final StringBuffer buffer = new StringBuffer();
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            br.close();
            ins.close();
            inr.close();
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgBase.postTweet.inner: " + e.toString());
        }

        connection.disconnect();
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgBase.postTweet: " + e.toString());
    }
}

From source file:cgeo.geocaching.cgBase.java

public static String requestJSON(String scheme, String host, String path, String method, String params) {
    int httpCode = -1;
    //String httpLocation = null;

    if (method == null) {
        method = "GET";
    } else {/*from   w w  w . j  a  va 2s.c o m*/
        method = method.toUpperCase();
    }

    boolean methodPost = false;
    if (method.equalsIgnoreCase("POST")) {
        methodPost = true;
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            try {
                URL u = null;
                if (methodPost) {
                    u = new URL(scheme + host + path);
                } else {
                    u = new URL(scheme + host + path + "?" + params);
                }

                if (u.getProtocol().toLowerCase().equals("https")) {
                    trustAllHosts();
                    HttpsURLConnection https = (HttpsURLConnection) u.openConnection();
                    https.setHostnameVerifier(doNotVerify);
                    uc = https;
                } else {
                    uc = (HttpURLConnection) u.openConnection();
                }

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
                if (methodPost) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    uc.setRequestProperty("Content-Length", Integer.toString(params.length()));
                    uc.setRequestProperty("X-HTTP-Method-Override", "GET");
                } else {
                    uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                }
                uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
                connection.setDoInput(true);
                if (methodPost) {
                    connection.setDoOutput(true);

                    final OutputStream out = connection.getOutputStream();
                    final OutputStreamWriter wr = new OutputStreamWriter(out);
                    wr.write(params);
                    wr.flush();
                    wr.close();
                } else {
                    connection.setDoOutput(false);
                }

                InputStream ins = getInputstreamFromConnection(connection);
                final InputStreamReader inr = new InputStreamReader(ins);
                final BufferedReader br = new BufferedReader(inr, 1024);

                readIntoBuffer(br, buffer);

                httpCode = connection.getResponseCode();

                final String paramsLog = params.replaceAll(passMatch, "password=***");
                Log.i(cgSettings.tag + " | JSON",
                        "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path
                                + "?" + paramsLog);

                connection.disconnect();
                br.close();
                ins.close();
                inr.close();
            } catch (IOException e) {
                httpCode = connection.getResponseCode();

                Log.e(cgSettings.tag, "cgeoBase.requestJSON.IOException: " + httpCode + ": "
                        + connection.getResponseMessage() + " ~ " + e.toString());
            }
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.requestJSON: " + e.toString());
        }

        if (StringUtils.isNotBlank(buffer)) {
            break;
        }

        if (httpCode == 403) {
            // we're not allowed to download content, so let's move
            break;
        }
    }

    String page = null;
    //This is reported as beeing deadCode (httpLocation is always null)
    //2011-08-09 - 302 is redirect so something should probably be done
    /*
     * if (httpCode == 302 && httpLocation != null) {
     * final Uri newLocation = Uri.parse(httpLocation);
     * if (newLocation.isRelative()) {
     * page = requestJSONgc(host, path, params);
     * } else {
     * page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
     * }
     * } else {
     */
    replaceWhitespace(buffer);
    page = buffer.toString();
    //}

    if (page != null) {
        return page;
    } else {
        return "";
    }
}

From source file:org.apache.olingo.fit.Services.java

@GET
@Path("/{name}/{type:[a-zA-Z].*}")
public Response getEntitySet(@Context final UriInfo uriInfo,
        @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
        @PathParam("name") final String name,
        @QueryParam("$top") @DefaultValue(StringUtils.EMPTY) final String top,
        @QueryParam("$skip") @DefaultValue(StringUtils.EMPTY) final String skip,
        @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format,
        @QueryParam("$count") @DefaultValue(StringUtils.EMPTY) final String count,
        @QueryParam("$filter") @DefaultValue(StringUtils.EMPTY) final String filter,
        @QueryParam("$orderby") @DefaultValue(StringUtils.EMPTY) final String orderby,
        @QueryParam("$skiptoken") @DefaultValue(StringUtils.EMPTY) final String skiptoken,
        @PathParam("type") final String type) {

    try {//from  ww  w.  j  a v  a  2 s.c  o  m
        final Accept acceptType;
        if (StringUtils.isNotBlank(format)) {
            acceptType = Accept.valueOf(format.toUpperCase());
        } else {
            acceptType = Accept.parse(accept);
        }

        final String location = uriInfo.getRequestUri().toASCIIString();
        try {
            // search for function ...
            final InputStream func = FSManager.instance().readFile(name, acceptType);
            return xml.createResponse(location, func, null, acceptType);
        } catch (NotFoundException e) {
            if (acceptType == Accept.XML || acceptType == Accept.TEXT) {
                throw new UnsupportedMediaTypeException("Unsupported media type");
            }

            // search for entitySet ...
            final String basePath = name + File.separatorChar;

            final StringBuilder builder = new StringBuilder();
            builder.append(basePath);

            if (type != null) {
                builder.append(type).append(File.separatorChar);
            }

            if (StringUtils.isNotBlank(orderby)) {
                builder.append(Constants.get(ConstantKey.ORDERBY)).append(File.separatorChar).append(orderby)
                        .append(File.separatorChar);
            }

            if (StringUtils.isNotBlank(filter)) {
                builder.append(Constants.get(ConstantKey.FILTER)).append(File.separatorChar)
                        .append(filter.replaceAll("/", "."));
            } else if (StringUtils.isNotBlank(skiptoken)) {
                builder.append(Constants.get(ConstantKey.SKIP_TOKEN)).append(File.separatorChar)
                        .append(skiptoken);
            } else {
                builder.append(metadata.getEntitySet(name).isSingleton() ? Constants.get(ConstantKey.ENTITY)
                        : Constants.get(ConstantKey.FEED));
            }

            final InputStream feed = FSManager.instance().readFile(builder.toString(), Accept.ATOM);

            final ResWrap<EntityCollection> container = atomDeserializer.toEntitySet(feed);

            setInlineCount(container.getPayload(), count);

            final ByteArrayOutputStream content = new ByteArrayOutputStream();
            final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING);

            // -----------------------------------------------
            // Evaluate $skip and $top
            // -----------------------------------------------
            List<Entity> entries = new ArrayList<Entity>(container.getPayload().getEntities());

            if (StringUtils.isNotBlank(skip)) {
                entries = entries.subList(Integer.valueOf(skip), entries.size());
            }

            if (StringUtils.isNotBlank(top)) {
                entries = entries.subList(0, Integer.valueOf(top));
            }

            container.getPayload().getEntities().clear();
            container.getPayload().getEntities().addAll(entries);
            // -----------------------------------------------

            if (acceptType == Accept.ATOM) {
                atomSerializer.write(writer, container);
            } else {
                jsonSerializer.write(writer, container);
            }
            writer.flush();
            writer.close();

            return xml.createResponse(location, new ByteArrayInputStream(content.toByteArray()),
                    Commons.getETag(basePath), acceptType);
        }
    } catch (Exception e) {
        return xml.createFaultResponse(accept, e);
    }
}

From source file:org.apache.hadoop.hive.ql.exec.DDLTask.java

private void writeToFile(String data, String file) throws IOException {
    Path resFile = new Path(file);
    FileSystem fs = resFile.getFileSystem(conf);
    FSDataOutputStream out = fs.create(resFile);
    try {// w  ww  . ja  v a 2  s .  c om
        if (data != null && !data.isEmpty()) {
            OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
            writer.write(data);
            writer.write((char) terminator);
            writer.flush();
        }
    } finally {
        IOUtils.closeStream(out);
    }
}

From source file:FourByFour.java

public void actionPerformed(ActionEvent event) {

    Object target = event.getSource();

    // Process the button events.
    if (target == skill_return_button) {
        skill_panel.setVisible(false);/*  w  w w  .  j a v  a 2 s  .  c  o m*/
        skill_return_button.setVisible(false);
        c_container.setVisible(true);
        b_container.setVisible(true);
        newGame();
    } else if (target == winner_return_button) {
        if (winner_flag) {
            String name = winner_name.getText();
            String tmp_name = new String("");
            int tmp_score = 0;
            boolean insert_flag = false;
            winner_flag = false;
            for (int i = 0; i < 20; i++) {
                if (insert_flag) {
                    name = names[i];
                    score = scores[i];
                    names[i] = tmp_name;
                    scores[i] = tmp_score;
                    tmp_name = name;
                    tmp_score = score;
                }
                if (!insert_flag && score > scores[i]) {
                    tmp_name = names[i];
                    tmp_score = scores[i];
                    scores[i] = score;
                    names[i] = name;
                    insert_flag = true;
                }
                high_names[i].setText(names[i]);
                high_scores[i].setText(Integer.toString(scores[i]));
            }
            scoresString = new String("");
            int place;
            for (int i = 0; i < 20; i++) {
                place = (int) places[i];
                scoresString += Integer.toString(place);
                scoresString += "\t";
                scoresString += names[i];
                scoresString += "   ";
                scoresString += Integer.toString(scores[i]);
                scoresString += "\n";
            }

            if (appletFlag) {
                // Use this section of code when writing the high
                // scores file back to a server. Requires the use
                // of a deamon on the server to receive the socket
                // connection.
                //
                // Create the output stream.
                // try {
                //    Socket socket = new Socket(host, port);
                //    outStream = new BufferedOutputStream
                //       (socket.getOutputStream(), 8192);
                // }
                // catch(IOException ioe) {
                //    System.out.println("Error: " + ioe.toString());
                // }
                // System.out.println("Output stream opened");
                //
                // Write the scores to the file back on the server.
                // outText = scoresString.getBytes();
                // try {
                //    outStream.write(outText);
                //    outStream.flush();
                //    outStream.close();
                //    outStream = null;
                // }
                // catch (IOException ioe) {
                //    System.out.println("Error: " + ioe.toString());
                // }
                // System.out.println("Output stream written");

                try {
                    OutputStreamWriter outFile = new OutputStreamWriter(new FileOutputStream("scores.txt"));
                    outFile.write(scoresString);
                    outFile.flush();
                    outFile.close();
                    outFile = null;
                } catch (IOException ioe) {
                    System.out.println("Error: " + ioe.toString());
                } catch (Exception e) {
                    System.out.println("Error: " + e.toString());
                }
            } else {

                try {
                    OutputStreamWriter outFile = new OutputStreamWriter(new FileOutputStream("scores.txt"));
                    outFile.write(scoresString);
                    outFile.flush();
                    outFile.close();
                    outFile = null;
                } catch (IOException ioe) {
                    System.out.println("Error: " + ioe.toString());
                }
            }
        }
        winner_panel.setVisible(false);
        winner_return_button.setVisible(false);
        winner_label.setVisible(false);
        winner_score_label.setVisible(false);
        winner_name_label.setVisible(false);
        winner_top_label.setVisible(false);
        winner_name.setVisible(false);
        c_container.setVisible(true);
        b_container.setVisible(true);
    } else if (target == high_return_button) {
        high_return_button.setVisible(false);
        high_panel.setVisible(false);
        c_container.setVisible(true);
        b_container.setVisible(true);
    } else if (target == instruct_return_button) {
        instruct_text.setVisible(false);
        instruct_return_button.setVisible(false);
        instruct_text.repaint();
        c_container.setVisible(true);
        b_container.setVisible(true);
    } else if (target == undo_button) {
        board.undo_move();
        canvas2D.repaint();
    } else if (target == instruct_button) {
        c_container.setVisible(false);
        b_container.setVisible(false);
        instruct_text.setVisible(true);
        instruct_return_button.setVisible(true);
    } else if (target == new_button) {
        newGame();
    } else if (target == skill_button) {
        c_container.setVisible(false);
        b_container.setVisible(false);
        skill_panel.setVisible(true);
        skill_return_button.setVisible(true);
    } else if (target == high_button) {
        // Read the high scores file.
        if (appletFlag) {
            try {
                inStream = new BufferedInputStream(new URL(getCodeBase(), "scores.txt").openStream(), 8192);
                Reader read = new BufferedReader(new InputStreamReader(inStream));
                StreamTokenizer st = new StreamTokenizer(read);
                st.whitespaceChars(32, 44);
                st.eolIsSignificant(false);

                int count = 0;
                int token = st.nextToken();
                boolean scoreFlag = true;
                String string;
                while (count < 20) {
                    places[count] = (int) st.nval;
                    string = new String("");
                    token = st.nextToken();
                    while (token == StreamTokenizer.TT_WORD) {
                        string += st.sval;
                        string += " ";
                        token = st.nextToken();
                    }
                    names[count] = string;
                    scores[count] = (int) st.nval;
                    token = st.nextToken();
                    count++;
                }
                inStream.close();
            } catch (Exception ioe) {
                System.out.println("Error: " + ioe.toString());
            }
        } else {
            try {
                inStream = new BufferedInputStream(new FileInputStream("scores.txt"));
                Reader read = new BufferedReader(new InputStreamReader(inStream));
                StreamTokenizer st = new StreamTokenizer(read);
                st.whitespaceChars(32, 44);
                st.eolIsSignificant(false);

                int count = 0;
                int token = st.nextToken();
                boolean scoreFlag = true;
                String string;
                while (count < 20) {
                    places[count] = (int) st.nval;
                    string = new String("");
                    token = st.nextToken();
                    while (token == StreamTokenizer.TT_WORD) {
                        string += st.sval;
                        string += " ";
                        token = st.nextToken();
                    }
                    names[count] = string;
                    scores[count] = (int) st.nval;
                    token = st.nextToken();
                    count++;
                }
                inStream.close();
            } catch (Exception ioe) {
                System.out.println("Error: " + ioe.toString());
            }
        }
        c_container.setVisible(false);
        b_container.setVisible(false);
        high_panel.setVisible(true);
        high_return_button.setVisible(true);
    }

    Checkbox box = group.getSelectedCheckbox();
    String label = box.getLabel();
    if (label.equals("Babe in the Woods        ")) {
        board.set_skill_level(0);
    } else if (label.equals("Walk and Chew Gum        ")) {
        board.set_skill_level(1);
    } else if (label.equals("Jeopardy Contestant      ")) {
        board.set_skill_level(2);
    } else if (label.equals("Rocket Scientist         ")) {
        board.set_skill_level(3);
    } else if (label.equals("Be afraid, be very afraid")) {
        board.set_skill_level(4);
    }
}

From source file:cgeo.geocaching.cgBase.java

public String requestJSONgc(String host, String path, String params) {
    int httpCode = -1;
    String httpLocation = null;//from w w  w  .j  a v a 2  s.  c o m

    final String cookiesDone = CookieJar.getCookiesAsString(prefs);

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            // POST
            final URL u = new URL("http://" + host + path);
            uc = u.openConnection();

            uc.setRequestProperty("Host", host);
            uc.setRequestProperty("Cookie", cookiesDone);
            uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
            uc.setRequestProperty("Referer", host + "/" + path);

            if (settings.asBrowser == 1) {
                uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                uc.setRequestProperty("Accept-Language", "en-US");
                uc.setRequestProperty("User-Agent", idBrowser);
                uc.setRequestProperty("Connection", "keep-alive");
                uc.setRequestProperty("Keep-Alive", "300");
            }

            connection = (HttpURLConnection) uc;
            connection.setReadTimeout(timeout);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
            connection.setDoInput(true);
            connection.setDoOutput(true);

            final OutputStream out = connection.getOutputStream();
            final OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write(params);
            wr.flush();
            wr.close();

            CookieJar.setCookies(prefs, uc);

            InputStream ins = getInputstreamFromConnection(connection);
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            Log.i(cgSettings.tag + " | JSON",
                    "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                            + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path + "?"
                            + paramsLog);

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgeoBase.requestJSONgc.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.requestJSONgc: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }
    }

    String page = null;
    if (httpCode == 302 && httpLocation != null) {
        final Uri newLocation = Uri.parse(httpLocation);
        if (newLocation.isRelative()) {
            page = requestJSONgc(host, path, params);
        } else {
            page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
        }
    } else {
        replaceWhitespace(buffer);
        page = buffer.toString();
    }

    if (page != null) {
        return page;
    } else {
        return "";
    }
}

From source file:cgeo.geocaching.cgBase.java

public cgResponse request(boolean secure, String host, String path, String method, String params, int requestId,
        Boolean xContentType) {/*www  .  ja  va 2  s  . c  om*/
    URL u = null;
    int httpCode = -1;
    String httpMessage = null;
    String httpLocation = null;

    if (requestId == 0) {
        requestId = (int) (Math.random() * 1000);
    }

    if (method == null
            || (method.equalsIgnoreCase("GET") == false && method.equalsIgnoreCase("POST") == false)) {
        method = "POST";
    } else {
        method = method.toUpperCase();
    }

    // https
    String scheme = "http://";
    if (secure) {
        scheme = "https://";
    }

    String cookiesDone = CookieJar.getCookiesAsString(prefs);

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    StringBuffer buffer = null;

    for (int i = 0; i < 5; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer = new StringBuffer();
        timeout = 30000 + (i * 10000);

        try {
            if (method.equals("GET")) {
                // GET
                u = new URL(scheme + host + path + "?" + params);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);
            } else {
                // POST
                u = new URL(scheme + host + path);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(true);

                final OutputStream out = connection.getOutputStream();
                final OutputStreamWriter wr = new OutputStreamWriter(out);
                wr.write(params);
                wr.flush();
                wr.close();
            }

            CookieJar.setCookies(prefs, uc);

            InputStream ins = getInputstreamFromConnection(connection);
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr, 16 * 1024);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpMessage = connection.getResponseMessage();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            Log.i(cgSettings.tag + "|" + requestId,
                    "[" + method + " " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                            + (int) (buffer.length() / 1024) + "k] Downloaded " + scheme + host + path + "?"
                            + paramsLog);

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgeoBase.request.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.request: " + e.toString());
        }

        if (buffer.length() > 0) {
            break;
        }
    }

    cgResponse response = new cgResponse();

    try {
        if (httpCode == 302 && httpLocation != null) {
            final Uri newLocation = Uri.parse(httpLocation);
            if (newLocation.isRelative()) {
                response = request(secure, host, path, "GET", new HashMap<String, String>(), requestId, false,
                        false, false);
            } else {
                boolean secureRedir = false;
                if (newLocation.getScheme().equals("https")) {
                    secureRedir = true;
                }
                response = request(secureRedir, newLocation.getHost(), newLocation.getPath(), "GET",
                        new HashMap<String, String>(), requestId, false, false, false);
            }
        } else {
            if (StringUtils.isNotEmpty(buffer)) {
                replaceWhitespace(buffer);
                String data = buffer.toString();
                buffer = null;

                if (data != null) {
                    response.setData(data);
                } else {
                    response.setData("");
                }
                response.setStatusCode(httpCode);
                response.setStatusMessage(httpMessage);
                response.setUrl(u.toString());
            }
        }
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgeoBase.page: " + e.toString());
    }

    return response;
}

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int)
 */// w w  w  .  j  a va2s.  c o m
public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword,
        final int validityPeriod, final int keySize) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", subjectData);
        DEBUGGER.debug("Value: {}", validityPeriod);
        DEBUGGER.debug("Value: {}", keySize);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final String signatureAlgorithm = certConfig.getSignatureAlgorithm();
    final String certificateAlgorithm = certConfig.getCertificateAlgorithm();
    final File privateKeyDirectory = FileUtils
            .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0));
    final File publicKeyDirectory = FileUtils
            .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0));
    final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0));
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0));
    final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O="
            + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C="
            + subjectData.get(5) + ",E=" + subjectData.get(6));

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm);
        DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm);
        DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory);
        DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory);
        DEBUGGER.debug("csrDirectory: {}", csrDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("x500Name: {}", x500Name);
    }

    File csrFile = null;
    JcaPEMWriter csrPemWriter = null;
    JcaPEMWriter publicKeyWriter = null;
    JcaPEMWriter privateKeyWriter = null;
    FileOutputStream csrFileStream = null;
    FileOutputStream keyStoreStream = null;
    FileOutputStream publicKeyFileStream = null;
    FileOutputStream privateKeyFileStream = null;
    OutputStreamWriter csrFileStreamWriter = null;
    OutputStreamWriter privateKeyStreamWriter = null;
    OutputStreamWriter publicKeyStreamWriter = null;

    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, storePassword.toCharArray());

        if (DEBUG) {
            DEBUGGER.debug("KeyStore: {}", keyStore);
        }

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm);
        keyGenerator.initialize(keySize, random);

        if (DEBUG) {
            DEBUGGER.debug("KeyGenerator: {}", keyGenerator);
        }

        KeyPair keyPair = keyGenerator.generateKeyPair();

        if (DEBUG) {
            DEBUGGER.debug("KeyPair: {}", keyPair);
        }

        if (keyPair != null) {
            final Signature sig = Signature.getInstance(signatureAlgorithm);
            final PrivateKey privateKey = keyPair.getPrivate();
            final PublicKey publicKey = keyPair.getPublic();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
                DEBUGGER.debug("PrivateKey: {}", privateKey);
                DEBUGGER.debug("PublicKey: {}", publicKey);
            }

            sig.initSign(privateKey, random);
            ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey);

            if (DEBUG) {
                DEBUGGER.debug("ContentSigner: {}", signGen);
            }

            Calendar expiry = Calendar.getInstance();
            expiry.add(Calendar.DAY_OF_YEAR, validityPeriod);

            if (DEBUG) {
                DEBUGGER.debug("Calendar: {}", expiry);
            }

            CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

            if (DEBUG) {
                DEBUGGER.debug("CertificateFactory: {}", certFactory);
            }

            X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory
                    .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) };

            if (DEBUG) {
                DEBUGGER.debug("X509Certificate[]: {}", (Object) issuerCert);
            }

            keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate(
                    new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()))));
            keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(),
                    certFactory.generateCertificate(new FileInputStream(
                            FileUtils.getFile(certConfig.getIntermediateCertificateFile()))));

            PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name,
                    publicKey);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequestBuilder: {}", builder);
            }

            PKCS10CertificationRequest csr = builder.build(signGen);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequest: {}", csr);
            }

            // write private key
            File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFile: {}", privateKeyFile);
            }

            if (!(privateKeyFile.createNewFile())) {
                throw new IOException("Failed to store private file");
            }

            privateKeyFileStream = new FileOutputStream(privateKeyFile);
            privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFileStream: {}", privateKeyFileStream);
                DEBUGGER.debug("privateKeyStreamWriter: {}", privateKeyStreamWriter);
            }

            privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter);
            privateKeyWriter.writeObject(privateKey);
            privateKeyWriter.flush();
            privateKeyStreamWriter.flush();
            privateKeyFileStream.flush();

            // write public key
            File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFile: {}", publicKeyFile);
            }

            if (!(publicKeyFile.createNewFile())) {
                throw new IOException("Failed to store public key file");
            }

            publicKeyFileStream = new FileOutputStream(publicKeyFile);
            publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter);
            publicKeyWriter.writeObject(publicKey);
            publicKeyWriter.flush();
            publicKeyStreamWriter.flush();
            publicKeyFileStream.flush();

            // write csr
            csrFile = FileUtils
                    .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("csrFile: {}", csrFile);
            }

            if (!(csrFile.createNewFile())) {
                throw new IOException("Failed to store CSR file");
            }

            csrFileStream = new FileOutputStream(csrFile);
            csrFileStreamWriter = new OutputStreamWriter(csrFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            csrPemWriter = new JcaPEMWriter(csrFileStreamWriter);
            csrPemWriter.writeObject(csr);
            csrPemWriter.flush();
            csrFileStreamWriter.flush();
            csrFileStream.flush();

            File keyStoreFile = FileUtils
                    .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType());

            if (DEBUG) {
                DEBUGGER.debug("keyStoreFile: {}", keyStoreFile);
            }

            keyStoreStream = FileUtils.openOutputStream(keyStoreFile);

            if (DEBUG) {
                DEBUGGER.debug("keyStoreStream: {}", keyStoreStream);
            }

            keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(),
                    issuerCert);
            keyStore.store(keyStoreStream, storePassword.toCharArray());
            keyStoreStream.flush();

            if (DEBUG) {
                DEBUGGER.debug("KeyStore: {}", keyStore);
            }
        } else {
            throw new CertificateManagementException("Failed to generate keypair. Cannot continue.");
        }
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (InvalidKeyException ikx) {
        throw new CertificateManagementException(ikx.getMessage(), ikx);
    } catch (OperatorCreationException ocx) {
        throw new CertificateManagementException(ocx.getMessage(), ocx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } finally {
        if (csrFileStreamWriter != null) {
            IOUtils.closeQuietly(csrFileStreamWriter);
        }

        if (csrFileStream != null) {
            IOUtils.closeQuietly(csrFileStream);
        }

        if (csrPemWriter != null) {
            IOUtils.closeQuietly(csrPemWriter);
        }

        if (publicKeyFileStream != null) {
            IOUtils.closeQuietly(publicKeyFileStream);
        }

        if (publicKeyStreamWriter != null) {
            IOUtils.closeQuietly(publicKeyStreamWriter);
        }

        if (publicKeyWriter != null) {
            IOUtils.closeQuietly(publicKeyWriter);
        }

        if (privateKeyFileStream != null) {
            IOUtils.closeQuietly(privateKeyFileStream);
        }

        if (privateKeyStreamWriter != null) {
            IOUtils.closeQuietly(privateKeyStreamWriter);
        }

        if (privateKeyWriter != null) {
            IOUtils.closeQuietly(privateKeyWriter);
        }

        if (keyStoreStream != null) {
            IOUtils.closeQuietly(keyStoreStream);
        }
    }

    return csrFile;
}

From source file:org.apache.geode.internal.cache.GemFireCacheImpl.java

public void loadCacheXml(InputStream stream)
        throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException {
    // make this cache available to callbacks being initialized during xml create
    final Object oldValue = xmlCache.get();
    xmlCache.set(this);
    try {/*from   ww w  .j  av  a2s  . c  o m*/
        CacheXmlParser xml;

        if (xmlParameterizationEnabled) {
            char[] buffer = new char[1024];
            Reader reader = new BufferedReader(new InputStreamReader(stream, "ISO-8859-1"));
            Writer stringWriter = new StringWriter();

            int n = -1;
            while ((n = reader.read(buffer)) != -1) {
                stringWriter.write(buffer, 0, n);
            }

            /**
             * Now replace all replaceable system properties here using <code>PropertyResolver</code>
             */
            String replacedXmlString = resolver.processUnresolvableString(stringWriter.toString());

            /*
             * Turn the string back into the default encoding so that the XML parser can work correctly
             * in the presence of an "encoding" attribute in the XML prolog.
             */
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            OutputStreamWriter writer = new OutputStreamWriter(baos, "ISO-8859-1");
            writer.write(replacedXmlString);
            writer.flush();

            xml = CacheXmlParser.parse(new ByteArrayInputStream(baos.toByteArray()));
        } else {
            xml = CacheXmlParser.parse(stream);
        }
        xml.create(this);
    } catch (IOException e) {
        throw new CacheXmlException("Input Stream could not be read for system property substitutions.");
    } finally {
        xmlCache.set(oldValue);
    }
}

From source file:carnero.cgeo.original.libs.Base.java

public String requestJSON(String scheme, String host, String path, String method, String params) {
    int httpCode = -1;
    String httpLocation = null;/*w w w.j a  va2s .c  o  m*/

    if (method == null) {
        method = "GET";
    } else {
        method = method.toUpperCase();
    }

    boolean methodPost = false;
    if (method.equalsIgnoreCase("POST")) {
        methodPost = true;
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(Settings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            try {
                URL u = null;
                if (methodPost) {
                    u = new URL(scheme + host + path);
                } else {
                    u = new URL(scheme + host + path + "?" + params);
                }

                if (u.getProtocol().toLowerCase().equals("https")) {
                    trustAllHosts();
                    HttpsURLConnection https = (HttpsURLConnection) u.openConnection();
                    https.setHostnameVerifier(doNotVerify);
                    uc = https;
                } else {
                    uc = (HttpURLConnection) u.openConnection();
                }

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
                if (methodPost) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    uc.setRequestProperty("Content-Length", Integer.toString(params.length()));
                    uc.setRequestProperty("X-HTTP-Method-Override", "GET");
                } else {
                    uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                }
                uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
                connection.setDoInput(true);
                if (methodPost) {
                    connection.setDoOutput(true);

                    final OutputStream out = connection.getOutputStream();
                    final OutputStreamWriter wr = new OutputStreamWriter(out);
                    wr.write(params);
                    wr.flush();
                    wr.close();
                } else {
                    connection.setDoOutput(false);
                }

                final String encoding = connection.getContentEncoding();
                InputStream ins;

                if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                    ins = new GZIPInputStream(connection.getInputStream());
                } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                    ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
                } else {
                    ins = connection.getInputStream();
                }
                final InputStreamReader inr = new InputStreamReader(ins);
                final BufferedReader br = new BufferedReader(inr);

                readIntoBuffer(br, buffer);

                httpCode = connection.getResponseCode();

                final String paramsLog = params.replaceAll(passMatch, "password=***");
                Log.i(Settings.tag + " | JSON",
                        "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path
                                + "?" + paramsLog);

                connection.disconnect();
                br.close();
                ins.close();
                inr.close();
            } catch (IOException e) {
                httpCode = connection.getResponseCode();

                Log.e(Settings.tag, "cgeoBase.requestJSON.IOException: " + httpCode + ": "
                        + connection.getResponseMessage() + " ~ " + e.toString());
            }
        } catch (Exception e) {
            Log.e(Settings.tag, "cgeoBase.requestJSON: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }

        if (httpCode == 403) {
            // we're not allowed to download content, so let's move
            break;
        }
    }

    String page = null;
    if (httpCode == 302 && httpLocation != null) {
        final Uri newLocation = Uri.parse(httpLocation);
        if (newLocation.isRelative() == true) {
            page = requestJSONgc(host, path, params);
        } else {
            page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
        }
    } else {
        page = replaceWhitespace(buffer);
    }

    if (page != null) {
        return page;
    } else {
        return "";
    }
}