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:bankingclient.TaoTaiKhoanFrame.java

public TaoTaiKhoanFrame(NewOrOldAccFrame acc) {

    initComponents();/* www.j ava 2  s.  c  om*/
    this.jText_ten_tk.setText("");
    this.jText_sd.setText("");

    this.noAcc = acc;
    this.mainCustomerName = null;
    this.setVisible(false);

    jBt_ht.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (NumberUtils.isNumber(jText_sd.getText()) && (Long.parseLong(jText_sd.getText()) > 0)) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(3);
                    dout.writeUTF(jText_ten_tk.getText() + "\n" + mainCustomerName + "\n" + jText_sd.getText());
                    dout.flush();
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        JOptionPane.showMessageDialog(rootPane, "da tao tai khoan thanh cong");
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "tao tai khoan khong thanh cong");
                    }
                    client.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                noAcc.setVisible(true);
                TaoTaiKhoanFrame.this.setVisible(false);
            } else {
                JOptionPane.showMessageDialog(rootPane, "Can nhap lai so tien gui");
            }

        }
    });
    jBt_ql.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            noAcc.setVisible(true);
            TaoTaiKhoanFrame.this.setVisible(false);

        }
    });
}

From source file:ict.servlet.UploadToServer.java

public static 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;/*  www  .ja v  a2  s . co  m*/
    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("uploaded_file", fileName);
        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\""
                + 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.info("Upload file to server" + "HTTP Response is : " + serverResponseMessage + ": "
                + serverResponseCode);
        // close streams
        m_log.info("Upload file to server" + fileName + " File is written");
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException ex) {
        //         ex.printStackTrace();
        m_log.error("Upload file to server" + "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        //      e.printStackTrace();
    }
    //this block will give the response of upload link
    /* try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = rd.readLine()) != null) {
      m_log.info("Huzza" + "RES Message: " + line);
      }
      rd.close();
      } catch (IOException ioex) {
      m_log.error("Huzza" + "error: " + ioex.getMessage(), ioex);
      }*/
    return serverResponseCode; // like 200 (Ok)

}

From source file:delete.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w  w  w  .ja va  2 s  . c o  m
 *
 * @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 {
    response.setContentType("text/html;charset=UTF-8");

    Socket s = new Socket("localhost", 9999);

    DataInputStream in = new DataInputStream(s.getInputStream());
    DataOutputStream outD = new DataOutputStream(s.getOutputStream());

    outD.writeUTF(request.getParameter("employee_id"));

    in.readUTF();

    s.close();

    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        out.println("Deleted");
    }
}

From source file:com.tc.simple.apn.factories.PushByteFactory.java

@Override
public byte[] buildPushBytes(int id, Payload payload) {
    byte[] byteMe = null;
    ByteArrayOutputStream baos = null;
    DataOutputStream dos = null;/*w ww  .  j ava 2s.c o  m*/

    try {
        baos = new ByteArrayOutputStream();

        dos = new DataOutputStream(baos);

        int expiry = 0; // (int) ((System.currentTimeMillis () / 1000L) + 7200);

        char[] cars = payload.getToken().trim().toCharArray();

        byte[] tokenBytes = Hex.decodeHex(cars);

        //command
        dos.writeByte(1);

        //id
        dos.writeInt(id);

        //expiry
        dos.writeInt(expiry);

        //token length.
        dos.writeShort(tokenBytes.length);

        //token
        dos.write(tokenBytes);

        //payload length
        dos.writeShort(payload.getJson().length());

        logger.log(Level.FINE, payload.getJson());

        //payload.
        dos.write(payload.getJson().getBytes());

        byteMe = baos.toByteArray();

    } catch (Exception e) {
        logger.log(Level.SEVERE, null, e);

    } finally {
        CloseUtils.close(dos);
        CloseUtils.close(baos);
    }

    return byteMe;

}

From source file:net.indialend.web.component.GCMComponent.java

public void setMessage(User user, String deactivate) {

    try {//from www.  j ava 2 s.c  o m
        URL obj = new URL(serviceUrl);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "key=" + API_KEY);

        String urlParameters = "{" + "   \"data\": {" + "     \"deactivate\": \"" + deactivate + "\"," + "   },"
                + "   \"to\": \"" + user.getGcmToken() + "\"" + " }";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.write(urlParameters.getBytes("UTF-8"));
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + serviceUrl);
        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());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.netflix.zeno.hash.HashOrderDependent.java

public HashOrderDependent() {
    try {/*from   w ww .j ava 2 s  .com*/
        digest = MessageDigest.getInstance("MD5");
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    digestOutputStream = new DigestOutputStream(NullOutputStream.NULL_OUTPUT_STREAM, digest);
    dataOutputStream = new DataOutputStream(digestOutputStream);
}

From source file:com.offbynull.peernetic.debug.visualizer.XStreamRecorder.java

/**
 * Constructs a {@link XStreamRecorder} object.
 * @param os output stream/*ww w.ja v a 2s .  co m*/
 * @throws NullPointerException if any arguments are {@code null}
 */
public XStreamRecorder(OutputStream os) {
    Validate.notNull(os);

    this.os = new DataOutputStream(os);
    xstream = new XStream();
}

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

/**
 * (non-Javadoc)// ww w .ja  v a2  s .  c o m
 * 
 * @see org.jmangos.sniffer.handler.PacketLogHandler#init()
 */
@Override
public void init() {
    final String date = String.format("%X", System.currentTimeMillis());
    try {
        this.fous = new DataOutputStream(new FileOutputStream(new File(this.build + "_" + date + ".dmp")));
        setInit(true);
    } catch (final FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:software.uncharted.util.HTTPUtil.java

public static String post(String urlToRead, String postData) {
    URL url;//ww  w.j  a  v a2  s .  com
    HttpURLConnection conn;
    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/json");

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        wr.close();

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[16384];
        InputStream is = conn.getInputStream();
        while ((nRead = is.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        buffer.flush();
        return buffer.toString();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Failed to read URL: " + urlToRead + " <" + e.getMessage() + ">");
    }
    return null;
}

From source file:ml.shifu.shifu.core.dtrain.dt.BinaryDTSerializer.java

public static void save(ModelConfig modelConfig, List<ColumnConfig> columnConfigList,
        List<List<TreeNode>> baggingTrees, String loss, int inputCount, OutputStream output)
        throws IOException {
    DataOutputStream fos = null;/* www. j a v a 2 s .  co  m*/

    try {
        fos = new DataOutputStream(new GZIPOutputStream(output));
        // version
        fos.writeInt(CommonConstants.TREE_FORMAT_VERSION);
        fos.writeUTF(modelConfig.getAlgorithm());
        fos.writeUTF(loss);
        fos.writeBoolean(modelConfig.isClassification());
        fos.writeBoolean(modelConfig.getTrain().isOneVsAll());
        fos.writeInt(inputCount);

        Map<Integer, String> columnIndexNameMapping = new HashMap<Integer, String>();
        Map<Integer, List<String>> columnIndexCategoricalListMapping = new HashMap<Integer, List<String>>();
        Map<Integer, Double> numericalMeanMapping = new HashMap<Integer, Double>();
        for (ColumnConfig columnConfig : columnConfigList) {
            if (columnConfig.isFinalSelect()) {
                columnIndexNameMapping.put(columnConfig.getColumnNum(), columnConfig.getColumnName());
            }
            if (columnConfig.isCategorical() && CollectionUtils.isNotEmpty(columnConfig.getBinCategory())) {
                columnIndexCategoricalListMapping.put(columnConfig.getColumnNum(),
                        columnConfig.getBinCategory());
            }

            if (columnConfig.isNumerical() && columnConfig.getMean() != null) {
                numericalMeanMapping.put(columnConfig.getColumnNum(), columnConfig.getMean());
            }
        }

        if (columnIndexNameMapping.size() == 0) {
            boolean hasCandidates = CommonUtils.hasCandidateColumns(columnConfigList);
            for (ColumnConfig columnConfig : columnConfigList) {
                if (CommonUtils.isGoodCandidate(columnConfig, hasCandidates)) {
                    columnIndexNameMapping.put(columnConfig.getColumnNum(), columnConfig.getColumnName());
                }
            }
        }

        // serialize numericalMeanMapping
        fos.writeInt(numericalMeanMapping.size());
        for (Entry<Integer, Double> entry : numericalMeanMapping.entrySet()) {
            fos.writeInt(entry.getKey());
            // for some feature, it is null mean value, it is not selected, just set to 0d to avoid NPE
            fos.writeDouble(entry.getValue() == null ? 0d : entry.getValue());
        }
        // serialize columnIndexNameMapping
        fos.writeInt(columnIndexNameMapping.size());
        for (Entry<Integer, String> entry : columnIndexNameMapping.entrySet()) {
            fos.writeInt(entry.getKey());
            fos.writeUTF(entry.getValue());
        }
        // serialize columnIndexCategoricalListMapping
        fos.writeInt(columnIndexCategoricalListMapping.size());
        for (Entry<Integer, List<String>> entry : columnIndexCategoricalListMapping.entrySet()) {
            List<String> categories = entry.getValue();
            if (categories != null) {
                fos.writeInt(entry.getKey());
                fos.writeInt(categories.size());
                for (String category : categories) {
                    // There is 16k limitation when using writeUTF() function.
                    // if the category value is larger than 10k, write a marker -1 and write bytes instead of
                    // writeUTF;
                    // in read part logic should be changed also to readByte not readUTF according to the marker
                    if (category.length() < Constants.MAX_CATEGORICAL_VAL_LEN) {
                        fos.writeUTF(category);
                    } else {
                        fos.writeShort(UTF_BYTES_MARKER); // marker here
                        byte[] bytes = category.getBytes("UTF-8");
                        fos.writeInt(bytes.length);
                        for (int i = 0; i < bytes.length; i++) {
                            fos.writeByte(bytes[i]);
                        }
                    }
                }
            }
        }

        Map<Integer, Integer> columnMapping = getColumnMapping(columnConfigList);
        fos.writeInt(columnMapping.size());
        for (Entry<Integer, Integer> entry : columnMapping.entrySet()) {
            fos.writeInt(entry.getKey());
            fos.writeInt(entry.getValue());
        }

        // after model version 4 (>=4), IndependentTreeModel support bagging, here write a default RF/GBT size 1
        fos.writeInt(baggingTrees.size());
        for (int i = 0; i < baggingTrees.size(); i++) {
            List<TreeNode> trees = baggingTrees.get(i);
            int treeLength = trees.size();
            fos.writeInt(treeLength);
            for (TreeNode treeNode : trees) {
                treeNode.write(fos);
            }
        }
    } catch (IOException e) {
        LOG.error("Error in writing output.", e);
    } finally {
        IOUtils.closeStream(fos);
    }
}