Example usage for java.io DataOutputStream write

List of usage examples for java.io DataOutputStream write

Introduction

In this page you can find the example usage for java.io DataOutputStream write.

Prototype

public synchronized void write(int b) throws IOException 

Source Link

Document

Writes the specified byte (the low eight bits of the argument b) to the underlying output stream.

Usage

From source file:org.apache.cassandra.service.StorageProxy.java

public static void addHintHeader(Message message, InetAddress target) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    byte[] previousHints = message.getHeader(RowMutation.HINT);
    if (previousHints != null) {
        dos.write(previousHints);
    }/*from   w ww. j  a  v  a2  s.co m*/
    ByteBufferUtil.writeWithShortLength(ByteBufferUtil.bytes(target.getHostAddress()), dos);
    message.setHeader(RowMutation.HINT, bos.toByteArray());
}

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 av  a2  s  . c  o  m*/

    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:org.apache.hadoop.yarn.client.api.impl.TestSharedCacheClientImpl.java

private Path makeFile(String filename) throws Exception {
    Path file = new Path(TEST_ROOT_DIR, filename);
    DataOutputStream out = null;
    try {/* w  w  w.j  a  va 2 s  . com*/
        out = localFs.create(file);
        out.write(input.getBytes("UTF-8"));
    } finally {
        if (out != null) {
            out.close();
        }
    }
    return file;
}

From source file:org.brickred.socialauth.util.HttpUtil.java

/**
 * //w  w  w.  j a v  a  2 s. c  o  m
 * @param urlStr
 *            the URL String
 * @param requestMethod
 *            Method type
 * @param params
 *            Parameters to pass in request
 * @param header
 *            Header parameters
 * @param inputStream
 *            Input stream of image
 * @param fileName
 *            Image file name
 * @param fileParamName
 *            Image Filename parameter. It requires in some provider.
 * @return Response object
 * @throws SocialAuthException
 */
public static Response doHttpRequest(final String urlStr, final String requestMethod,
        final Map<String, String> params, final Map<String, String> header, final InputStream inputStream,
        final String fileName, final String fileParamName) throws SocialAuthException {
    HttpURLConnection conn;
    try {

        URL url = new URL(urlStr);
        if (proxyObj != null) {
            conn = (HttpURLConnection) url.openConnection(proxyObj);
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }

        if (requestMethod.equalsIgnoreCase(MethodType.POST.toString())
                || requestMethod.equalsIgnoreCase(MethodType.PUT.toString())) {
            conn.setDoOutput(true);
        }

        conn.setDoInput(true);

        conn.setInstanceFollowRedirects(true);
        if (timeoutValue > 0) {
            LOG.debug("Setting connection timeout : " + timeoutValue);
            conn.setConnectTimeout(timeoutValue);
        }
        if (requestMethod != null) {
            conn.setRequestMethod(requestMethod);
        }
        if (header != null) {
            for (String key : header.keySet()) {
                conn.setRequestProperty(key, header.get(key));
            }
        }

        // If use POST or PUT must use this
        OutputStream os = null;
        if (inputStream != null) {
            if (requestMethod != null && !MethodType.GET.toString().equals(requestMethod)
                    && !MethodType.DELETE.toString().equals(requestMethod)) {
                LOG.debug(requestMethod + " request");
                String boundary = "----Socialauth-posting" + System.currentTimeMillis();
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
                boundary = "--" + boundary;

                os = conn.getOutputStream();
                DataOutputStream out = new DataOutputStream(os);
                write(out, boundary + "\r\n");

                if (fileParamName != null) {
                    write(out, "Content-Disposition: form-data; name=\"" + fileParamName + "\"; filename=\""
                            + fileName + "\"\r\n");
                } else {
                    write(out, "Content-Disposition: form-data;  filename=\"" + fileName + "\"\r\n");
                }
                write(out, "Content-Type: " + "multipart/form-data" + "\r\n\r\n");
                int b;
                while ((b = inputStream.read()) != -1) {
                    out.write(b);
                }
                // out.write(imageFile);
                write(out, "\r\n");

                Iterator<Map.Entry<String, String>> entries = params.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry<String, String> entry = entries.next();
                    write(out, boundary + "\r\n");
                    write(out, "Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
                    // write(out,
                    // "Content-Type: text/plain;charset=UTF-8 \r\n\r\n");
                    LOG.debug(entry.getValue());
                    out.write(entry.getValue().getBytes("UTF-8"));
                    write(out, "\r\n");
                }

                write(out, boundary + "--\r\n");
                write(out, "\r\n");
            }
        }
        conn.connect();
    } catch (Exception e) {
        throw new SocialAuthException(e);
    }
    return new Response(conn);

}

From source file:org.hydracache.protocol.data.marshaller.DataMessageMarshaller.java

@Override
public void writeObject(DataMessage msg, DataOutputStream dataOut) throws IOException {
    Validate.notNull(msg.getBlob(), "Data message is empty");

    versionMarshaller.writeObject(msg.getVersion(), dataOut);

    dataOut.write(msg.getBlob());
}

From source file:com.facebook.infrastructure.db.ReadResponse.java

public void serialize(ReadResponse rm, DataOutputStream dos) throws IOException {
    dos.writeUTF(rm.table());/*from   w w w .  j  a va 2  s  .  c o  m*/
    dos.writeInt(rm.digest().length);
    dos.write(rm.digest());
    dos.writeBoolean(rm.isDigestQuery());

    if (!rm.isDigestQuery() && rm.row() != null) {
        Row.serializer().serialize(rm.row(), dos);
    }
}

From source file:org.openbaton.nfvo.core.api.KeyManagement.java

private String encodePublicKey(PublicKey publicKey, String user) throws IOException {
    String publicKeyEncoded;//from  ww  w  .j  a v  a2 s  . com
    RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
    ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(byteOs);
    dos.writeInt("ssh-rsa".getBytes().length);
    dos.write("ssh-rsa".getBytes());
    dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length);
    dos.write(rsaPublicKey.getPublicExponent().toByteArray());
    dos.writeInt(rsaPublicKey.getModulus().toByteArray().length);
    dos.write(rsaPublicKey.getModulus().toByteArray());
    publicKeyEncoded = new String(encodeBase64(byteOs.toByteArray()));
    return "ssh-rsa " + publicKeyEncoded + " " + user;
}

From source file:mitm.common.security.password.PBEncryptionParameters.java

/**
 * Returns the encoded form of PBEncryptionParameters.
 *//*from   w  w w . j  av  a2s  .  co m*/
public byte[] getEncoded() throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    DataOutputStream out = new DataOutputStream(bos);

    out.writeLong(serialVersionUID);

    out.writeInt(salt.length);
    out.write(salt);

    out.writeInt(iterationCount);

    out.writeInt(encryptedData.length);
    out.write(encryptedData);

    return bos.toByteArray();
}

From source file:com.microsoft.speech.tts.Authentication.java

private void HttpPost(String AccessTokenUri, String apiKey) {
    InputStream inSt = null;/*from w  ww  . j  a  v a2s  .c  om*/
    HttpsURLConnection webRequest = null;

    this.accessToken = null;
    //Prepare OAuth request
    try {
        URL url = new URL(AccessTokenUri);
        webRequest = (HttpsURLConnection) url.openConnection();
        webRequest.setDoInput(true);
        webRequest.setDoOutput(true);
        webRequest.setConnectTimeout(5000);
        webRequest.setReadTimeout(5000);
        webRequest.setRequestProperty("Ocp-Apim-Subscription-Key", apiKey);
        webRequest.setRequestMethod("POST");

        String request = "";
        byte[] bytes = request.getBytes();
        webRequest.setRequestProperty("content-length", String.valueOf(bytes.length));
        webRequest.connect();

        DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream());
        dop.write(bytes);
        dop.flush();
        dop.close();

        inSt = webRequest.getInputStream();
        InputStreamReader in = new InputStreamReader(inSt);
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }

        bufferedReader.close();
        in.close();
        inSt.close();
        webRequest.disconnect();

        this.accessToken = strBuffer.toString();

    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}

From source file:com.nicolacimmino.expensestracker.tracker.expenses_api.ExpensesApiRequest.java

public boolean performRequest() {

    jsonResponseArray = null;//  ww w.  jav  a2s .c o m
    jsonResponseObject = null;

    HttpURLConnection connection = null;

    try {

        // Get the request JSON document as U*TF-8 encoded bytes, suitable for HTTP.
        mRequestData = ((mRequestData != null) ? mRequestData : new JSONObject());
        byte[] postDataBytes = mRequestData.toString(0).getBytes("UTF-8");

        URL url = new URL(mUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(mRequestMethod == "GET" ? false : true); // No body data for GET
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod(mRequestMethod);
        connection.setUseCaches(false);

        // For all methods except GET we need to include data in the body.
        if (mRequestMethod != "GET") {
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(postDataBytes.length));

            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.write(postDataBytes);
            wr.flush();
            wr.close();
        }

        if (connection.getResponseCode() == 200) {
            InputStreamReader in = new InputStreamReader((InputStream) connection.getContent());
            BufferedReader buff = new BufferedReader(in);
            String line = buff.readLine().toString();
            buff.close();
            Object json = new JSONTokener(line).nextValue();
            if (json.getClass() == JSONObject.class) {
                jsonResponseObject = (JSONObject) json;
            } else if (json.getClass() == JSONArray.class) {
                jsonResponseArray = (JSONArray) json;
            } // else members will be left to null indicating no valid response.
            return true;
        }

    } catch (MalformedURLException e) {
        Log.e(TAG, e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return false;
}