Example usage for java.io DataOutputStream close

List of usage examples for java.io DataOutputStream close

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with the stream.

Usage

From source file:com.ning.arecibo.util.timeline.samples.TestSampleCoder.java

@Test(groups = "fast")
public void testScan() throws Exception {
    final DateTime startTime = new DateTime(DateTimeZone.UTC);
    final DateTime endTime = startTime.plusSeconds(5);
    final List<DateTime> dateTimes = ImmutableList.<DateTime>of(startTime.plusSeconds(1),
            startTime.plusSeconds(2), startTime.plusSeconds(3), startTime.plusSeconds(4));
    final byte[] compressedTimes = timelineCoder.compressDateTimes(dateTimes);

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
    final ScalarSample<Short> sample = new ScalarSample<Short>(SampleOpcode.SHORT, (short) 4);
    sampleCoder.encodeSample(dataOutputStream, sample);
    sampleCoder.encodeSample(dataOutputStream, new RepeatSample<Short>(3, sample));
    dataOutputStream.close();

    sampleCoder.scan(outputStream.toByteArray(), compressedTimes, dateTimes.size(),
            new TimeRangeSampleProcessor(startTime, endTime) {
                @Override// w w  w . j ava2s .com
                public void processOneSample(final DateTime time, final SampleOpcode opcode,
                        final Object value) {
                    Assert.assertTrue(time.isAfter(startTime));
                    Assert.assertTrue(time.isBefore(endTime));
                    Assert.assertEquals(Short.valueOf(value.toString()), sample.getSampleValue());
                }
            });
}

From source file:com.amazon.alexa.avs.auth.companionapp.OAuth2ClientForPkce.java

JsonObject postRequest(HttpURLConnection connection, String data) throws IOException {
    int responseCode = -1;
    InputStream error = null;/*from  ww  w .  j  a v  a 2  s.c o m*/
    InputStream response = null;
    DataOutputStream outputStream = null;
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setDoOutput(true);

    outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(data.getBytes(StandardCharsets.UTF_8));
    outputStream.flush();
    outputStream.close();
    responseCode = connection.getResponseCode();

    try {
        response = connection.getInputStream();
        JsonReader reader = Json.createReader(new InputStreamReader(response, StandardCharsets.UTF_8));
        return reader.readObject();

    } catch (IOException ioException) {
        error = connection.getErrorStream();
        if (error != null) {
            LWAException lwaException = new LWAException(IOUtils.toString(error), responseCode);
            throw lwaException;
        } else {
            throw ioException;
        }
    } finally {
        IOUtils.closeQuietly(error);
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(response);
    }
}

From source file:fi.elfcloud.sci.Connection.java

/**
 * Does a store operation to elfcloud.fi server.
 * @param headers request headers to be applied
 * @param dataChunk data to be sent/*from w  w  w  .jav  a2  s  .  com*/
 * @param len length of the data
 * @throws ECException
 */
public void sendData(Map<String, String> headers, byte[] dataChunk, int len) throws ECException {
    Object[] keys = headers.keySet().toArray();
    URL url;

    try {
        url = new URL(Connection.url + Connection.apiVersion + "/store");
        conn = (HttpURLConnection) url.openConnection();
        for (int i = 0; i < keys.length; i++) {
            conn.setRequestProperty((String) keys[i], headers.get(keys[i]));
        }
        conn.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.write(dataChunk, 0, len);
        String result = conn.getHeaderField("X-ELFCLOUD-RESULT");
        wr.close();
        if (conn.getResponseCode() != 200 || !result.equals("OK")) {
            ECDataItemException exception;
            if (conn.getResponseCode() == 200) {
                String[] exceptionData = result.split(" ", 4);
                int exceptionID = Integer.parseInt(exceptionData[1]);
                String message = exceptionData[3];
                if (exceptionID == 101) {
                    cookieJar.removeAll();
                    while (authTries < 3) {
                        if (auth()) {
                            sendData(headers, dataChunk, len);
                            return;
                        }
                    }
                    authTries = 0;
                }
                exception = new ECDataItemException();
                exception.setId(exceptionID);
                exception.setMessage(message);
            } else {
                exception = new ECDataItemException();
                exception.setId(conn.getResponseCode());
                exception.setMessage(conn.getResponseMessage());
            }
            throw exception;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        ECClientException exception = new ECClientException();
        exception.setId(408);
        exception.setMessage("Error connecting to elfcloud.fi server");
        authTries = 0;
        throw exception;
    }

}

From source file:ml.shifu.guagua.io.Bzip2BytableSerializer.java

/**
 * Serialize from object to bytes./*w  ww  .j  ava2 s  .  c  om*/
 * 
 * @throws NullPointerException
 *             if result is null.
 * @throws GuaguaRuntimeException
 *             if any io exception.
 */
@Override
public byte[] objectToBytes(RESULT result) {
    ByteArrayOutputStream out = null;
    DataOutputStream dataOut = null;
    try {
        out = new ByteArrayOutputStream();
        OutputStream gzipOutput = new BZip2CompressorOutputStream(out);
        dataOut = new DataOutputStream(gzipOutput);
        result.write(dataOut);
    } catch (IOException e) {
        throw new GuaguaRuntimeException(e);
    } finally {
        if (dataOut != null) {
            try {
                dataOut.close();
            } catch (IOException e) {
                throw new GuaguaRuntimeException(e);
            }
        }
    }
    return out.toByteArray();
}

From source file:hudson.console.ConsoleNote.java

private ByteArrayOutputStream encodeToBytes() throws IOException {
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(new GZIPOutputStream(buf));
    try {/*from ww  w .j ava  2  s  .  c om*/
        oos.writeObject(this);
    } finally {
        oos.close();
    }

    ByteArrayOutputStream buf2 = new ByteArrayOutputStream();

    DataOutputStream dos = new DataOutputStream(new Base64OutputStream(buf2, true, -1, null));
    try {
        buf2.write(PREAMBLE);
        dos.writeInt(buf.size());
        buf.writeTo(dos);
    } finally {
        dos.close();
    }
    buf2.write(POSTAMBLE);
    return buf2;
}

From source file:com.reddit.util.ApiUtil.java

/**
 * Experimental right now.  I messed around with this but never really used it for anything.
 * /*from w  w  w.java2 s .c o  m*/
 * @param url should be new URL("https://ssl.reddit.com/api/login/myusername");
 * @param user
 * @param pw
 * @throws IOException
 * @throws JSONException
 */
public void login(URL url, String user, String pw) throws IOException, JSONException {

    String data = "api_type=json&user=" + user + "&passwd=" + pw;
    HttpURLConnection httpUrlConn = null;
    httpUrlConn = (HttpURLConnection) url.openConnection();
    httpUrlConn.setRequestMethod("POST");
    httpUrlConn.setDoOutput(true);
    httpUrlConn.setUseCaches(false);
    httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    httpUrlConn.setRequestProperty("Content-Length", String.valueOf(data.length()));

    DataOutputStream dataOutputStream = new DataOutputStream(httpUrlConn.getOutputStream());
    dataOutputStream.writeBytes(data);
    dataOutputStream.flush();
    dataOutputStream.close();
    InputStream is = httpUrlConn.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
    String line;
    StringBuffer response = new StringBuffer();
    while ((line = bufferedReader.readLine()) != null) {
        response.append(line);
        response.append('\r');
    }
    for (Entry<String, List<String>> r : httpUrlConn.getHeaderFields().entrySet()) {
        System.out.println(r.getKey() + ": " + r.getValue());
    }
    bufferedReader.close();
    System.out.println("Response: " + response.toString());
    this.setModHash(new JSONObject(response.toString()).getJSONObject("json").getJSONObject("data")
            .getString("modhash"));
    this.setCookie(new JSONObject(response.toString()).getJSONObject("json").getJSONObject("data")
            .getString("cookie"));

}

From source file:api.APICall.java

public String executePost(String targetURL, String urlParameters) {
    URL url;/*w  w w  .ja v  a 2  s. c o m*/
    HttpURLConnection connection = null;
    try {
        // Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        // Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        // Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();

    } catch (SocketException se) {
        se.printStackTrace();
        System.out.println("Server is down.");
        return null;
    } catch (Exception e) {

        e.printStackTrace();
        return null;

    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.mendhak.gpslogger.senders.gdocs.GDocsHelper.java

private String UpdateFileContents(String authToken, String gpxFileId, byte[] fileContents) {
    HttpURLConnection conn = null;
    String fileId = null;//from w w w. j a  v  a 2 s .  c  om

    String fileUpdateUrl = "https://www.googleapis.com/upload/drive/v2/files/" + gpxFileId
            + "?uploadType=media";

    try {

        if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
            //Due to a pre-froyo bug
            //http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            System.setProperty("http.keepAlive", "false");
        }

        URL url = new URL(fileUpdateUrl);

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("User-Agent", "GPSLogger for Android");
        conn.setRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Content-Type", "application/xml");
        conn.setRequestProperty("Content-Length", String.valueOf(fileContents.length));

        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.write(fileContents);
        wr.flush();
        wr.close();

        String fileMetadata = Utilities.GetStringFromInputStream(conn.getInputStream());

        JSONObject fileMetadataJson = new JSONObject(fileMetadata);
        fileId = fileMetadataJson.getString("id");
        Utilities.LogDebug("File updated : " + fileId);

    } catch (Exception e) {
        System.out.println(e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }

    }

    return fileId;

}

From source file:net.roboconf.target.azure.internal.AzureIaasHandler.java

private int processPostRequest(URL url, byte[] data, String contentType, String keyStore,
        String keyStorePassword) throws GeneralSecurityException, IOException {

    SSLSocketFactory sslFactory = this.getSSLSocketFactory(keyStore, keyStorePassword);
    HttpsURLConnection con;/*ww  w  .  j ava2s  .  c  o m*/
    con = (HttpsURLConnection) url.openConnection();
    con.setSSLSocketFactory(sslFactory);
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.addRequestProperty("x-ms-version", "2014-04-01");
    con.setRequestProperty("Content-Length", String.valueOf(data.length));
    con.setRequestProperty("Content-Type", contentType);

    DataOutputStream requestStream = new DataOutputStream(con.getOutputStream());
    requestStream.write(data);
    requestStream.flush();
    requestStream.close();

    return con.getResponseCode();
}

From source file:net.servicestack.client.JsonServiceClient.java

public HttpURLConnection createRequest(String requestUrl, String httpMethod, byte[] requestBody,
        String requestType) {/*from  w  ww.  j  a  va2 s  . c o m*/
    try {
        URL url = new URL(requestUrl);

        HttpURLConnection req = (HttpURLConnection) url.openConnection();
        req.setDoOutput(true);

        if (timeoutMs != null) {
            req.setConnectTimeout(timeoutMs);
            req.setReadTimeout(timeoutMs);
        }

        req.setRequestMethod(httpMethod);
        req.setRequestProperty(HttpHeaders.Accept, MimeTypes.Json);

        if (requestType != null) {
            req.setRequestProperty(HttpHeaders.ContentType, requestType);
        }

        if (requestBody != null) {
            req.setRequestProperty(HttpHeaders.ContentLength, Integer.toString(requestBody.length));
            DataOutputStream wr = new DataOutputStream(req.getOutputStream());
            wr.write(requestBody);
            wr.flush();
            wr.close();
        }

        if (RequestFilter != null) {
            RequestFilter.exec(req);
        }

        if (GlobalRequestFilter != null) {
            GlobalRequestFilter.exec(req);
        }

        return req;

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}