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:dualcontrol.CryptoClientDemo.java

private void call(Properties properties, MockableConsole console, String hostAddress, int port, byte[] data)
        throws Exception {
    Socket socket = SSLContexts.create(false, "cryptoclient.ssl", properties, console).getSocketFactory()
            .createSocket(hostAddress, port);
    DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
    dos.writeShort(data.length);//from   ww w  .j  a v a2 s. com
    dos.write(data);
    dos.flush();
    DataInputStream dis = new DataInputStream(socket.getInputStream());
    byte[] ivBytes = new byte[dis.readShort()];
    dis.readFully(ivBytes);
    byte[] bytes = new byte[dis.readShort()];
    dis.readFully(bytes);
    if (new String(data).contains("DECRYPT")) {
        System.err.printf("INFO CryptoClientDemo decrypted %s\n", new String(bytes));
    } else {
        System.out.printf("%s:%s\n", Base64.encodeBase64String(ivBytes), Base64.encodeBase64String(bytes));
    }
    socket.close();
}

From source file:com.linkedin.pinot.perf.ForwardIndexWriterBenchmark.java

public static void convertRawToForwardIndex(File rawFile) throws Exception {
    List<String> lines = IOUtils.readLines(new FileReader(rawFile));
    int totalDocs = lines.size();
    int max = Integer.MIN_VALUE;
    int maxNumberOfMultiValues = Integer.MIN_VALUE;
    int totalNumValues = 0;
    int data[][] = new int[totalDocs][];
    for (int i = 0; i < lines.size(); i++) {
        String line = lines.get(i);
        String[] split = line.split(",");
        totalNumValues = totalNumValues + split.length;
        if (split.length > maxNumberOfMultiValues) {
            maxNumberOfMultiValues = split.length;
        }//from  w w  w .jav  a  2s .c o m
        data[i] = new int[split.length];
        for (int j = 0; j < split.length; j++) {
            String token = split[j];
            int val = Integer.parseInt(token);
            data[i][j] = val;
            if (val > max) {
                max = val;
            }
        }
    }
    int maxBitsNeeded = (int) Math.ceil(Math.log(max) / Math.log(2));
    int size = 2048;
    int[] offsets = new int[size];
    int bitMapSize = 0;
    File outputFile = new File("output.mv.fwd");

    FixedBitMultiValueWriter fixedBitSkipListSCMVWriter = new FixedBitMultiValueWriter(outputFile, totalDocs,
            totalNumValues, maxBitsNeeded);

    for (int i = 0; i < totalDocs; i++) {
        fixedBitSkipListSCMVWriter.setIntArray(i, data[i]);
        if (i % size == size - 1) {
            MutableRoaringBitmap rr1 = MutableRoaringBitmap.bitmapOf(offsets);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(bos);
            rr1.serialize(dos);
            dos.close();
            // System.out.println("Chunk " + i / size + " bitmap size:" + bos.size());
            bitMapSize += bos.size();
        } else if (i == totalDocs - 1) {
            MutableRoaringBitmap rr1 = MutableRoaringBitmap.bitmapOf(Arrays.copyOf(offsets, i % size));
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(bos);
            rr1.serialize(dos);
            dos.close();
            // System.out.println("Chunk " + i / size + " bitmap size:" + bos.size());
            bitMapSize += bos.size();
        }
    }
    fixedBitSkipListSCMVWriter.close();
    System.out.println("Output file size:" + outputFile.length());
    System.out.println("totalNumberOfDoc\t\t\t:" + totalDocs);
    System.out.println("totalNumberOfValues\t\t\t:" + totalNumValues);
    System.out.println("chunk size\t\t\t\t:" + size);
    System.out.println("Num chunks\t\t\t\t:" + totalDocs / size);
    int numChunks = totalDocs / size + 1;
    int totalBits = (totalNumValues * maxBitsNeeded);
    int dataSizeinBytes = (totalBits + 7) / 8;

    System.out.println("Raw data size with fixed bit encoding\t:" + dataSizeinBytes);
    System.out.println("\nPer encoding size");
    System.out.println();
    System.out.println("size (offset + length)\t\t\t:" + ((totalDocs * (4 + 4)) + dataSizeinBytes));
    System.out.println();
    System.out.println("size (offset only)\t\t\t:" + ((totalDocs * (4)) + dataSizeinBytes));
    System.out.println();
    System.out.println("bitMapSize\t\t\t\t:" + bitMapSize);
    System.out.println("size (with bitmap)\t\t\t:" + (bitMapSize + (numChunks * 4) + dataSizeinBytes));

    System.out.println();
    System.out.println("Custom Bitset\t\t\t\t:" + (totalNumValues + 7) / 8);
    System.out.println("size (with custom bitset)\t\t\t:"
            + (((totalNumValues + 7) / 8) + (numChunks * 4) + dataSizeinBytes));
}

From source file:com.meetingninja.csse.database.BaseDatabaseAdapter.java

protected static int sendPostPayload(URLConnection connection, String payload) throws IOException {
    Log.d(IRequest.POST, "[URL] " + connection.getURL().toString());
    logPrint(payload);//from  w w w .j av  a2  s  . c o  m

    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    return ((HttpURLConnection) connection).getResponseCode();
}

From source file:cit360.sandbox.BackEndMenu.java

public static final void smtpExample() {
    // declaration section:
    // smtpClient: our client socket
    // os: output stream
    // is: input stream
    Socket smtpSocket = null;// w  ww  . j  a  va 2 s  .c o m
    DataOutputStream os = null;
    DataInputStream is = null;
    // Initialization section:
    // Try to open a socket on port 25
    // Try to open input and output streams
    try {
        smtpSocket = new Socket("localhost", 25);
        os = new DataOutputStream(smtpSocket.getOutputStream());
        is = new DataInputStream(smtpSocket.getInputStream());
    } catch (UnknownHostException e) {
        System.err.println("Did not recognize server: localhost");
    } catch (IOException e) {
        System.err.println("Was not able to open I/O connection to: localhost");
    }
    // If everything has been initialized then we want to write some data
    // to the socket we have opened a connection to on port 25
    if (smtpSocket != null && os != null && is != null) {
        try {

            os.writeBytes("HELO\n");
            os.writeBytes("MAIL From: david.banks0889@gmail.com\n");
            os.writeBytes("RCPT To: david.banks0889@gmail.com\n");
            os.writeBytes("DATA\n");
            os.writeBytes("From: david.banks0889@gmail.com\n");
            os.writeBytes("Subject: TEST\n");
            os.writeBytes("Hi there\n"); // message body
            os.writeBytes("\n.\n");
            os.writeBytes("QUIT");
            // keep on reading from/to the socket till we receive the "Ok" from SMTP,
            // once we received that then we want to break.
            String responseLine;
            while ((responseLine = is.readLine()) != null) {
                System.out.println("Server: " + responseLine);
                if (responseLine.contains("Ok")) {
                    break;
                }
            }
            // clean up:
            // close the output stream
            // close the input stream
            // close the socket
            os.close();
            is.close();
            smtpSocket.close();
        } catch (UnknownHostException e) {
            System.err.println("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
    }
}

From source file:com.dbay.apns4j.tools.ApnsTools.java

@Deprecated
public final static byte[] generateData(int id, int expire, byte[] token, byte[] payload) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream os = new DataOutputStream(bos);
    try {//w w  w .ja  v  a2  s  .co  m
        os.writeByte(Command.SEND);
        os.writeInt(id);
        os.writeInt(expire);
        os.writeShort(token.length);
        os.write(token);
        os.writeShort(payload.length);
        os.write(payload);
        os.flush();
        return bos.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    }
    throw new RuntimeException();
}

From source file:LCModels.MessageTransmitter.java

@Override
public void run() {
    try {//from www .  j  a v  a2s. co m
        // Socket connects to the ServerSocket, ServerSocket receives a Socket, what? haha//
        //send data as points
        //            Socket s = new Socket(hostname,targetPort);
        //            Socket z = new Socket(hostname, 48500, InetAddress.getByName("127.0.0.1"), targetPort);
        Socket client = new Socket(hostname, targetPort);
        /* Get server's OutputStream */
        OutputStream outToServer = client.getOutputStream();
        /* Get server's DataOutputStream to write/send message */
        DataOutputStream out = new DataOutputStream(outToServer);
        /* Write message to DataOutputStream */
        out.writeUTF(transmitJSON.toString());
        /* Get InputStream to get message from server */
        InputStream inFromServer = client.getInputStream();
        /* Get DataInputStream to read message of server */
        DataInputStream in = new DataInputStream(inFromServer);
        /* Print message received from server */
        System.out.println("Server says..." + in.readUTF());
        client.close();
    } catch (IOException ex) {
        Logger.getLogger(MessageTransmitter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:MainFrame.CheckConnection.java

private boolean isOnline() throws MalformedURLException, IOException, Exception {
    String url = "http://www.itstepdeskview.hol.es";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

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

    String urlParameters = "apideskviewer.checkStatus={}";

    // Send post request
    con.setDoOutput(true);/*from w  w w  . j a va  2s.  c om*/
    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()));

    JSONParser parser = new JSONParser();
    Object parsedResponse = parser.parse(in);

    JSONObject jsonParsedResponse = (JSONObject) parsedResponse;

    String s = (String) jsonParsedResponse.get("response");
    if (s.equals("online")) {
        return true;
    } else {
        return false;
    }
}

From source file:buildhappy.tools.DownloadFile.java

/**
 * ?filepath???/*from  ww  w.  ja v  a2 s .  c  o m*/
 */
private void saveToLocal(byte[] data, String filePath) {
    FileOutputStream fileOut = null;
    DataOutputStream dataOut = null;
    try {
        fileOut = new FileOutputStream(new File(filePath));
        dataOut = new DataOutputStream(fileOut);
        for (int i = 0; i < data.length; i++) {
            dataOut.write(data[i]);
        }
        dataOut.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (dataOut != null) {
            try {
                dataOut.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:edu.mit.ll.graphulo.util.SerializationUtil.java

public static void serializeWritable(Writable obj, OutputStream outputStream) {
    Preconditions.checkNotNull(obj);//  w  w  w . j  av  a 2 s.  co  m
    Preconditions.checkNotNull(outputStream);
    try (DataOutputStream out = new DataOutputStream(outputStream)) {
        obj.write(out);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:backtype.storm.utils.ShellProcess.java

public Number launch(Map conf, TopologyContext context) throws IOException {
    ProcessBuilder builder = new ProcessBuilder(command);
    builder.directory(new File(context.getCodeDir()));
    _subprocess = builder.start();/*from   ww  w . j a  v a 2  s. c o m*/

    processIn = new DataOutputStream(_subprocess.getOutputStream());
    processOut = new BufferedReader(new InputStreamReader(_subprocess.getInputStream()));
    processErrorStream = _subprocess.getErrorStream();

    JSONObject setupInfo = new JSONObject();
    setupInfo.put("pidDir", context.getPIDDir());
    setupInfo.put("conf", conf);
    setupInfo.put("context", context);
    writeMessage(setupInfo);

    return (Number) readMessage().get("pid");
}