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.android.dialer.omni.PlaceUtil.java

/**
 * Executes a post request and return a JSON object
 * @param url The API URL/*www  .  ja v  a 2s  .  c o m*/
 * @param data The data to post in POST field
 * @return the JSON object
 * @throws IOException
 * @throws JSONException
 */
public static JSONObject postJsonRequest(String url, String postData) throws IOException, JSONException {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("POST");

    if (DEBUG)
        Log.d(TAG, "Posting: " + postData + " to " + url);

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(postData);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    JSONObject json = new JSONObject(response.toString());
    return json;
}

From source file:com.microsoft.office365.connectmicrosoftgraph.ConnectUnitTests.java

@BeforeClass
public static void getAccessTokenUsingPasswordGrant()
        throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, JSONException {
    URL url = new URL(TOKEN_ENDPOINT);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

    String urlParameters = String.format(
            "grant_type=%1$s&resource=%2$s&client_id=%3$s&username=%4$s&password=%5$s", GRANT_TYPE,
            URLEncoder.encode(Constants.MICROSOFT_GRAPH_API_ENDPOINT_RESOURCE_ID, "UTF-8"), clientId, username,
            password);//  w  w w  . j av  a  2 s  . c  om

    connection.setRequestMethod(REQUEST_METHOD);
    connection.setRequestProperty("Content-Type", CONTENT_TYPE);
    connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes("UTF-8").length));

    connection.setDoOutput(true);
    DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
    dataOutputStream.writeBytes(urlParameters);
    dataOutputStream.flush();
    dataOutputStream.close();

    connection.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    JsonParser jsonParser = new JsonParser();
    JsonObject grantResponse = (JsonObject) jsonParser.parse(response.toString());
    accessToken = grantResponse.get("access_token").getAsString();
}

From source file:com.pubkit.network.PubKitNetwork.java

public static JSONObject sendPost(String apiKey, JSONObject jsonObject) {
    URL url;//from ww  w .j a v a2  s. c  om
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(PUBKIT_API_URL);
        String encodedData = jsonObject.toString();
        byte[] postDataBytes = jsonObject.toString().getBytes("UTF-8");

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Length", "" + String.valueOf(postDataBytes.length));
        connection.setRequestProperty("api_key", apiKey);

        connection.setUseCaches(false);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(encodedData);//set data
        wr.flush();

        //Get Response
        InputStream inputStream = connection.getErrorStream(); //first check for error.
        if (inputStream == null) {
            inputStream = connection.getInputStream();
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        StringBuilder response = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        wr.close();
        rd.close();

        String responseString = response.toString();
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return new JSONObject("{'error':'" + responseString + "'}");
        } else {
            try {
                return new JSONObject(responseString);
            } catch (JSONException e) {
                Log.e("PUBKIT", "Error parsing data", e);
            }
        }
    } catch (Exception e) {
        Log.e("PUBKIT", "Network exception:", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

From source file:cc.aileron.commons.resource.ResourceImpl.java

/**
 * @return byte[]/*from w w w.  j  av a2  s . c  o  m*/
 * @throws IOException
 */
@Override
public byte[] toBytes() throws IOException {
    final BufferedInputStream in = new BufferedInputStream(content.getInputStream());
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final DataOutputStream os = new DataOutputStream(baos);

    byte[] buffer = new byte[8192];
    while (in.read(buffer) != -1) {
        os.write(buffer);
        buffer = new byte[8192];
    }

    return baos.toByteArray();
}

From source file:com.px100systems.util.serialization.DataStream.java

public DataStream() {
    os = new ByteArrayOutputStream(1024);
    dos = new DataOutputStream(os);
}

From source file:com.gagein.crawler.FileDownLoader.java

/**
 * ? filePath ???//  w w  w  .  ja  v a 2  s  .c om
 */
private void saveToLocal(byte[] data, String filePath) {
    try {
        System.out.println("========SaveToLocal========filePath===" + filePath);
        DataOutputStream out = new DataOutputStream(new FileOutputStream(new File(filePath)));
        for (int i = 0; i < data.length; i++)
            out.write(data[i]);
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.snaker.ocr.TesseractOCR.java

@Override
public String recognize(byte[] image) throws OCRException {
    if (tessExecutable == null) {
        tessExecutable = getDefaultTessExecutable();
    }/*from  ww w.j  a v a2s.  c om*/

    File source = null;
    File dest = null;
    try {
        String prefix = System.nanoTime() + "";
        source = File.createTempFile(prefix, ".jpg");
        DataOutputStream dos = new DataOutputStream(new FileOutputStream(source));
        dos.write(image);
        dos.flush();
        dos.close();
        String sourceFileName = source.getAbsolutePath();
        Process p = Runtime.getRuntime().exec(String.format("%s %s %s -l eng nobatch digits", tessExecutable,
                sourceFileName, sourceFileName));
        String destFileName = sourceFileName + ".txt";
        dest = new File(destFileName);
        int result = p.waitFor();
        if (result == 0) {
            BufferedReader in = new BufferedReader(new FileReader(dest));
            StringBuilder sb = new StringBuilder();
            String str;
            while ((str = in.readLine()) != null) {
                sb.append(str).append("\n");
            }
            in.close();
            return sb.toString().trim();
        } else {
            String msg;
            switch (result) {
            case 1:
                msg = "Errors accessing files. There may be spaces in your image's filename.";
                break;
            case 29:
                msg = "Cannot recognize the image or its selected region.";
                break;
            case 31:
                msg = "Unsupported image format.";
                break;
            default:
                msg = "Errors occurred.";
            }
            throw new OCRException(msg);
        }
    } catch (IOException e) {
        throw new OCRException("recognize failed", e);
    } catch (InterruptedException e) {
        logger.error("interrupted", e);
    } finally {
        if (source != null) {
            source.delete();
        }
        if (dest != null) {
            dest.delete();
        }
    }
    return null;
}

From source file:io.v.positioning.gae.ServletPostAsyncTask.java

@Override
protected String doInBackground(Context... params) {
    mContext = params[0];/*  ww  w .  j  a  va2  s  .  c o m*/
    DataOutputStream os = null;
    InputStream is = null;
    try {
        URLConnection conn = mUrl.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.connect();
        os = new DataOutputStream(conn.getOutputStream());
        os.write(mData.toString().getBytes("UTF-8"));
        is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        return br.readLine();
    } catch (IOException e) {
        return "IOException while contacting GEA: " + e.getMessage();
    } catch (Exception e) {
        return "Exception while contacting GEA: " + e.getLocalizedMessage();
    } finally {
        if (os != null)
            try {
                os.close();
            } catch (IOException e) {
                return "IOException closing os: " + e.getMessage();
            }
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                return "IOException closing is: " + e.getMessage();
            }
    }
}

From source file:gaffer.serialisation.implementation.raw.CompactRawLongSerialiserTest.java

private static void test(final long value) throws SerialisationException {
    final byte[] b = SERIALISER.serialise(value);
    final Object o = SERIALISER.deserialise(b);
    assertEquals(Long.class, o.getClass());
    assertEquals(value, o);//from w w  w.j av  a2 s . c o m
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    CompactRawSerialisationUtils.write(value, new DataOutputStream(baos));
    final long result = CompactRawSerialisationUtils
            .read(new DataInputStream(new ByteArrayInputStream(baos.toByteArray())));
    assertEquals(result, value);
}

From source file:bankingclient.DNFrame.java

public DNFrame(MainFrame vmain) {

    initComponents();/* w w  w.  j  a v a  2  s .co m*/

    this.jTextField1.setText("");
    this.jTextField2.setText("");
    this.jTextField_cmt.setText("");
    this.jTextField_sdt.setText("");

    this.main = vmain;
    noAcc = new NewOrOldAccFrame(this);
    this.setVisible(false);
    jL_sdt.setVisible(false);
    jL_cmtnd.setVisible(false);
    jTextField_cmt.setVisible(false);
    jTextField_sdt.setVisible(false);

    jBt_dn.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (!jCheck_qmk.isSelected()) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(2);
                    dout.writeUTF(jTextField1.getText() + "\n" + jTextField2.getText());
                    dout.flush();
                    while (true) {
                        break;
                    }
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        noAcc.setVisible(true);
                        DNFrame.this.setVisible(false);
                        noAcc.setMainCustomer(jTextField1.getText());

                    } else {
                        JOptionPane.showMessageDialog(new JFrame(),
                                "Tn ?ang Nhp Khng Tn Ti, hoac mat khau sai");
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(rootPane, "C Li Kt Ni Mng....");
                }
            } else if ((!jTextField_cmt.getText().equals("")) && (!jTextField_sdt.getText().equals(""))
                    && (NumberUtils.isNumber(jTextField_cmt.getText()))
                    && (NumberUtils.isNumber(jTextField_sdt.getText()))) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(9);
                    dout.writeUTF(jTextField1.getText() + "\n" + jTextField_sdt.getText() + "\n"
                            + jTextField_cmt.getText());
                    dout.flush();
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        noAcc.setVisible(true);
                        DNFrame.this.setVisible(false);
                        noAcc.setMainCustomer(jTextField1.getText());
                    } else {
                        JOptionPane.showMessageDialog(new JFrame(), "Khong dang nhap duoc, thong tin sai");
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else {
                JOptionPane.showMessageDialog(new JFrame(), "Can dien day du thong tin va dung mau");
            }
        }
    });
    jBt_ql.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            main.setVisible(true);
            DNFrame.this.setVisible(false);
        }
    });
    jCheck_qmk.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (jCheck_qmk.isSelected()) {
                jL_sdt.setVisible(true);
                jL_cmtnd.setVisible(true);
                jTextField_cmt.setVisible(true);
                jTextField_sdt.setVisible(true);
            } else {
                jL_sdt.setVisible(false);
                jL_cmtnd.setVisible(false);
                jTextField_cmt.setVisible(false);
                jTextField_sdt.setVisible(false);
            }
        }
    });
}