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:net.mohatu.bloocoin.miner.RegisterClass.java

private void register() {
    try {//from  w  w w. j a  va2 s  .  co  m
        String result = new String();
        Socket sock = new Socket(this.url, this.port);
        String command = "{\"cmd\":\"register" + "\",\"addr\":\"" + addr + "\",\"pwd\":\"" + key + "\"}";
        DataInputStream is = new DataInputStream(sock.getInputStream());
        DataOutputStream os = new DataOutputStream(sock.getOutputStream());
        os.write(command.getBytes());
        os.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            result += inputLine;
        }

        is.close();
        os.close();
        sock.close();
        System.out.println(result);
        if (result.contains("\"success\": true")) {
            System.out.println("Registration successful: " + addr);
            saveBloostamp();
        } else if (result.contains("\"success\": false")) {
            System.out.println("Result: Failed");
            MainView.updateStatusText("Registration failed. ");
            System.exit(0);
        }
    } catch (UnknownHostException e) {
        System.out.println("Error: Unknown host.");
    } catch (IOException e) {
        System.out.println("Error: Network error.");
    }
}

From source file:com.apteligent.ApteligentJavaClient.java

/*********************************************************************************************************************/

private Token auth(String email, String password) throws IOException {
    String urlParameters = "grant_type=password&username=" + email + "&password=" + password;

    URL obj = new URL(API_TOKEN);
    HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
    conn.setDoOutput(true);/* w ww  . j a  va2s.c o  m*/
    conn.setDoInput(true);

    //add request header
    String basicAuth = new String(Base64.encodeBytes(apiKey.getBytes()));
    conn.setRequestProperty("Authorization", String.format("Basic %s", basicAuth));
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
    conn.setRequestMethod("POST");

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

    // read token
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser jp = jsonFactory.createParser(conn.getInputStream());
    ObjectMapper mapper = getObjectMapper();
    Token token = mapper.readValue(jp, Token.class);

    return token;
}

From source file:info.fetter.logstashforwarder.protocol.LumberjackClient.java

public int sendCompressedFrame(List<Map<String, byte[]>> keyValuesList) throws IOException {
    output.writeByte(PROTOCOL_VERSION);/*from w w w .java  2s  . c  o m*/
    output.writeByte(FRAME_COMPRESSED);

    ByteArrayOutputStream uncompressedBytes = new ByteArrayOutputStream();
    DataOutputStream uncompressedOutput = new DataOutputStream(uncompressedBytes);
    for (Map<String, byte[]> keyValues : keyValuesList) {
        logger.trace("Adding data frame");
        sendDataFrame(uncompressedOutput, keyValues);
    }
    uncompressedOutput.close();
    Deflater compressor = new Deflater();
    byte[] uncompressedData = uncompressedBytes.toByteArray();
    if (logger.isDebugEnabled()) {
        logger.debug("Deflating data : " + uncompressedData.length + " bytes");
    }
    if (logger.isTraceEnabled()) {
        HexDump.dump(uncompressedData, 0, System.out, 0);
    }
    compressor.setInput(uncompressedData);
    compressor.finish();

    ByteArrayOutputStream compressedBytes = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    while (!compressor.finished()) {
        int count = compressor.deflate(buffer);
        compressedBytes.write(buffer, 0, count);
    }
    compressedBytes.close();
    byte[] compressedData = compressedBytes.toByteArray();
    if (logger.isDebugEnabled()) {
        logger.debug("Deflated data : " + compressor.getTotalOut() + " bytes");
    }
    if (logger.isTraceEnabled()) {
        HexDump.dump(compressedData, 0, System.out, 0);
    }

    output.writeInt(compressor.getTotalOut());
    output.write(compressedData);
    output.flush();

    if (logger.isDebugEnabled()) {
        logger.debug("Sending compressed frame : " + keyValuesList.size() + " frames");
    }
    return 6 + compressor.getTotalOut();
}

From source file:io.dacopancm.socketdcm.net.StreamSocket.java

public void handle() {
    try {/* w  ww  .j  ava 2s  .c  o m*/

        if (ConectType.GET_STREAMLIST.name().equalsIgnoreCase(method)) {
            DataOutputStream dOut = new DataOutputStream(sock.getOutputStream());
            DataInputStream dIn = new DataInputStream(sock.getInputStream());

            String files = HelperUtil.toJSON(mainApp.getStreamFilesList().toArray());

            dOut.writeUTF(files);
            dOut.flush(); // Send off the data
            dOut.close();
        } else if (ConectType.GET_STREAM.name().equalsIgnoreCase(method)) {
            DataOutputStream dOut = new DataOutputStream(sock.getOutputStream());
            DataInputStream dIn = new DataInputStream(sock.getInputStream());

            boolean player = mainApp.playStream(streamid);

            dOut.writeUTF("" + (player ? HelperUtil.VLC_SRV_PORT : player));
            dOut.flush(); // Send off the data
            dOut.close();

        }
    } catch (IOException ex) {
        HelperUtil.showErrorB("No se pudo establecer conexin");
        try {
            if (sock != null) {
                sock.close();
            }
        } catch (IOException e) {
        }
    }
}

From source file:com.machinelinking.api.client.APIClient.java

private InputStream sendRequest(String service, String group, Map<String, Object> properties)
        throws IOException {
    try {/*ww  w. jav a 2  s.  co  m*/
        URL url = new URL(service);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(connTimeout);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoOutput(true);

        properties.put(ParamsValidator.app_id, appId);
        properties.put(ParamsValidator.app_key, appKey);
        StringBuilder data = ParamsValidator.getInstance().buildRequest(group, properties);
        httpURLConnection.addRequestProperty("Content-type",
                "application/x-www-form-urlencoded; charset=UTF-8");

        DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
        dataOutputStream.write(data.toString().getBytes());
        dataOutputStream.close();

        if (httpURLConnection.getResponseCode() == 200) {
            return httpURLConnection.getInputStream();
        } else {
            return httpURLConnection.getErrorStream();
        }
    } catch (MalformedURLException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.datatorrent.contrib.hdht.MockFileAccess.java

@Override
public FileWriter getWriter(final long bucketKey, final String fileName) throws IOException {
    final DataOutputStream dos = getOutputStream(bucketKey, fileName);
    final CountingOutputStream cos = new CountingOutputStream(dos);
    final Output out = new Output(cos);

    return new FileWriter() {
        @Override//from   w w w  .  j  a  va2  s .c  o  m
        public void close() throws IOException {
            out.close();
            cos.close();
            dos.close();
        }

        @Override
        public void append(byte[] key, byte[] value) throws IOException {
            kryo.writeObject(out, key);
            kryo.writeObject(out, value);
        }

        @Override
        public long getBytesWritten() {
            return cos.getCount() + out.position();
        }

    };

}

From source file:com.quigley.zabbixj.agent.active.ActiveThread.java

private byte[] getRequest(JSONObject jsonObject) throws Exception {
    byte[] requestBytes = jsonObject.toString().getBytes();

    String header = "ZBXD\1";
    byte[] headerBytes = header.getBytes();

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    dos.writeLong(requestBytes.length);/*from   ww w.  ja v  a2 s.  com*/
    dos.flush();
    dos.close();
    bos.close();
    byte[] requestLengthBytes = bos.toByteArray();

    byte[] allBytes = new byte[headerBytes.length + requestLengthBytes.length + requestBytes.length];

    int index = 0;
    for (int i = 0; i < headerBytes.length; i++) {
        allBytes[index++] = headerBytes[i];
    }
    for (int i = 0; i < requestLengthBytes.length; i++) {
        allBytes[index++] = requestLengthBytes[7 - i]; // Reverse the byte order.
    }
    for (int i = 0; i < requestBytes.length; i++) {
        allBytes[index++] = requestBytes[i];
    }

    return allBytes;
}

From source file:com.github.abilityapi.abilityapi.external.Metrics.java

/**
 * Sends the data to the bStats server.//from w w  w  .j  a va  2 s. c o m
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JsonObject data) throws Exception {
    Validate.notNull(data, "Data cannot be null");
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}

From source file:net.mohatu.bloocoin.miner.RegCustom.java

private void register() {
    try {// ww w .ja  v a2  s.  com
        String result = new String();
        Socket sock = new Socket(this.url, this.port);
        String command = "{\"cmd\":\"register" + "\",\"addr\":\"" + addr + "\",\"pwd\":\"" + key + "\"}";
        DataInputStream is = new DataInputStream(sock.getInputStream());
        DataOutputStream os = new DataOutputStream(sock.getOutputStream());
        os.write(command.getBytes());
        os.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            result += inputLine;
        }

        is.close();
        os.close();
        sock.close();
        System.out.println(result);
        if (result.contains("\"success\": true")) {
            System.out.println("Registration successful: " + addr);
            saveBloostamp();
        } else if (result.contains("\"success\": false")) {
            System.out.println("Result: Failed");
            JOptionPane.showMessageDialog(Main.scrollPane,
                    "Registration failed.\nCheck your network connection", "Registration Failed",
                    JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:httpRequests.GetPost.java

private void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);/*from  w  ww. ja v  a2  s .c  o m*/
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    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());

}