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:me.rojo8399.placeholderapi.impl.Metrics.java

/**
 * Sends the data to the bStats server./*from  w  w  w .j  a va  2s  . co  m*/
 *
 * @param data
 *            The data to send.
 * @throws Exception
 *             If the request failed.
 */
private static void sendData(JsonObject data) throws Exception {
    Validate.notNull(data, "Data cannot be null");
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip
    // our
    // request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We
    // send
    // our
    // data
    // in
    // JSON
    // format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response
    // - Just send our data :)
}

From source file:info.fetter.logstashforwarder.protocol.LumberjackClient.java

private int sendDataFrame(DataOutputStream output, Map<String, byte[]> keyValues) throws IOException {
    output.writeByte(PROTOCOL_VERSION);//from w w  w .  j  a  v a 2  s  .  c o  m
    output.writeByte(FRAME_DATA);
    output.writeInt(sequence++);
    output.writeInt(keyValues.size());
    int bytesSent = 10;
    for (String key : keyValues.keySet()) {
        int keyLength = key.length();
        output.writeInt(keyLength);
        bytesSent += 4;
        output.write(key.getBytes());
        bytesSent += keyLength;
        byte[] value = keyValues.get(key);
        output.writeInt(value.length);
        bytesSent += 4;
        output.write(value);
        bytesSent += value.length;
    }
    output.flush();
    return bytesSent;
}

From source file:org.apache.hadoop.hive.ql.metadata.formatting.TextMetaDataFormatter.java

/**
 * Show the list of databases/* ww  w  .  ja  v a2  s.com*/
 */
@Override
public void showDatabases(DataOutputStream outStream, List<String> databases) throws HiveException {
    try {
        for (String database : databases) {
            // create a row per database name
            outStream.write(database.getBytes("UTF-8"));
            outStream.write(terminator);
        }
    } catch (IOException e) {
        throw new HiveException(e);
    }
}

From source file:org.apache.cassandra.db.ReadCommand.java

public void serialize(ReadCommand rm, DataOutputStream dos) throws IOException {
    dos.writeUTF(rm.table);/* w ww  . ja va2s. com*/
    dos.writeUTF(rm.key);
    dos.writeUTF(rm.columnFamilyColumn);
    dos.writeInt(rm.start);
    dos.writeInt(rm.count);
    dos.writeLong(rm.sinceTimestamp);
    dos.writeBoolean(rm.isDigestQuery());
    dos.writeInt(rm.columnNames.size());
    if (rm.columnNames.size() > 0) {
        for (String cName : rm.columnNames) {
            dos.writeInt(cName.getBytes().length);
            dos.write(cName.getBytes());
        }
    }
}

From source file:net.contrapunctus.rngzip.io.RNGZSettings.java

/**
 * Record a representation of these settings onto the designated
 * stream.  This representation is sufficient for reconstructing
 * the settings upon decompressing.//from  w ww  . j  a va  2  s  .  c o  m
 */
public void writeTo(MultiplexOutputStream mux, int stream) throws IOException {
    /* For future compatibility, the config stream tells how many
       other embedded streams will exist, then gives the compression
       scheme for each one.  For now, that is:
            
       zz  encoder id (one byte, 0=FIXED, 1=HUFFMAN, 2=BYTE)
       02  number of streams
       xx  compression for bit stream (0=NONE, 1=GZ, 2=BZ2, 3=PPM, 4=LZMA)
       yy  compression for data stream (same)
    */
    DataOutputStream out = mux.open(stream, new OutputStreamFilter<DataOutputStream>() {
        public DataOutputStream wrap(OutputStream out) throws IOException {
            return new DataOutputStream(out);
        }
    });
    out.write(coding.ordinal());
    out.write(2);
    out.write(treeCompr.ordinal());
    out.write(dataCompr.ordinal());
}

From source file:org.apache.hadoop.hive.ql.metadata.formatting.TextMetaDataFormatter.java

/**
 * Describe a database// w  w  w . j  ava  2 s.  c  om
 */
@Override
public void showDatabaseDescription(DataOutputStream outStream, String database, String comment,
        String location, String ownerName, String ownerType, Map<String, String> params) throws HiveException {
    try {
        outStream.write(database.getBytes("UTF-8"));
        outStream.write(separator);
        if (comment != null) {
            outStream.write(HiveStringUtils.escapeJava(comment).getBytes("UTF-8"));
        }
        outStream.write(separator);
        if (location != null) {
            outStream.write(location.getBytes("UTF-8"));
        }
        outStream.write(separator);
        if (ownerName != null) {
            outStream.write(ownerName.getBytes("UTF-8"));
        }
        outStream.write(separator);
        if (ownerType != null) {
            outStream.write(ownerType.getBytes("UTF-8"));
        }
        outStream.write(separator);
        if (params != null && !params.isEmpty()) {
            outStream.write(params.toString().getBytes("UTF-8"));
        }
        outStream.write(terminator);
    } catch (IOException e) {
        throw new HiveException(e);
    }
}

From source file:org.csploit.android.core.System.java

private static void startCoreDaemon() throws SuException, DaemonException {
    boolean access_granted = false;
    DataOutputStream writer = null;
    BufferedReader reader = null;
    String line;/*from   w  w w  . j ava2  s  .c  om*/
    int ret = -1;

    try {
        Process shell = Runtime.getRuntime().exec("su");
        writer = new DataOutputStream(shell.getOutputStream());
        String cmd;

        cmd = String.format("{ echo 'ACCESS GRANTED' >&2; cd '%s' && exec ./start_daemon.sh ;} || exit 1\n",
                System.getCorePath());

        writer.write(cmd.getBytes());
        writer.flush();

        ret = shell.waitFor();

        if (ret != 0) {
            reader = new BufferedReader(new InputStreamReader(shell.getErrorStream()));

            while ((line = reader.readLine()) != null) {
                if (line.equals("ACCESS GRANTED")) {
                    access_granted = true;
                    Logger.debug("'ACCESS GRANTED' found");
                } else
                    Logger.warning("STDERR: " + line);
            }
        } else
            access_granted = true;

    } catch (IOException e) {
        // command "su" not found or cannot write to it's stdin
        Logger.error(e.getMessage());
    } catch (InterruptedException e) {
        // interrupted while waiting for shell exit value
        Logger.error(e.getMessage());
    } finally {
        if (writer != null)
            try {
                writer.close();
            } catch (IOException ignored) {
            }
        if (reader != null)
            try {
                reader.close();
            } catch (IOException ignored) {
            }
    }

    mKnownIssues.fromFile(String.format("%s/issues", getCorePath()));

    if (!access_granted)
        throw new SuException();

    if (ret != 0) {
        File log = new File(System.getCorePath(), "cSploitd.log");
        DaemonException daemonException = new DaemonException("core daemon returned " + ret);
        if (log.exists() && log.canRead()) {
            ACRAConfiguration conf = ACRA.getConfig();
            conf.setApplicationLogFile(log.getAbsolutePath());
            ACRA.setConfig(conf);
            ACRA.getErrorReporter().handleException(daemonException, false);
        }
        throw daemonException;
    }
}

From source file:org.apache.hadoop.hive.ql.metadata.formatting.TextMetaDataFormatter.java

/**
 * Show a list of tables./*w ww. j  ava2s. c o  m*/
 */
@Override
public void showTables(DataOutputStream out, Set<String> tables) throws HiveException {
    Iterator<String> iterTbls = tables.iterator();

    try {
        while (iterTbls.hasNext()) {
            // create a row per table name
            out.write(iterTbls.next().getBytes("UTF-8"));
            out.write(terminator);
        }
    } catch (IOException e) {
        throw new HiveException(e);
    }
}

From source file:com.google.glassware.NotifyServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Respond with OK and status 200 in a timely fashion to prevent redelivery
    response.setContentType("text/html");
    Writer writer = response.getWriter();
    writer.append("OK");
    writer.close();// w w w  .j  a v  a 2  s.  c o m

    // Get the notification object from the request body (into a string so we
    // can log it)
    BufferedReader notificationReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
    String notificationString = "";

    String responseStringForFaceDetection = null;
    // Count the lines as a very basic way to prevent Denial of Service attacks
    int lines = 0;
    String line;
    while ((line = notificationReader.readLine()) != null) {
        notificationString += line;
        lines++;

        // No notification would ever be this long. Something is very wrong.
        if (lines > 1000) {
            throw new IOException("Attempted to parse notification payload that was unexpectedly long.");
        }
    }
    notificationReader.close();

    LOG.info("got raw notification " + notificationString);

    JsonFactory jsonFactory = new JacksonFactory();

    // If logging the payload is not as important, use
    // jacksonFactory.fromInputStream instead.
    Notification notification = jsonFactory.fromString(notificationString, Notification.class);

    LOG.info("Got a notification with ID: " + notification.getItemId());

    // Figure out the impacted user and get their credentials for API calls
    String userId = notification.getUserToken();
    Credential credential = AuthUtil.getCredential(userId);
    Mirror mirrorClient = MirrorClient.getMirror(credential);

    if (notification.getCollection().equals("locations")) {
        LOG.info("Notification of updated location");
        Mirror glass = MirrorClient.getMirror(credential);
        // item id is usually 'latest'
        Location location = glass.locations().get(notification.getItemId()).execute();

        LOG.info("New location is " + location.getLatitude() + ", " + location.getLongitude());
        MirrorClient.insertTimelineItem(credential, new TimelineItem()
                .setText("Java Quick Start says you are now at " + location.getLatitude() + " by "
                        + location.getLongitude())
                .setNotification(new NotificationConfig().setLevel("DEFAULT")).setLocation(location)
                .setMenuItems(Lists.newArrayList(new MenuItem().setAction("NAVIGATE"))));

        // This is a location notification. Ping the device with a timeline item
        // telling them where they are.
    } else if (notification.getCollection().equals("timeline")) {
        // Get the impacted timeline item
        TimelineItem timelineItem = mirrorClient.timeline().get(notification.getItemId()).execute();
        LOG.info("Notification impacted timeline item with ID: " + timelineItem.getId());

        // If it was a share, and contains a photo, update the photo's caption to
        // acknowledge that we got it.
        if (notification.getUserActions().contains(new UserAction().setType("SHARE"))
                && timelineItem.getAttachments() != null && timelineItem.getAttachments().size() > 0) {
            String finalresponseForCard = null;

            String questionString = timelineItem.getText();
            if (!questionString.isEmpty()) {
                String[] questionStringArray = questionString.split(" ");

                LOG.info(timelineItem.getText() + " is the questions asked by the user");
                LOG.info("A picture was taken");

                if (questionString.toLowerCase().contains("search")
                        || questionString.toLowerCase().contains("tag")
                        || questionString.toLowerCase().contains("train")
                        || questionString.toLowerCase().contains("mark")
                        || questionString.toLowerCase().contains("recognize")
                        || questionString.toLowerCase().contains("what is")) {

                    //Fetching the image from the timeline
                    InputStream inputStream = downloadAttachment(mirrorClient, notification.getItemId(),
                            timelineItem.getAttachments().get(0));

                    //converting the image to Base64
                    Base64 base64Object = new Base64(false);
                    String encodedImageToBase64 = base64Object.encodeToString(IOUtils.toByteArray(inputStream)); //byteArrayForOutputStream.toByteArray()
                    // byteArrayForOutputStream.close();
                    encodedImageToBase64 = java.net.URLEncoder.encode(encodedImageToBase64, "ISO-8859-1");

                    //sending the API request
                    LOG.info("Sending request to API");
                    //For initial protoype we're calling the Alchemy API for detecting the number of Faces using web API call
                    try {
                        String urlParameters = "";
                        String tag = "";

                        if (questionString.toLowerCase().contains("tag")
                                || questionString.toLowerCase().contains("mark")) {

                            tag = extractTagFromQuestion(questionString);
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_add&name_space=recognizeObject&user_id=user1&tag="
                                    + tag + "&base64=" + encodedImageToBase64;

                        } else if (questionString.toLowerCase().contains("train")) {
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_train&name_space=recognizeObject&user_id=user1";
                        } else if (questionString.toLowerCase().contains("search")) {
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_search&name_space=recognizeObject&user_id=user1&base64="
                                    + encodedImageToBase64;
                        } else if (questionString.toLowerCase().contains("recognize")
                                || questionString.toLowerCase().contains("what is")) {
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_recognize&name_space=recognizeObject&user_id=user1&base64="
                                    + encodedImageToBase64;
                        }
                        byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
                        int postDataLength = postData.length;
                        String newrequest = "http://rekognition.com/func/api/";
                        URL url = new URL(newrequest);
                        HttpURLConnection connectionFaceDetection = (HttpURLConnection) url.openConnection();

                        // Increase the timeout for reading the response
                        connectionFaceDetection.setReadTimeout(15000);

                        connectionFaceDetection.setDoOutput(true);
                        connectionFaceDetection.setDoInput(true);
                        connectionFaceDetection.setInstanceFollowRedirects(false);
                        connectionFaceDetection.setRequestMethod("POST");
                        connectionFaceDetection.setRequestProperty("Content-Type",
                                "application/x-www-form-urlencoded");
                        connectionFaceDetection.setRequestProperty("X-Mashape-Key",
                                "pzFbNRvNM4mshgWJvvdw0wpLp5N1p1X3AX9jsnOhjDUkn5Lvrp");
                        connectionFaceDetection.setRequestProperty("charset", "utf-8");
                        connectionFaceDetection.setRequestProperty("Accept", "application/json");
                        connectionFaceDetection.setRequestProperty("Content-Length",
                                Integer.toString(postDataLength));
                        connectionFaceDetection.setUseCaches(false);

                        DataOutputStream outputStreamForFaceDetection = new DataOutputStream(
                                connectionFaceDetection.getOutputStream());
                        outputStreamForFaceDetection.write(postData);

                        BufferedReader inputStreamForFaceDetection = new BufferedReader(
                                new InputStreamReader((connectionFaceDetection.getInputStream())));

                        StringBuilder responseForFaceDetection = new StringBuilder();

                        while ((responseStringForFaceDetection = inputStreamForFaceDetection
                                .readLine()) != null) {
                            responseForFaceDetection.append(responseStringForFaceDetection);
                        }

                        //closing all the connections
                        inputStreamForFaceDetection.close();
                        outputStreamForFaceDetection.close();
                        connectionFaceDetection.disconnect();

                        responseStringForFaceDetection = responseForFaceDetection.toString();
                        LOG.info(responseStringForFaceDetection);

                        JSONObject responseJSONObjectForFaceDetection = new JSONObject(
                                responseStringForFaceDetection);
                        if (questionString.toLowerCase().contains("train") || questionString.contains("tag")
                                || questionString.toLowerCase().contains("mark")) {
                            JSONObject usageKeyFromResponse = responseJSONObjectForFaceDetection
                                    .getJSONObject("usage");
                            finalresponseForCard = usageKeyFromResponse.getString("status");
                            if (!tag.equals(""))
                                finalresponseForCard = "Object is tagged as " + tag;
                        } else {
                            JSONObject sceneUnderstandingObject = responseJSONObjectForFaceDetection
                                    .getJSONObject("scene_understanding");
                            JSONArray matchesArray = sceneUnderstandingObject.getJSONArray("matches");
                            JSONObject firstResultFromArray = matchesArray.getJSONObject(0);

                            double percentSureOfObject;
                            //If an score has value 1, then the value type is Integer else the value type is double
                            if (firstResultFromArray.get("score") instanceof Integer) {
                                percentSureOfObject = (Integer) firstResultFromArray.get("score") * 100;
                            } else
                                percentSureOfObject = (Double) firstResultFromArray.get("score") * 100;

                            finalresponseForCard = "The object is " + firstResultFromArray.getString("tag")
                                    + ". Match score is" + percentSureOfObject;
                        }

                        //section where if it doesn't contain anything about tag or train

                    } catch (Exception e) {
                        LOG.warning(e.getMessage());
                    }

                }

                else
                    finalresponseForCard = "Could not understand your words";
            } else
                finalresponseForCard = "Could not understand your words";

            TimelineItem responseCardForSDKAlchemyAPI = new TimelineItem();

            responseCardForSDKAlchemyAPI.setText(finalresponseForCard);
            responseCardForSDKAlchemyAPI
                    .setMenuItems(Lists.newArrayList(new MenuItem().setAction("READ_ALOUD")));
            responseCardForSDKAlchemyAPI.setSpeakableText(finalresponseForCard);
            responseCardForSDKAlchemyAPI.setSpeakableType("Results are as follows");
            responseCardForSDKAlchemyAPI.setNotification(new NotificationConfig().setLevel("DEFAULT"));
            mirrorClient.timeline().insert(responseCardForSDKAlchemyAPI).execute();
            LOG.info("New card added to the timeline");

        } else if (notification.getUserActions().contains(new UserAction().setType("LAUNCH"))) {
            LOG.info("It was a note taken with the 'take a note' voice command. Processing it.");

            // Grab the spoken text from the timeline card and update the card with
            // an HTML response (deleting the text as well).
            String noteText = timelineItem.getText();
            String utterance = CAT_UTTERANCES[new Random().nextInt(CAT_UTTERANCES.length)];

            timelineItem.setText(null);
            timelineItem.setHtml(makeHtmlForCard(
                    "<p class='text-auto-size'>" + "Oh, did you say " + noteText + "? " + utterance + "</p>"));
            timelineItem.setMenuItems(Lists.newArrayList(new MenuItem().setAction("DELETE")));

            mirrorClient.timeline().update(timelineItem.getId(), timelineItem).execute();
        } else {
            LOG.warning("I don't know what to do with this notification, so I'm ignoring it.");
        }
    }
}

From source file:com.amazon.alexa.avs.companion.ProvisioningClient.java

JSONObject doRequest(HttpURLConnection connection, String data) throws IOException, JSONException {
    int responseCode = -1;
    InputStream response = null;//from   w w  w.jav a 2 s .  c  o m
    DataOutputStream outputStream = null;

    try {
        if (connection instanceof HttpsURLConnection) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(pinnedSSLSocketFactory);
        }

        connection.setRequestProperty("Content-Type", "application/json");
        if (data != null) {
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(data.getBytes());
            outputStream.flush();
            outputStream.close();
        } else {
            connection.setRequestMethod("GET");
        }

        responseCode = connection.getResponseCode();
        response = connection.getInputStream();

        if (responseCode != 204) {
            String responseString = IOUtils.toString(response);
            JSONObject jsonObject = new JSONObject(responseString);
            return jsonObject;
        } else {
            return null;
        }
    } catch (IOException e) {
        if (responseCode < 200 || responseCode >= 300) {
            response = connection.getErrorStream();
            if (response != null) {
                String responseString = IOUtils.toString(response);
                throw new RuntimeException(responseString);
            }
        }
        throw e;
    } finally {
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(response);
    }
}