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:com.lyonsdensoftware.vanitymirror.PythonConnectionThread.java

@Override
public void run() {
    // Try connecting to the master server
    try {//from  w  w  w  . j a  va 2s .  com

        // Create a socket to connect to the server
        this.socket = new Socket(this.mainWindow.getConfigFile().getHostname(),
                this.mainWindow.getConfigFile().getPort());

        // Note it in the log
        log.info("LOG", "Connect to MasterServer at IP: " + socket.getInetAddress().getHostAddress()
                + " on PORT: " + socket.getPort());

        connectedToServer = true;

        // Create an input stream to receive data from the server
        mainWindow.setFromServer(new DataInputStream(socket.getInputStream()));

        // Create an output stream to send data to the server
        mainWindow.setToServer(new DataOutputStream(socket.getOutputStream()));

        // Main Loop
        while (runThread) {

            // Check for data from the server
            BufferedReader in = new BufferedReader(new InputStreamReader(mainWindow.getFromServer()));

            if (in.ready()) {
                // Convert in data to json
                Gson gson = new Gson();

                JSONObject json = new JSONObject(gson.fromJson(in.readLine(), JSONObject.class));

                if (json.keys().hasNext()) {
                    // handle the data
                    handleDataFromServer(json);
                } else {
                    System.out.println(json.toString());
                }
            }
        }

        // Loop not running now so close connection
        socket.close();
        mainWindow.getFromServer().close();
        mainWindow.getToServer().close();
    } catch (IOException ex) {
        log.error("ERROR", ex.toString());
    }
}

From source file:hudson.cli.Connection.java

public Connection(InputStream in, OutputStream out) {
    this.in = in;
    this.out = out;
    this.din = new DataInputStream(in);
    this.dout = new DataOutputStream(out);
}

From source file:com.snaplogic.snaps.lunex.RequestProcessor.java

public String execute(RequestBuilder rBuilder) throws MalformedURLException, IOException {
    try {/* w ww  . j  a  v  a 2 s.  co m*/
        URL api_url = new URL(rBuilder.getURL());
        HttpURLConnection httpUrlConnection = (HttpURLConnection) api_url.openConnection();
        httpUrlConnection.setRequestMethod(rBuilder.getMethod().toString());
        httpUrlConnection.setDoInput(true);
        httpUrlConnection.setDoOutput(true);
        if (rBuilder.getSnapType() != LunexSnaps.Read) {
            rBuilder.getHeaders().add(Pair.of(CONTENT_LENGTH, rBuilder.getRequestBodyLenght()));
        }
        for (Pair<String, String> header : rBuilder.getHeaders()) {
            if (!StringUtils.isEmpty(header.getKey()) && !StringUtils.isEmpty(header.getValue())) {
                httpUrlConnection.setRequestProperty(header.getKey(), header.getValue());
            }
        }
        log.debug(String.format(LUNEX_HTTP_INFO, rBuilder.getSnapType(), rBuilder.getURL(),
                httpUrlConnection.getRequestProperties().toString()));
        if (rBuilder.getSnapType() != LunexSnaps.Read) {
            String paramsJson = null;
            if (!StringUtils.isEmpty(paramsJson = rBuilder.getRequestBody())) {
                DataOutputStream cgiInput = new DataOutputStream(httpUrlConnection.getOutputStream());
                log.debug(String.format(LUNEX_HTTP_REQ_INFO, paramsJson));
                cgiInput.writeBytes(paramsJson);
                cgiInput.flush();
                IOUtils.closeQuietly(cgiInput);
            }
        }

        List<String> input = null;
        StringBuilder response = new StringBuilder();
        try (InputStream iStream = httpUrlConnection.getInputStream()) {
            input = IOUtils.readLines(iStream);
        } catch (IOException ioe) {
            log.warn(String.format(INPUT_STREAM_ERROR, ioe.getMessage()));
            try (InputStream eStream = httpUrlConnection.getErrorStream()) {
                if (eStream != null) {
                    input = IOUtils.readLines(eStream);
                } else {
                    response.append(String.format(INPUT_STREAM_ERROR, ioe.getMessage()));
                }
            } catch (IOException ioe1) {
                log.warn(String.format(INPUT_STREAM_ERROR, ioe1.getMessage()));
            }
        }
        statusCode = httpUrlConnection.getResponseCode();
        log.debug(String.format(HTTP_STATUS, statusCode));
        if (input != null && !input.isEmpty()) {
            for (String line : input) {
                response.append(line);
            }
        }
        return formatResponse(response, rBuilder);
    } catch (MalformedURLException me) {
        log.error(me.getMessage(), me);
        throw me;
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
        throw ioe;
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        throw ex;
    }
}

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

private void submit() {
    for (int i = 0; i < solved.size(); i++) {
        try {// ww  w.j a  v a2 s  .c  o  m
            Socket sock = new Socket(this.url, this.port);
            String result = new String();
            DataInputStream is = new DataInputStream(sock.getInputStream());
            DataOutputStream os = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            solution = solved.get(i);
            hash = DigestUtils.sha512Hex(solution);

            String command = "{\"cmd\":\"check" + "\",\"winning_string\":\"" + solution
                    + "\",\"winning_hash\":\"" + hash + "\",\"addr\":\"" + Main.getAddr() + "\"}";
            os = new DataOutputStream(sock.getOutputStream());
            os.write(command.getBytes());

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

            if (result.contains("\"success\": true")) {
                System.out.println("Result: Submitted");
                Main.updateStatusText(solution + " submitted", Color.blue);
                Thread gc = new Thread(new Coins());
                gc.start();
            } else if (result.contains("\"success\": false")) {
                System.out.println("Result: Failed");
                Main.updateStatusText("Submission of " + solution + " failed, already exists!", Color.red);
            }
            is.close();
            os.close();
            os.flush();
            sock.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            Main.updateStatusText("Submission of " + solution + " failed, connection failed!", Color.red);
        } catch (IOException e) {
            e.printStackTrace();
            Main.updateStatusText("Submission of " + solution + " failed, connection failed!", Color.red);
        }
    }
    Thread gc = new Thread(new Coins());
    gc.start();
}

From source file:com.cloudera.dataflow.hadoop.WritableCoder.java

@Override
public void encode(T value, OutputStream outStream, Context context) throws IOException {
    value.write(new DataOutputStream(outStream));
}

From source file:org.darwinathome.server.controller.HubController.java

@RequestMapping(Hub.AUTHENTICATE_SERVICE)
public void authenticate(@RequestParam(Hub.PARAM_BODY_NAME) String bodyName,
        @RequestParam(Hub.PARAM_PASSWORD) String password, OutputStream outputStream) throws IOException {
    log.info(Hub.AUTHENTICATE_SERVICE);/*w  w w  .j  a va 2  s. c  om*/
    DataOutputStream dos = new DataOutputStream(outputStream);
    Player player = storage.authenticate(bodyName, password);
    if (player != null) {
        PlayerSession session = new PlayerSession(player);
        sessionMap.put(session.getToken(), session);
        dos.writeUTF(Hub.SUCCESS);
        dos.writeUTF(session.getToken());
    } else {
        dos.writeUTF(Hub.FAILURE);
        dos.writeUTF(Failure.AUTHENTICATION.toString());
    }
    dos.close();
}

From source file:identify.SendMessage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w w  w.j  a v a 2 s  .  c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ParseException {
    String sender = request.getParameter("sender");
    String receiver = request.getParameter("receiver");
    String message = request.getParameter("body");
    int index = SaveToken.storage.findUsername(receiver);
    System.out.println(index);
    String tokenTo = SaveToken.storage.getData().get(index).getToken();
    JSONObject obj = new JSONObject();
    obj.put("sender", sender);
    obj.put("receiver", receiver);
    obj.put("body", message);
    JSONObject arrayObj = new JSONObject();
    arrayObj.put("to", tokenTo);
    arrayObj.put("data", obj);
    System.out.println(arrayObj.toString());
    String USER_AGENT = "Mozilla/5.0";
    String authKey = "key=AIzaSyBPldzkpB5YtLm3N8cYbdoweqtn5Dk3IfQ";
    String contentType = "application/json";
    String url = "https://fcm.googleapis.com/fcm/send";
    URL connection = new URL(url);
    HttpURLConnection con = (HttpURLConnection) connection.openConnection();

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

    String urlParameters = arrayObj.toString();
    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuilder resp = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        resp.append(inputLine);
    }
    in.close();
    String acrHeaders = request.getHeader("Access-Control-Request-Headers");
    String acrMethod = request.getHeader("Access-Control-Request-Method");
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Headers", acrHeaders);
    response.setHeader("Access-Control-Allow-Methods", acrMethod);
    response.setContentType("application/json:charset=UTF-8");
    response.getWriter().write(resp.toString());
}

From source file:org.darwinathome.server.persistence.impl.WorldHistoryImpl.java

public synchronized Frozen getFrozenWorld() {
    if (frozen == null || (frozen.getAge() < world().getAge())) {
        try {//from   w ww. j a  va 2  s .  c om
            log.info("Freezing...");
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            for (Being being : world().getBeings()) {
                being.getBody().executeTransformations(null);
            }
            world().write(new DataOutputStream(outputStream));
            frozen = new Frozen(outputStream.toByteArray(), world().getAge());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return frozen;
}

From source file:IntSort.java

public void writeStream(String[] sData, boolean[] bData, int[] iData) {
    try {//from  w  ww .  j a  v  a 2s.  co  m
        // Write data into an internal byte array
        ByteArrayOutputStream strmBytes = new ByteArrayOutputStream();

        // Write Java data types into the above byte array
        DataOutputStream strmDataType = new DataOutputStream(strmBytes);

        byte[] record;

        for (int i = 0; i < sData.length; i++) {
            // Write Java data types      
            strmDataType.writeUTF(sData[i]);
            strmDataType.writeBoolean(bData[i]);
            strmDataType.writeInt(iData[i]);

            // Clear any buffered data
            strmDataType.flush();

            // Get stream data into byte array and write record      
            record = strmBytes.toByteArray();
            rs.addRecord(record, 0, record.length);

            // Toss any data in the internal array so writes 
            // starts at beginning (of the internal array)
            strmBytes.reset();
        }

        strmBytes.close();
        strmDataType.close();

    } catch (Exception e) {
        db(e.toString());
    }
}