Example usage for java.io OutputStreamWriter close

List of usage examples for java.io OutputStreamWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:com.example.user.rideshareapp1.MyGcmListenerService.java

/**
 * Called when message is received./*  ww w .  ja  va  2  s.  com*/
 *
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs.
 *             For Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {

    //TODO find a way to find if it is chat and store it in the file, create a notification
    if (android.os.Debug.isDebuggerConnected())
        android.os.Debug.waitForDebugger();

    String message = data.getString("message");

    String id;

    if (data.containsKey("topic")) {

        id = data.getString("ride");

        try (FileOutputStream fOut = openFileOutput("chat_" + id + ".txt", MODE_WORLD_READABLE | MODE_APPEND)) {

            OutputStreamWriter osw = new OutputStreamWriter(fOut);

            osw.write(data.getString("name") + ":" + data.getString("message") + "`");
            osw.flush();
            osw.close();

        } catch (IOException e) {
            Toast.makeText(this, "Failed to open chat file from notification", Toast.LENGTH_LONG).show();
        }

    } else {

        sendNotification(
                data.getString("title") + "`" + data.getString("name") + "`" + data.getString("message"));
    }

    Log.i(TAG, "From: " + from);
    Log.i(TAG, "Message: " + message);

    // [START_EXCLUDE]
    /**
     * Production applications would usually process the message here.
     * Eg: - Syncing with server.
     *     - Store message in local database.
     *     - Update UI.
     */

    /**
     * In some cases it may be useful to show a notification indicating to the user
     * that a message was received.
     */

    // [END_EXCLUDE]
}

From source file:com.juick.android.Utils.java

public static RESTResponse postJSON(final Context context, final String url, final String data,
        final String contentType) {
    final URLAuth authorizer = getAuthorizer(url);
    final RESTResponse[] ret = new RESTResponse[] { null };
    final boolean[] cookieCleared = new boolean[] { false };
    authorizer.authorize(context, false, false, url, new Function<Void, String>() {
        @Override//from  ww w  .  j a  v  a  2 s .  c om
        public Void apply(String myCookie) {
            final boolean noAuthRequested = myCookie != null && myCookie.equals(URLAuth.REFUSED_AUTH);
            if (noAuthRequested)
                myCookie = null;
            HttpURLConnection conn = null;
            try {
                String nurl = authorizer.authorizeURL(url, myCookie);
                URL jsonURL = new URL(nurl);
                conn = (HttpURLConnection) jsonURL.openConnection();
                if (contentType != null) {
                    conn.addRequestProperty("Content-Type", contentType);
                }
                authorizer.authorizeRequest(context, conn, myCookie, nurl);

                conn.setUseCaches(false);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");

                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.close();

                URLAuth.ReplyCode authReplyCode = authorizer.validateNon200Reply(conn, url, false);
                try {
                    if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && noAuthRequested) {
                        ret[0] = new RESTResponse(NO_AUTH, false, null);
                    } else if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && !cookieCleared[0]) {
                        cookieCleared[0] = true; // don't enter loop
                        final Function<Void, String> thiz = this;
                        authorizer.clearCookie(context, new Runnable() {
                            @Override
                            public void run() {
                                authorizer.authorize(context, true, false, url, thiz);
                            }
                        });
                    } else {
                        if (conn.getResponseCode() == 200 || authReplyCode == URLAuth.ReplyCode.NORMAL) {
                            InputStream inputStream = conn.getInputStream();
                            ret[0] = streamToString(inputStream, null);
                            inputStream.close();
                        } else {
                            ret[0] = new RESTResponse(
                                    "HTTP " + conn.getResponseCode() + " " + conn.getResponseMessage(), false,
                                    null);
                        }
                    }
                } finally {
                    conn.disconnect();
                }
            } catch (Exception e) {
                Log.e("getJSON", e.toString());
                ret[0] = new RESTResponse(ServerToClient.NETWORK_CONNECT_ERROR + e.toString(), true, null);
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
            return null; //To change body of implemented methods use File | Settings | File Templates.
        }
    });
    while (ret[0] == null) { // bad, but true
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    }
    return ret[0];
}

From source file:crossbear.convergence.ConvergenceConnector.java

/**
 * Contact a ConvergenceNotary and ask it for all information about certificate observations it has made on a specific host.
 * //w  w  w . j a va 2 s.  co  m
 * Please note: Contacting a ConvergenceNotary is possible with and without sending the fingerprint of the observed certificate. In both cases the Notary will send a list of
 * ConvergenceCertificateObservations. The problem is that if no fingerprint is sent or the fingerprint matches the last certificate that the Notary observed for the host, the Notary will just
 * read the list of ConvergenceCertificateObservations from its database. It will not contact the server to see if it the certificate is still the one it uses. The problem with that is that with
 * this algorithm Convergence usually makes only one certificate observation per server. When asked for that server a Notary will therefore reply "I saw that certificate last July". Since
 * Crossbear requires statements like "I saw this certificate since last July" it will send a fake-fingerprint to the Convergence Notaries. This compels the Notary to query the server for
 * its current certificate. After that the Notary will update its database and will then send the updated list of ConvergenceCertificateObservations to Crossbear.
 * 
 * @param notary
 *            The notary to contact
 * @param hostPort
 *            The Hostname and port of the server on which the information about the certificate observations is desired.
 * @return The Response-String that the Notary sent as an answer. It will contain a JSON-encoded list of ConvergenceCertificateObservations
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
private static String contactNotary(ConvergenceNotary notary, String hostPort)
        throws IOException, KeyManagementException, NoSuchAlgorithmException {

    // Construct a fake fingerprint to send to the Notary (currently the Hex-String representation of "ConvergenceIsGreat:)")
    String data = "fingerprint=43:6F:6E:76:65:72:67:65:6E:63:65:49:73:47:72:65:61:74:3A:29";

    // Build the url to connect to based on the Notary and the certificate's host
    URL url = new URL("https://" + notary.getHostPort() + "/target/" + hostPort.replace(":", "+"));

    // Open a HttpsURLConnection for that url
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    /*
     * Set a TrustManager on that connection that forces the use of the Notary's certificate. If the Notary sends any certificate that differs from the one that it is supposed to have (according
     * to the ConvergenceNotaries-table) an Exception will be thrown. This protects against Man-in-the-middle attacks placed between the Crossbear server and the Notary.
     */
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null,
            new TrustManager[] {
                    new TrustSingleCertificateTM(Message.hexStringToByteArray(notary.getCertSHA256Hash())) },
            new java.security.SecureRandom());
    conn.setSSLSocketFactory(sc.getSocketFactory());

    // Set the timeout during which the Notary has to reply
    conn.setConnectTimeout(3000);

    // POST the fake fingerprint to the Notary
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the Notary's response. Since Convergence replies with a 409-error if it has never observed a certificate conn.getInputStream() will be null. The way to get the Notarys reply in that case is to use conn.getErrorStream().
    InputStream is;
    if (conn.getResponseCode() >= 400) {
        is = conn.getErrorStream();

    } else {
        // This line should never be executed since we send a fake fingerprint that should never belong to an actually observed certificate. But who knows ...
        is = conn.getInputStream();
    }

    // Read the Notary's reply and store it
    String response = Message.inputStreamToString(is);

    // Close all opened streams
    wr.close();

    // Return the Notary's reply
    return response;

}

From source file:com.indeed.imhotep.web.QueryMetadata.java

/**
 * Serializes this object to the stream as JSON.
 * Closes the stream after./* w w  w . ja  v  a2  s . co  m*/
 */
public void toStream(OutputStream outputStream) {
    final String stringSerialization = toJSON();
    try {
        final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                new BufferedOutputStream(outputStream), Charsets.UTF_8);
        outputStreamWriter.write(stringSerialization);
        outputStreamWriter.close();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:it.avalz.opendaylight.controller.Controller.java

public void addFlow(Flow f) {
    Vertex v = f.getNode();//w w w .  j av  a2s  . c o m

    String authString = this.username + ":" + this.password;

    try {
        StringBuilder urlString = new StringBuilder();

        urlString.append(this.baseUrl).append("/flowprogrammer/default/node/OF/").append(v.getId())
                .append("/staticFlow/").append(f.getName());
        URL url = new URL(urlString.toString());
        byte[] authEncoded = Base64.encodeBase64(authString.getBytes());
        String authEncodedString = new String(authEncoded);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");

        connection.setRequestProperty("Authorization", "Basic " + authEncodedString);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");

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

        out.write(f.toString());
        out.close();

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

    System.out.println("Flow installed on vertex " + v);
    System.out.println(f);
}

From source file:de.rub.syssec.saaf.analysis.steps.reporting.STReportGenerator.java

private void writeToFile(File reportFile, String result) throws IOException {
    reportFile.createNewFile();/*w ww. j a  v  a  2s  . c  om*/
    FileOutputStream os = new FileOutputStream(reportFile);
    OutputStreamWriter writer = new OutputStreamWriter(os, Charset.forName("utf-8"));
    writer.write(result);
    writer.flush();
    writer.close();
}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesRetriever.java

private static JSONArray retrieveTimeSeriesPOST(String urlString, long startEpoch, long endEpoch, String metric,
        HashMap<String, String> tags) throws OpenTSDBException {

    urlString = urlString + API_METHOD;/*w  w  w .  j  av a 2 s .  c o m*/
    String result = "";

    try {
        HttpURLConnection httpConnection = TimeSeriesUtility.openHTTPConnectionPOST(urlString);
        OutputStreamWriter wr = new OutputStreamWriter(httpConnection.getOutputStream());

        JSONObject mainObject = new JSONObject();
        mainObject.put("start", startEpoch);
        mainObject.put("end", endEpoch);

        JSONArray queryArray = new JSONArray();

        JSONObject queryParams = new JSONObject();
        queryParams.put("aggregator", "sum");
        queryParams.put("metric", metric);

        queryArray.put(queryParams);

        if (tags != null) {
            JSONObject queryTags = new JSONObject();

            Iterator<Entry<String, String>> entries = tags.entrySet().iterator();
            while (entries.hasNext()) {
                @SuppressWarnings("rawtypes")
                Map.Entry entry = (Map.Entry) entries.next();
                queryTags.put((String) entry.getKey(), (String) entry.getValue());
            }

            queryParams.put("tags", queryTags);
        }

        mainObject.put("queries", queryArray);
        String queryString = mainObject.toString();

        wr.write(queryString);
        wr.flush();
        wr.close();

        result = TimeSeriesUtility.readHttpResponse(httpConnection);

    } catch (IOException e) {
        throw new OpenTSDBException("Unable to connect to server", e);
    } catch (JSONException e) {
        throw new OpenTSDBException("Error on request data", e);
    }

    return TimeSeriesUtility.makeResponseJSONArray(result);
}

From source file:com.oxiane.maven.xqueryMerger.Merger.java

@Override
public void execute() throws MojoExecutionException {
    Path sourceRootPath = inputSources.toPath();
    Path destinationRootPath = outputDirectory.toPath();
    IOFileFilter filter = buildFilter();
    Iterator<File> it = FileUtils.iterateFiles(inputSources, filter, FileFilterUtils.directoryFileFilter());
    if (!it.hasNext()) {
        getLog().warn("No file found matching " + filter.toString() + " in " + inputSources.getAbsolutePath());
    }/*from ww  w. ja  v  a2 s  .  co  m*/
    while (it.hasNext()) {
        File sourceFile = it.next();
        Path fileSourcePath = sourceFile.toPath();
        Path relativePath = sourceRootPath.relativize(fileSourcePath);
        getLog().debug("[Merger] found source: " + fileSourcePath.toString());
        getLog().debug("[Merger]    relative path is " + relativePath.toString());
        StreamSource source = new StreamSource(sourceFile);
        XQueryMerger merger = new XQueryMerger(source);
        merger.setMainQuery();
        File destinationFile = destinationRootPath.resolve(relativePath).toFile();
        getLog().debug("[Merger]    destination will be " + destinationFile.getAbsolutePath());
        try {
            String result = merger.merge();
            destinationFile.getParentFile().mkdirs();
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(destinationFile),
                    merger.getEncoding());
            osw.write(result);
            osw.flush();
            osw.close();
            getLog().debug("[Merger] " + relativePath.toString() + " merged into "
                    + destinationFile.getAbsolutePath());
        } catch (ParsingException ex) {
            getLog().error(ex.getMessage());
            throw new MojoExecutionException("Merge of " + sourceFile.getAbsolutePath() + " fails", ex);
        } catch (FileNotFoundException ex) {
            getLog().error(ex.getMessage());
            throw new MojoExecutionException(
                    "Unable to create destination " + destinationFile.getAbsolutePath(), ex);
        } catch (IOException ex) {
            getLog().error(ex.getMessage());
            throw new MojoExecutionException("While writing " + destinationFile.getAbsolutePath(), ex);
        }
    }
}

From source file:com.msopentech.odatajclient.testservice.utils.XmlElement.java

public InputStream toStream() throws Exception {
    InputStream res;/*from  w ww  . j a  v a2  s . co  m*/
    try {
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final OutputStreamWriter osw = new OutputStreamWriter(bos);

        getStart().writeAsEncodedUnicode(osw);
        osw.flush();

        IOUtils.copy(getContent(), bos);

        getEnd().writeAsEncodedUnicode(osw);
        osw.flush();
        osw.close();

        res = new ByteArrayInputStream(bos.toByteArray());
    } catch (Exception e) {
        LOG.error("Error serializing elemnt", e);
        res = null;
    }
    return res;
}

From source file:com.synelixis.xifi.AuthWebClient.Client.java

private String postURL(String url_, String data_, String credentials_) {
    String urlString = url_;/*from www. j a  va2 s.c o  m*/
    String JSON = data_;
    String credentials = credentials_;

    try {
        URL u = new URL(urlString);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setDoOutput(true);
        c.setRequestMethod("POST");
        if ((credentials != null) && !credentials.equals("")) {
            c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            c.setRequestProperty("Authorization", "Basic " + credentials);
        } else {
            c.setRequestProperty("Content-Type", "application/json");
            c.setRequestProperty("Accept", "application/json");
        }
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream());
        out.write(JSON);
        out.flush();
        out.close();
        System.out.println("url:" + url_ + " -- data:" + data_ + " -- response" + c.getResponseCode());
        switch (c.getResponseCode()) {
        case 200:
        case 201:
            BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            String result = sb.toString();
            return result;
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE,
                "Unexpected exception when call the remote server ", ex);
    }
    return null;
}