Example usage for java.io DataOutputStream DataOutputStream

List of usage examples for java.io DataOutputStream DataOutputStream

Introduction

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

Prototype

public DataOutputStream(OutputStream out) 

Source Link

Document

Creates a new data output stream to write data to the specified underlying output stream.

Usage

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

private void register() {
    try {//from  w  w  w.j  a v  a  2 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");
            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:net.mohatu.bloocoin.miner.RegisterClass.java

private void register() {
    try {//  w  ww .  java2  s.c om
        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:dualcontrol.CryptoHandler.java

public void handle(DualControlKeyStoreSession dualControl, Socket socket) throws Exception {
    try {//  w ww .j  a v a2s .  co m
        this.dualControl = dualControl;
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        int length = dis.readShort();
        byte[] bytes = new byte[length];
        dis.readFully(bytes);
        String data = new String(bytes);
        String[] fields = data.split(":");
        String mode = fields[0];
        String alias = fields[1];
        this.dos = new DataOutputStream(socket.getOutputStream());
        if (mode.equals("GETKEY")) {
            if (enableGetKey) {
                SecretKey key = dualControl.loadKey(alias);
                dos.writeUTF(key.getAlgorithm());
                write(key.getEncoded());
            }
        } else {
            cipher(mode, alias, fields[2], fields[3], fields[4]);
        }
    } finally {
        dos.close();
    }
}

From source file:com.pinterest.deployservice.events.EventSenderImpl.java

public void sendDeployEvent(String what, String tags, String data) throws Exception {
    JsonObject object = new JsonObject();
    object.addProperty("what", what);
    object.addProperty("tags", tags);
    object.addProperty("data", data);
    final String paramsToSend = object.toString();
    DataOutputStream output = null;
    HttpURLConnection connection = null;
    int retry = 0;
    while (retry < TOTAL_RETRY) {
        try {/*from w  ww . j a va 2  s  .com*/
            URL requestUrl = new URL(this.URL);
            connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setDoOutput(true);

            connection.setRequestProperty("Content-Type", "application/json; charset=utf8");
            connection.setRequestProperty("Content-Length", Integer.toString(paramsToSend.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setRequestMethod("POST");
            output = new DataOutputStream(connection.getOutputStream());
            output.writeBytes(paramsToSend);
            output.flush();
            output.close();
            String result = IOUtils.toString(connection.getInputStream(), "UTF-8").toLowerCase();
            LOG.info("Successfully send events to the statsboard: " + result);
            return;
        } catch (Exception e) {
            LOG.error("Failed to send event", e);
        } finally {
            IOUtils.closeQuietly(output);
            if (connection != null) {
                connection.disconnect();
            }
            retry++;
        }
    }
    throw new DeployInternalException("Failed to send event");
}

From source file:com.koda.common.lcm.Tool.java

public static void toFile(String fn, Serializable obj) throws IOException {
    FileOutputStream fos = new FileOutputStream(fn);
    DataOutputStream dos = new DataOutputStream(fos);
    dos.writeUTF(doObject(obj));//w  w  w . j  ava 2  s  .c  om

}

From source file:com.example.networkPacketFormats.ServeFunction.java

public ServeFunction(Socket s, Connection con) {
    this.con = con;
    sock = s;/*from   www. j a  v a2 s. c o  m*/
    try {
        /*
        Get the input stream
        */
        inFromClient = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        /*
        Get the Output stream
        */
        outToClient = new DataOutputStream(sock.getOutputStream());

    } catch (IOException ex) {
        Logger.getLogger(ServeFunction.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.cloudmaster.cmp.util.AlarmSystem.transfer.HttpSender.java

public ResponseObject send(TransportObject object) throws Exception {
    ResponseObject rs = new ResponseObject();
    ByteArrayOutputStream bOs = null;
    DataOutputStream dOs = null;/*from  w  w w .  j  a va 2s . co m*/
    DataInputStream dIs = null;
    HttpClient client;
    PostMethod meth = null;
    byte[] rawData;
    try {
        bOs = new ByteArrayOutputStream();
        dOs = new DataOutputStream(bOs);
        object.toStream(dOs);
        bOs.flush();
        rawData = bOs.toByteArray();

        client = new HttpClient();
        client.setConnectionTimeout(this.timeout);
        client.setTimeout(this.datatimeout);
        client.setHttpConnectionFactoryTimeout(this.timeout);

        meth = new PostMethod(object.getValue(SERVER_URL));
        // meth = new UTF8PostMethod(url);
        meth.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, ENCODING);
        // meth.addParameter(SERVER_ARGS, new String(rawData,"UTF-8"));

        // meth.setRequestBody(new String(rawData));
        // meth.setRequestBody(new String(rawData,"UTF-8"));

        byte[] base64Array = Base64.encode(rawData).getBytes();
        meth.setRequestBody(new String(base64Array));

        // System.out.println(new String(rawData));

        client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(1, false));
        client.executeMethod(meth);

        dIs = new DataInputStream(meth.getResponseBodyAsStream());

        if (meth.getStatusCode() == HttpStatus.SC_OK) {

            Header errHeader = meth.getResponseHeader(HDR_ERROR);

            if (errHeader != null) {
                rs.setError(meth.getResponseBodyAsString());
                return rs;
            }

            rs = ResponseObject.fromStream(dIs);

            return rs;
        } else {
            meth.releaseConnection();
            throw new IOException("Connection failure: " + meth.getStatusLine().toString());
        }
    } finally {
        if (meth != null) {
            meth.releaseConnection();
        }
        if (bOs != null) {
            bOs.close();
        }
        if (dOs != null) {
            dOs.close();
        }
        if (dIs != null) {
            dIs.close();
        }
    }
}

From source file:MethodHashing.java

public static long methodHash(Method method) throws Exception {
    Class[] parameterTypes = method.getParameterTypes();
    String methodDesc = method.getName() + "(";
    for (int j = 0; j < parameterTypes.length; j++) {
        methodDesc += getTypeString(parameterTypes[j]);
    }//from  w w w. j a va  2  s . co m
    methodDesc += ")" + getTypeString(method.getReturnType());

    long hash = 0;
    ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(512);
    MessageDigest messagedigest = MessageDigest.getInstance("SHA");
    DataOutputStream dataoutputstream = new DataOutputStream(
            new DigestOutputStream(bytearrayoutputstream, messagedigest));
    dataoutputstream.writeUTF(methodDesc);
    dataoutputstream.flush();
    byte abyte0[] = messagedigest.digest();
    for (int j = 0; j < Math.min(8, abyte0.length); j++)
        hash += (long) (abyte0[j] & 0xff) << j * 8;
    return hash;
}

From source file:com.base2.kagura.core.authentication.RestAuthentication.java

public InputStream httpPost(String suffix, HashMap<String, String> values) {
    try {// ww  w . ja v a2  s  .  c  o m
        URL obj = new URL(url + "/" + suffix);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        con.setRequestMethod("POST");

        String data = new ObjectMapper().writeValueAsString(values);

        con.setRequestProperty("Content-Type", "application/json");
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(data);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        if (responseCode != 200)
            throw new Exception("Got error code: " + responseCode);
        return con.getInputStream();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.jmangos.sniffer.handler.PKTLogHandler.java

@Override
public void init() {
    final String date = String.format("%X", System.currentTimeMillis());
    final ByteBuffer buffer = ByteBuffer.allocate(66);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.put("PKT".getBytes());
    buffer.put((byte) 1);
    buffer.put((byte) 3);
    buffer.put((byte) 12);
    buffer.putInt(this.build);
    buffer.put("xxXX".getBytes());
    buffer.put(this.keyReader.getKey());
    buffer.putInt((int) (System.currentTimeMillis() / 1000L));
    buffer.putInt(0);//from   w  ww .  j  a v a2 s  .co  m
    buffer.putInt(0);
    try {
        this.fous = new DataOutputStream(new FileOutputStream(new File(this.build + "_" + date + ".pkt")));
        this.fous.write(buffer.array());
        setInit(true);
    } catch (final FileNotFoundException e) {
        e.printStackTrace();
    } catch (final IOException e) {
        e.printStackTrace();
    }
}