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.jackrabbit.core.journal.FileRecordLog.java

/**
 * Write signature and major/minor./*from  w ww.j a va  2s  . com*/
 *
 * @param out input stream
 * @throws java.io.IOException if an I/O error occurs.
 */
private void writeHeader(DataOutputStream out) throws IOException {
    out.write(SIGNATURE);
    out.writeShort(MAJOR_VERSION);
    out.writeShort(MINOR_VERSION);
}

From source file:halive.shootinoutside.common.core.game.map.GameMap.java

private byte[] getMapData() {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DataOutputStream output = new DataOutputStream(out);
    for (int x = 0; x < tiles.length; x++) {
        for (int y = 0; y < tiles[x].length; y++) {
            try {
                output.write(tiles[x][y].getTileID());
            } catch (IOException e) {
                return null;
            }/* w  w w  .  jav a  2  s .co m*/
        }
    }
    return out.toByteArray();
}

From source file:org.darwinathome.server.controller.HubController.java

@RequestMapping(Hub.GET_WORLD_SERVICE)
public void getWorld(@PathVariable("session") String session, OutputStream outputStream) throws IOException {
    log.info(Hub.GET_WORLD_SERVICE + " " + session);
    DataOutputStream dos = new DataOutputStream(outputStream);
    PlayerSession playerSession = sessionMap.get(session);
    if (playerSession != null) {
        dos.writeUTF(Hub.SUCCESS);/*from ww  w  . ja v  a 2s.c  om*/
        dos.write(worldHistory.getFrozenWorld().getWorld());
        Iterator<PlayerSession> sessionWalk = sessionMap.values().iterator();
        while (sessionWalk.hasNext()) {
            if (sessionWalk.next().isExpired()) {
                sessionWalk.remove();
            }
        }
    } else {
        dos.writeUTF(Hub.FAILURE);
        dos.writeUTF(Failure.SESSION.toString());
    }
}

From source file:com.hellofyc.base.net.http.HttpUtils.java

protected void configConnection(HttpURLConnection connection) throws IOException {
    connection.setConnectTimeout(mConnectTimeout);
    connection.setReadTimeout(mReadTimeout);
    connection.setUseCaches(false);//from w  w  w. j  ava2 s.co  m
    connection.setDoInput(true);
    connection.setRequestProperty("Charset", Charset.defaultCharset().name());
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("User-Agent", mUserAgent);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestProperty("Cookie", CookieHelper.parse(mRequestParams.getCookies()));

    switch (mType) {
    case TYPE_TEXT: {
        connection.setRequestMethod(mMethod.name());
        if (mMethod == Method.POST) {
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", CONTENT_TYPE_TEXT);
            String paramsString;
            if (!TextUtils.isEmpty(mRequestParams.getString())) {
                paramsString = mRequestParams.getString();
            } else {
                paramsString = parseMapToUrlParamsString(mRequestParams.getArrayMap());
            }
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(paramsString.getBytes());
            outputStream.flush();
            outputStream.close();
        }
        break;
    }
    case TYPE_BITMAP: {
        connection.setRequestMethod(Method.POST.name());
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", CONTENT_TYPE_FILE);
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Object> entry : mRequestParams.getArrayMap().entrySet()) {
            builder.append(PREFIX).append(BOUNDARY).append(LINE_END);
            builder.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"")
                    .append(LINE_END);
            builder.append("Content-Type: text/plain; charset=\"utf-8\"").append(LINE_END);
            builder.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
            builder.append(LINE_END);
            builder.append(entry.getValue());
            builder.append(LINE_END);
        }
        outputStream.write(builder.toString().getBytes());

        outputStream.writeBytes(PREFIX + BOUNDARY + LINE_END);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + "bitmap" + "\";filename=\""
                + "bitmap.jpg" + "\"" + LINE_END);
        outputStream.writeBytes(LINE_END);
        outputStream.write(bitmapToBytes(mBitmap));
        outputStream.writeBytes(LINE_END);
        outputStream.writeBytes(PREFIX + BOUNDARY + PREFIX + LINE_END);
        outputStream.flush();
        outputStream.close();
        break;
    }
    case TYPE_FILE: {
        connection.setRequestMethod(Method.POST.name());
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", CONTENT_TYPE_FILE);

        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Object> entry : mRequestParams.getArrayMap().entrySet()) {
            builder.append(PREFIX).append(BOUNDARY).append(LINE_END);
            builder.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"")
                    .append(LINE_END);
            builder.append("Content-Type: text/plain; charset=\"utf-8\"").append(LINE_END);
            builder.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
            builder.append(LINE_END);
            builder.append(entry.getValue());
            builder.append(LINE_END);
        }

        for (ArrayMap.Entry<String, File> entry : mFileMap.entrySet()) {
            String text = PREFIX + BOUNDARY + LINE_END + "Content-Disposition: form-data; name=\""
                    + entry.getKey() + "\"; filename=\"" + entry.getValue().getName() + "\"" + LINE_END
                    + "Content-Type:" + "application/octet-stream" + LINE_END
                    + "Content-Transfer-Encoding: binary" + LINE_END + LINE_END;
            outputStream.writeBytes(builder.append(text).toString());

            BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(entry.getValue()));
            int length;
            byte[] bytes = new byte[1024 * 1024];
            while ((length = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
            inputStream.close();
        }

        String endTag = LINE_END + PREFIX + BOUNDARY + PREFIX + LINE_END;
        outputStream.writeBytes(endTag);
        outputStream.flush();
        outputStream.close();
        break;
    }
    }
}

From source file:net.roboconf.target.azure.internal.AzureIaasHandler.java

private int processPostRequest(URL url, byte[] data, String contentType, String keyStore,
        String keyStorePassword) throws GeneralSecurityException, IOException {

    SSLSocketFactory sslFactory = this.getSSLSocketFactory(keyStore, keyStorePassword);
    HttpsURLConnection con;/*from  www .ja v a 2s . c om*/
    con = (HttpsURLConnection) url.openConnection();
    con.setSSLSocketFactory(sslFactory);
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.addRequestProperty("x-ms-version", "2014-04-01");
    con.setRequestProperty("Content-Length", String.valueOf(data.length));
    con.setRequestProperty("Content-Type", contentType);

    DataOutputStream requestStream = new DataOutputStream(con.getOutputStream());
    requestStream.write(data);
    requestStream.flush();
    requestStream.close();

    return con.getResponseCode();
}

From source file:net.servicestack.client.JsonServiceClient.java

public HttpURLConnection createRequest(String requestUrl, String httpMethod, byte[] requestBody,
        String requestType) {//from  w ww.  j  av a 2s.co m
    try {
        URL url = new URL(requestUrl);

        HttpURLConnection req = (HttpURLConnection) url.openConnection();
        req.setDoOutput(true);

        if (timeoutMs != null) {
            req.setConnectTimeout(timeoutMs);
            req.setReadTimeout(timeoutMs);
        }

        req.setRequestMethod(httpMethod);
        req.setRequestProperty(HttpHeaders.Accept, MimeTypes.Json);

        if (requestType != null) {
            req.setRequestProperty(HttpHeaders.ContentType, requestType);
        }

        if (requestBody != null) {
            req.setRequestProperty(HttpHeaders.ContentLength, Integer.toString(requestBody.length));
            DataOutputStream wr = new DataOutputStream(req.getOutputStream());
            wr.write(requestBody);
            wr.flush();
            wr.close();
        }

        if (RequestFilter != null) {
            RequestFilter.exec(req);
        }

        if (GlobalRequestFilter != null) {
            GlobalRequestFilter.exec(req);
        }

        return req;

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.hawq.pxf.service.MetadataResponse.java

/**
 * Serializes the metadata list in JSON, To be used as the result string for HAWQ.
 *///from  ww  w  . j  ava 2  s  . c o  m
@Override
public void write(OutputStream output) throws IOException {
    DataOutputStream dos = new DataOutputStream(output);
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(org.codehaus.jackson.map.SerializationConfig.Feature.USE_ANNOTATIONS, true); // enable annotations for serialization
    mapper.setSerializationInclusion(Inclusion.NON_EMPTY); // ignore empty fields

    if (metadataList == null || metadataList.isEmpty()) {
        dos.write(METADATA_DEFAULT_RESPONSE.getBytes());
        return;
    }

    dos.write("{\"PXFMetadata\":[".getBytes());

    String prefix = "";
    for (Metadata metadata : metadataList) {
        if (metadata == null) {
            throw new IllegalArgumentException("metadata object is null - cannot serialize");
        }
        if ((metadata.getFields() == null) || metadata.getFields().isEmpty()) {
            throw new IllegalArgumentException(
                    "metadata for " + metadata.getItem() + " contains no fields - cannot serialize");
        }
        StringBuilder result = new StringBuilder();
        result.append(prefix).append(mapper.writeValueAsString(metadata));
        prefix = ",";
        dos.write(result.toString().getBytes());
    }

    dos.write("]}".getBytes());
}

From source file:com.igormaznitsa.jhexed.renders.svg.SVGImage.java

public void write(final OutputStream out, final boolean zipped) throws IOException {
    final DataOutputStream dout = out instanceof DataOutputStream ? (DataOutputStream) out
            : new DataOutputStream(out);
    if (zipped) {
        final byte[] packedImage = Utils.packByteArray(this.originalNonParsedImageData);

        dout.writeInt(packedImage.length);
        dout.write(packedImage);
    } else {//from w w  w  . java2s.  c o m
        dout.write(this.originalNonParsedImageData);
    }
    dout.writeBoolean(this.quality);
}

From source file:com.mendhak.gpslogger.senders.gdocs.GDocsHelper.java

private String UpdateFileContents(String authToken, String gpxFileId, byte[] fileContents) {
    HttpURLConnection conn = null;
    String fileId = null;//from  ww w.  jav  a2 s  .co  m

    String fileUpdateUrl = "https://www.googleapis.com/upload/drive/v2/files/" + gpxFileId
            + "?uploadType=media";

    try {

        if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
            //Due to a pre-froyo bug
            //http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            System.setProperty("http.keepAlive", "false");
        }

        URL url = new URL(fileUpdateUrl);

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("User-Agent", "GPSLogger for Android");
        conn.setRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Content-Type", "application/xml");
        conn.setRequestProperty("Content-Length", String.valueOf(fileContents.length));

        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.write(fileContents);
        wr.flush();
        wr.close();

        String fileMetadata = Utilities.GetStringFromInputStream(conn.getInputStream());

        JSONObject fileMetadataJson = new JSONObject(fileMetadata);
        fileId = fileMetadataJson.getString("id");
        Utilities.LogDebug("File updated : " + fileId);

    } catch (Exception e) {
        System.out.println(e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }

    }

    return fileId;

}

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

@Override
protected String doInBackground(Context... params) {
    mContext = params[0];//from  ww  w. ja va 2  s .  co 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();
            }
    }
}