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:edu.cornell.med.icb.goby.compression.HybridChunkCodec1.java

@Override
public ByteArrayOutputStream encode(final Message readCollection) throws IOException {
    if (readCollection == null) {
        return null;
    }/* w  w w  . j a  va 2  s .c  om*/
    final ByteArrayOutputStream result = new ByteArrayOutputStream();
    final DataOutputStream completeChunkData = new DataOutputStream(result);
    final ByteArrayOutputStream hybridStreamBytes = new ByteArrayOutputStream();
    final Message reducedProtoBuff = handler.compressCollection(readCollection, hybridStreamBytes);

    final int hybridStreamSize = hybridStreamBytes.size();
    final byte[] bytes = hybridStreamBytes.toByteArray();

    crc32.reset();
    crc32.update(bytes);
    final int crcChecksum = (int) crc32.getValue();
    completeChunkData.writeInt(hybridStreamSize);
    completeChunkData.writeInt(crcChecksum);
    completeChunkData.write(bytes);

    final ByteArrayOutputStream out = gzipCodec.encode(reducedProtoBuff);

    final byte[] gzipBytes = out.toByteArray();
    final int gzipBytesSize = gzipBytes.length;
    completeChunkData.write(gzipBytes);
    completeChunkData.flush();
    if (debug && chunkIndex % 100 == 0) {

        //TODO remove compression of original collection. Only useful for stat collection
        int originalGzipSize = gzipCodec.encode(readCollection).toByteArray().length;

        final int gain = originalGzipSize - (gzipBytesSize + hybridStreamSize);
        LOG.info(String.format(
                "compressed size=%d gzip size=%d (original gzip=%d) percent compressed/(compressed+gzip) %g gain=%d, %g%% ",
                hybridStreamSize, gzipBytesSize, originalGzipSize,
                100d * ((double) hybridStreamSize) / (hybridStreamSize + gzipBytesSize), gain,
                gain * 100d / originalGzipSize));

    }
    chunkIndex++;
    return result;
}

From source file:com.bikfalvi.java.web.WebState.java

/**
 * Creates a GET web request for the current URL.
 * @throws IOException /*from w w w. j a v a  2s.c  o  m*/
 */
public void execute() throws IOException {
    // If the data is not null.
    if (null != this.data) {
        // Write the data.
        this.connection.setDoOutput(true);
        DataOutputStream stream = new DataOutputStream(this.connection.getOutputStream());
        stream.write(this.data);
        stream.flush();
        stream.close();
    }

    // Execute the request and set the response code.
    int code = this.connection.getResponseCode();

    // Set the response data.
    this.setResponse(code, this.connection.getInputStream(), this.connection.getContentEncoding());

    // Complete the request.
    this.complete();
}

From source file:org.openxdata.server.service.impl.FormDownloadServiceTest.java

@Test
@Ignore("throws too many exceptions")
public void testSubmitForms_noSerializer() throws Exception {

    // create the stream
    final PipedOutputStream pout = new PipedOutputStream();
    DataInputStream in = new DataInputStream(new PipedInputStream(pout));
    Thread thread = new Thread(new Runnable() {
        @Override/*from  w w w . j a  v  a2  s  . c o m*/
        public void run() {
            DataOutput output = new DataOutputStream(pout);
            try {
                output.writeByte(1);
                output.writeUTF(XFormsFixture.getSampleFormModelData());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    thread.start();
    DataOutputStream out = new DataOutputStream(new ByteArrayOutputStream());

    // run test
    formDownloadService.submitForms(in, out, null);

    // do checks afterwards
    List<FormDataHeader> formData = studyManagerService.getFormData(12, null, null, null);
    Assert.assertEquals("after submit there is 1 form data", 1, formData.size());
}

From source file:Main.java

public static byte[] convertToB64(int[] a) {
    ByteArrayOutputStream os = new ByteArrayOutputStream(a.length * 4 + 2);
    try {//from w  ww  .  jav  a2 s .c o m
        DataOutputStream dou = new DataOutputStream(os);
        for (int i = 0; i < a.length; i++)
            dou.writeInt(a[i]);
        return encode(os.toByteArray());
    } catch (Exception s) {
        return null;
    }
}

From source file:jdroidremote.ServerFrame.java

public void initEventDriven() {
    jbtRunServer.addActionListener(new ActionListener() {
        @Override//from  w ww .  ja  v  a2 s .  c o m
        public void actionPerformed(ActionEvent e) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        serverSocket = new ServerSocket(5005);
                        System.out.println("Server is running...");
                        clientSocket = serverSocket.accept();
                        dis = new DataInputStream(clientSocket.getInputStream());
                        dos = new DataOutputStream(clientSocket.getOutputStream());
                        System.out.println(
                                "some device connected us from address: " + clientSocket.getInetAddress());

                        thReceiveMouseCoords.start();
                        thStartMonitoring.start();

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

            thReceiveMouseCoords = new Thread(new Runnable() {
                @Override
                public void run() {

                    System.out.println("START RECEIVING COORDS.............");

                    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                    double width = screenSize.getWidth();
                    double height = screenSize.getHeight();

                    while (1 == 1) {
                        try {
                            String receivedStr = dis.readUTF();

                            if (receivedStr.contains("left_click")) {
                                robot.mousePress(KeyEvent.BUTTON1_DOWN_MASK);
                                robot.mouseRelease(KeyEvent.BUTTON1_DOWN_MASK);
                            } else if (receivedStr.contains("right_click")) {
                                robot.mousePress(KeyEvent.BUTTON3_DOWN_MASK);
                                robot.mouseRelease(KeyEvent.BUTTON3_DOWN_MASK);
                            } else if (receivedStr.contains("coords")) {
                                System.out.println(receivedStr);
                                String[] mouseCoords = receivedStr.split(":");

                                int x = (int) (Integer.parseInt(mouseCoords[0]) * width / 100);
                                int y = (int) (Integer.parseInt(mouseCoords[1]) * height / 100);

                                robot.mouseMove(x, y);
                            } else {
                                String[] dataArr = receivedStr.split("-");

                                typeCharacter(dataArr[1]);
                            }
                        } catch (IOException ex) {
                            Logger.getLogger(ServerFrame.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            });
        }
    });
}

From source file:bankingclient.ChonThaoTacFrame.java

public ChonThaoTacFrame(NewOrOldAccFrame acc) {
    initComponents();//from ww w  .  j av  a  2 s. co m
    jTextField1.setText("");

    jLabel4.setVisible(false);
    jComboBox2.setVisible(false);
    jLabel2.setVisible(false);
    jLabel3.setVisible(false);
    jTextField1.setVisible(false);
    jBt_xn1.setVisible(false);
    jBt_xn2.setVisible(false);

    this.accList = null;
    this.cusList = null;
    this.noAcc = acc;
    this.tt = new Thong_Tin_TK(this);
    this.setVisible(false);

    jBt_xn1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (NumberUtils.isNumber(jTextField1.getText()) && (Long.parseLong(jTextField1.getText()) > 0)) {
                long currentMoney = 0;
                try {
                    Socket client = new Socket("113.22.46.207", 6013);

                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(8);
                    dout.writeUTF((String) jComboBox1.getSelectedItem());
                    dout.flush();

                    DataInputStream din = new DataInputStream(client.getInputStream());
                    Scanner lineScanner = new Scanner(din.readUTF());
                    currentMoney = Long.parseLong(lineScanner.nextLine());
                    System.out.println(currentMoney);

                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(rootPane,
                            "Li kt ni mng,bn cn kim tra kt ni");
                }

                if (jCheck_gt.isSelected()) {
                    try {
                        Socket client = new Socket("113.22.46.207", 6013);
                        DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                        dout.writeByte(5);
                        dout.writeUTF((String) jComboBox1.getSelectedItem() + "\n" + jTextField1.getText()
                                + "\n" + (noAcc.getCustomer()));
                        dout.flush();

                    } catch (Exception ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(rootPane, "C Li Kt Ni Xy ra....");
                    }
                    JOptionPane.showMessageDialog(rootPane, "Gi Ti?n Thnh Cng...");
                }

                if (jCheck_rt.isSelected()) {
                    if ((Long.parseLong(jTextField1.getText()) <= currentMoney)) {
                        try {
                            Socket client = new Socket("113.22.46.207", 6013);
                            DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                            dout.writeByte(6);
                            dout.writeUTF((String) jComboBox1.getSelectedItem() + "\n" + jTextField1.getText()
                                    + "\n" + (noAcc.getCustomer()));
                            dout.flush();

                        } catch (Exception ex) {
                            ex.printStackTrace();
                            JOptionPane.showMessageDialog(rootPane, "C Li Kt Ni Xy Ra.....");
                        }
                        JOptionPane.showMessageDialog(rootPane, "Rt Ti?n Thnh Cng ...");
                    } else {
                        System.out.println("Khng  Ti?n Trong ti khon.." + currentMoney);
                        JOptionPane.showMessageDialog(null, "Ti Khon Khng ? ? Rt ...");
                    }
                }

                noAcc.setVisible(true);
                ChonThaoTacFrame.this.setVisible(false);
            } else {
                JOptionPane.showMessageDialog(rootPane,
                        "Cn Nhp Li S Ti?n Cn Gi Hoc Rt..");
            }

        }
    });

    jBt_tt.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            tt.setTk((String) jComboBox1.getSelectedItem());
            tt.hienTenTk();
            long currentMoney = 0;
            try {
                Socket client = new Socket("113.22.46.207", 6013);

                DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                dout.writeByte(8);
                dout.writeUTF((String) jComboBox1.getSelectedItem());
                dout.flush();

                DataInputStream din = new DataInputStream(client.getInputStream());
                Scanner lineScanner = new Scanner(din.readUTF());
                currentMoney = Long.parseLong(lineScanner.nextLine());
                //                    System.out.println(currentMoney);

            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(rootPane,
                        "Li kt ni mng,bn cn kim tra kt ni");
            }
            tt.hienSoDu(((Long) currentMoney).toString());
            tt.setVisible(true);
            try {
                Socket client = new Socket("113.22.46.207", 6013);

                DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                dout.writeByte(10);
                dout.writeUTF((String) jComboBox1.getSelectedItem());
                dout.flush();

                DataInputStream din = new DataInputStream(client.getInputStream());
                Scanner cusScanner = new Scanner(din.readUTF());
                while (cusScanner.hasNextLine()) {
                    tt.addCus(cusScanner.nextLine());
                }
            } catch (Exception ee) {
                ee.printStackTrace();
            }
            tt.hienChuTaiKhoan();
            try {
                Socket client = new Socket("113.22.46.207", 6013);
                DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                dout.writeByte(12);
                dout.writeUTF((String) jComboBox1.getSelectedItem());
                dout.flush();

                DataInputStream din = new DataInputStream(client.getInputStream());
                Scanner dateScanner = new Scanner(din.readUTF());
                int day = Integer.parseInt(dateScanner.nextLine());
                int month = Integer.parseInt(dateScanner.nextLine());
                int year = Integer.parseInt(dateScanner.nextLine());
                String date = (day + "-" + month + "-" + year);
                tt.hienNgayLapTaiKhoan(date);
                while (dateScanner.hasNextLine()) {
                    //                        System.out.println("aaa");
                    tt.addGiaoDich(dateScanner.nextLine());
                }
                tt.hienGiaoDich();
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            ChonThaoTacFrame.this.setVisible(false);
        }
    });

    jBt_xn2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (jCheck_tctk.isSelected()) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(7);
                    dout.writeUTF((String) jComboBox1.getSelectedItem() + "\n"
                            + (String) jComboBox2.getSelectedItem());
                    dout.flush();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(rootPane,
                            "C Li Kt Ni Xy Ra\n Thm Ch Tht Bi...");
                }
                JOptionPane.showMessageDialog(rootPane, "Thm Ch Ti Khon Thnh Cng..");
            } else {
                System.out.println("nothing to do...");
            }
        }
    });

    jBt_xtk.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Socket client = new Socket("113.22.46.207", 6013);
                DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                dout.writeByte(11);
                String sent = (String) (jComboBox1.getSelectedItem()) + "\n" + noAcc.getCustomer();
                dout.writeUTF(sent);
                dout.flush();
                DataInputStream din = new DataInputStream(client.getInputStream());
                byte check = din.readByte();
                if (check == 1) {
                    JOptionPane.showMessageDialog(rootPane, "xoa tai khoan thanh cong");
                } else {
                    JOptionPane.showMessageDialog(rootPane,
                            "<html>xoa tai khoan <b>khong</b> thanh cong <br> chi chu chinh moi co the xoa tai khoan</html>");
                }

            } catch (Exception ee) {
                ee.printStackTrace();
                JOptionPane.showMessageDialog(rootPane, "Li Kt Ni ,Vui Lng Kim Tra Li..");
            }
        }
    });

    /*dont touch*/
    jBt_ql.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            noAcc.setVisible(true);
            ChonThaoTacFrame.this.setVisible(false);
        }
    });
    /*dont touch*/

    jComboBox1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }
    });

    jComboBox2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }
    });

    /*dont touch jcheckbox*/
    jCheck_tctk.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (jCheck_tctk.isSelected()) {
                jLabel4.setVisible(true);
                jComboBox2.setVisible(true);
                jBt_xn2.setVisible(true);
            } else {
                jLabel4.setVisible(false);
                jComboBox2.setVisible(false);
                jBt_xn2.setVisible(false);
            }
        }
    });
    jCheck_gt.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (jCheck_gt.isSelected()) {
                if (jCheck_rt.isSelected()) {
                    jCheck_rt.setSelected(false);
                }
                jLabel2.setVisible(true);
                jLabel3.setVisible(true);
                jTextField1.setVisible(true);
                jBt_xn1.setVisible(true);
            } else {
                jLabel2.setVisible(false);
                jLabel3.setVisible(false);
                jTextField1.setVisible(false);
                jBt_xn1.setVisible(false);
            }
        }
    });
    jCheck_rt.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (jCheck_rt.isSelected()) {
                if (jCheck_gt.isSelected()) {
                    jCheck_gt.setSelected(false);
                }
                jLabel2.setVisible(true);
                jLabel3.setVisible(true);
                jTextField1.setVisible(true);
                jBt_xn1.setVisible(true);
            } else {
                jLabel2.setVisible(false);
                jLabel3.setVisible(false);
                jTextField1.setVisible(false);
                jBt_xn1.setVisible(false);
            }
        }
    });
    /*dont touch jcheckbox*/
}

From source file:fyp.project.uploadFile.UploadFile.java

public int upLoad2Server(String sourceFileUri) {
    String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp";
    // String [] string = sourceFileUri;
    String fileName = sourceFileUri;
    int serverResponseCode = 0;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;//from   w w w . j  a  v  a2  s.  c om
    DataInputStream inStream = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    String responseFromServer = "";

    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {

        return 0;
    }
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("file", fileName);
        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
                + fileName.substring(fileName.lastIndexOf("/")) + "\"" + lineEnd);

        m_log.log(Level.INFO, "Content-Disposition: form-data; name=\"file\";filename=\"{0}\"{1}",
                new Object[] { fileName.substring(fileName.lastIndexOf("/")), lineEnd });
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size

        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        m_log.log(Level.INFO, "Upload file to server" + "HTTP Response is : {0}: {1}",
                new Object[] { serverResponseMessage, serverResponseCode });

        // close streams
        m_log.log(Level.INFO, "Upload file to server{0} File is written", fileName);
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        m_log.log(Level.ALL, "Upload file to server" + "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        e.printStackTrace();
    }
    //this block will give the response of upload link

    return serverResponseCode; // like 200 (Ok)

}

From source file:com.ryan.ryanreader.cache.PersistentCookieStore.java

public synchronized byte[] toByteArray() {

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final DataOutputStream dos = new DataOutputStream(baos);

    try {//www . ja v a  2  s. c o m

        dos.writeInt(cookies.size());

        for (final Cookie cookie : cookies) {

            dos.writeUTF(cookie.getName());
            dos.writeUTF(cookie.getValue());
            dos.writeUTF(cookie.getDomain());
            dos.writeUTF(cookie.getPath());
            dos.writeBoolean(cookie.isSecure());
        }

        dos.flush();
        dos.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return baos.toByteArray();
}

From source file:com.igormaznitsa.jhexed.swing.editor.filecontainer.FileContainer.java

public void write(final OutputStream out) throws IOException {
    final DataOutputStream dout = out instanceof DataOutputStream ? (DataOutputStream) out
            : new DataOutputStream(out);
    dout.writeInt(MAGIC);/* w  ww  . j  ava2  s. co m*/
    dout.writeShort(FORMAT_VERSION);

    dout.writeShort(this.sections.size());
    for (final FileContainerSection s : this.sections) {
        s.write(dout);
    }
    dout.writeInt(MAGIC);

    dout.flush();
}

From source file:br.org.indt.ndg.servlets.PostResultsOpenRosa.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    m_openRosaBD.setPortAndAddress(SystemProperties.getServerAddress());

    InputStreamReader inputStreamReader = new InputStreamReader(request.getInputStream(), "UTF-8");
    boolean success = m_openRosaBD.parseAndPersistResult(inputStreamReader, request.getContentType());

    DataOutputStream dataOutputStream = new DataOutputStream(response.getOutputStream());
    if (success) {
        dataOutputStream.writeInt(SUCCESS);
        log.info("Successfully processed result stream from " + request.getRemoteAddr());
    } else {//w w  w  .ja  v  a  2 s  . co m
        dataOutputStream.writeInt(FAILURE);
        log.error("Failed processing result stream from " + request.getRemoteAddr());
    }
    dataOutputStream.close();
}