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:com.flozano.socialauth.util.HttpUtil.java

/**
 *
 * @param urlStr//from ww  w.ja va 2s .co m
 *            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, Optional<ConnectionSettings> connectionSettings)
        throws SocialAuthException {
    HttpURLConnection conn;
    try {

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

        connectionSettings.ifPresent(settings -> settings.apply(conn));

        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:net.sheehantech.cherry.ProtocolTest.java

private byte[] expected(byte command, byte[] token, byte[] payload) {
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    DataOutputStream dataStream = new DataOutputStream(byteStream);
    try {// ww  w .  j a v  a  2s. c o  m
        dataStream.writeByte(command);
        dataStream.writeShort(token.length);
        dataStream.write(token);
        dataStream.writeShort(payload.length);
        dataStream.write(payload);
        return (byteStream.toByteArray());
    } catch (final IOException e) {
        throw new AssertionError();
    }
}

From source file:com.nokia.dempsy.messagetransport.tcp.TcpSender.java

@Override
public synchronized void send(byte[] messageBytes) throws MessageTransportException {
    try {/*  ww w.  j  a v a  2  s .  c  o  m*/
        DataOutputStream localDataOutputStream = getDataOutputStream();

        localDataOutputStream.writeInt(messageBytes.length);
        localDataOutputStream.flush();
        localDataOutputStream.write(messageBytes);
        localDataOutputStream.flush();
    } catch (IOException ioe) {
        close();
        throw new MessageTransportException(
                "It appears the client " + destination + " is no longer taking calls.", ioe);
    }
}

From source file:com.skubit.bitid.loaders.SignInAsyncTaskLoader.java

private void writeRequest(String message) throws IOException {
    DataOutputStream dos = new DataOutputStream(mConnection.getOutputStream());
    dos.write(message.getBytes());
    dos.close();/* w  w  w  .j  av a  2  s  .c  om*/
}

From source file:net.brtly.monkeyboard.plugin.core.panel.PluginDockableLayout.java

@Override
public void writeStream(DataOutputStream out) throws IOException {
    out.writeUTF(_id); // wirthe plugin id

    byte[] b = Bundle.toByteArray(_bundle); // write the size in bytes of the Bundle
    out.writeInt(b.length);//from ww w .  j a va 2  s . com

    out.write(b); // write the Bundle
}

From source file:org.getspout.spout.packet.PacketBlockData.java

public void writeData(DataOutputStream output) throws IOException {
    output.writeInt(data == null ? 0 : data.length);
    output.writeBoolean(compressed);//from w  ww . j  a v  a2  s.co  m
    if (data != null) {
        output.write(data);
    }
}

From source file:org.hoteia.qalingo.translation.LoaderTranslationUtil.java

private static void processLineWithValue(DataOutputStream writer, String prefixKey, CSVRecord line,
        int languagePosition, int linePosition, String outputEncoding)
        throws UnsupportedEncodingException, IOException {
    if (line.size() > 1) {
        String key = prefixKey + ".";
        String firstCell = line.get(0);
        if (StringUtils.isNotEmpty(firstCell)) {
            key = key + I18nKeyUtil.handleKey(firstCell).trim() + ".";
        }/*from ww  w  . ja  v  a 2 s . c om*/
        String secondCell = line.get(1);
        if (StringUtils.isNotEmpty(secondCell)) {
            key = key + I18nKeyUtil.handleKey(secondCell).trim();

            if (StringUtils.isNotEmpty(secondCell) && line.size() > languagePosition) {
                String value = line.get(languagePosition);
                if (value.contains("\\\"")) {
                    LOG.warn("Some properties values contain double quote twice: " + value);
                    value = value.replace("\\\"", "\"");
                }
                writer.write(((String) key + "=" + value).getBytes(outputEncoding));
            }
        }
        if (linePosition != 1) {
            writer.write(buildCarriageReturn(outputEncoding));
        }

    }
}

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

private void HttpPost(String AccessTokenUri, String requestDetails) {
    InputStream inSt = null;//from  w ww  .  java  2 s .com
    HttpsURLConnection webRequest = null;

    this.token = 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("content-type", "application/x-www-form-urlencoded");
        webRequest.setRequestMethod("POST");

        byte[] bytes = requestDetails.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();

        // parse the access token from the json format
        String result = strBuffer.toString();
        JSONObject jsonRoot = new JSONObject(result);
        this.token = new OxfordAccessToken();

        if (jsonRoot.has("access_token")) {
            this.token.access_token = jsonRoot.getString("access_token");
        }

        if (jsonRoot.has("token_type")) {
            this.token.token_type = jsonRoot.getString("token_type");
        }

        if (jsonRoot.has("expires_in")) {
            this.token.expires_in = jsonRoot.getString("expires_in");
        }

        if (jsonRoot.has("scope")) {
            this.token.scope = jsonRoot.getString("scope");
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}

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

public void serialize(CommitLogHeader clHeader, DataOutputStream dos) throws IOException {
    dos.writeInt(clHeader.getBitSet().length);
    dos.write(clHeader.getBitSet());
    int[] positions = clHeader.getPositions();

    for (int position : positions) {
        dos.writeInt(position);/*from w  w  w  .  ja  v  a 2 s. c  o m*/
    }
}

From source file:org.cablelabs.playready.cryptfile.PlayReadyPSSH.java

@Override
protected void generatePSSHData(DataOutputStream dos) throws IOException {

    // PlayReady Header Object Size field
    dos.write(toLEBytes(proSize, 4));

    // Number of Records field
    dos.write(toLEBytes(wrmHeaders.size(), 2));

    for (WRMHeader header : wrmHeaders) {

        byte[] wrmData = header.getWRMHeaderData();

        // Record Type (always 1 for WRM Headers)
        dos.write(toLEBytes(1, 2));//from   w  ww  . j a  va  2  s. co m

        // Record Length
        dos.write(toLEBytes(wrmData.length, 2));

        // Data
        dos.write(wrmData);
    }
}