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.tc.simple.apn.factories.PushByteFactory.java

@Override
public byte[] buildPushBytes(int id, Payload payload) {
    byte[] byteMe = null;
    ByteArrayOutputStream baos = null;
    DataOutputStream dos = null;

    try {/*  w  w w  .j  a va 2  s. co m*/
        baos = new ByteArrayOutputStream();

        dos = new DataOutputStream(baos);

        int expiry = 0; // (int) ((System.currentTimeMillis () / 1000L) + 7200);

        char[] cars = payload.getToken().trim().toCharArray();

        byte[] tokenBytes = Hex.decodeHex(cars);

        //command
        dos.writeByte(1);

        //id
        dos.writeInt(id);

        //expiry
        dos.writeInt(expiry);

        //token length.
        dos.writeShort(tokenBytes.length);

        //token
        dos.write(tokenBytes);

        //payload length
        dos.writeShort(payload.getJson().length());

        logger.log(Level.FINE, payload.getJson());

        //payload.
        dos.write(payload.getJson().getBytes());

        byteMe = baos.toByteArray();

    } catch (Exception e) {
        logger.log(Level.SEVERE, null, e);

    } finally {
        CloseUtils.close(dos);
        CloseUtils.close(baos);
    }

    return byteMe;

}

From source file:org.openhab.binding.sonance.internal.SonanceBinding.java

/**
 * Send volume commands to groups (music zones)
 *
 * @param itemName//from   w w w . j  a va2  s.c  o  m
 *            item name to send update to
 * @param command
 *            Sonance IP code to execute
 * @param outToServer
 *            date output stream we can write to
 * @param i
 *            bufered reader where we can read from
 * @throws IOException
 *             throws an exception when we can't reach to amplifier
 */
private void sendVolumeCommand(String itemName, String command, DataOutputStream outToServer, BufferedReader i)
        throws IOException {
    char[] cbuf = new char[50]; // Response is always 50 characters

    logger.debug("Sending volume command {}", command);

    outToServer.write(hexStringToByteArray(command));
    i.read(cbuf, 0, 50);

    Matcher m = volumePattern.matcher(new String(cbuf));

    if (m.find()) {
        String volume = m.group(1);
        eventPublisher.postUpdate(itemName, new DecimalType(volume));
        logger.debug("Setting volume for item {} on {}", itemName, volume);
    } else {
        logger.error("Error sending regular volume command {}, received this: {}", command, new String(cbuf));
    }
}

From source file:org.openhab.binding.sonance.internal.SonanceBinding.java

/**
 * Enable or disable specific groups (music zones)
 *
 * @param itemName/*from  www .j  a  v a2 s . c  o m*/
 *            item name to send update to
 * @param command
 *            Sonance IP code to execute
 * @param outToServer
 *            date output stream we can write to
 * @param i
 *            bufered reader where we can read from
 * @throws IOException
 *             throws an exception when we can't reach to amplifier
 */
private void sendMuteCommand(String itemName, String command, DataOutputStream outToServer, BufferedReader i)
        throws IOException {
    char[] cbuf = new char[50]; // Response is always 50 characters

    logger.debug("Sending mute command {}", command);
    outToServer.write(hexStringToByteArray(command));
    i.read(cbuf, 0, 50);

    String result = new String(cbuf);

    logger.trace("Received this result: {}", result);

    if (result.contains("Mute=on") || result.contains("MuteOn")) {
        eventPublisher.postUpdate(itemName, OnOffType.OFF);
        logger.debug("Setting mute item {} on OFF", itemName);
    } else if (result.contains("Mute=off") || result.contains("MuteOff")) {
        eventPublisher.postUpdate(itemName, OnOffType.ON);
        logger.debug("Setting mute item {} on ON", itemName);
    } else {
        logger.error("Error sending mute command {}, received this: {}", command, result);
    }
}

From source file:org.openhab.binding.sonance.internal.SonanceBinding.java

/**
 * Wake up or put amplifier to sleep//from   w  ww.j av  a  2s.c om
 *
 * @param itemName
 *            item name to send update to
 * @param command
 *            Sonance IP code to execute
 * @param outToServer
 *            date output stream we can write to
 * @param i
 *            bufered reader where we can read from
 * @throws IOException
 *             throws an exception when we can't reach to amplifier
 */
private void sendPowerCommand(String itemName, String command, DataOutputStream outToServer, BufferedReader i)
        throws IOException {
    char[] cbuf = new char[50]; // Response is always 50 characters

    logger.debug("Sending power command {}", command);
    outToServer.write(hexStringToByteArray(command));
    i.read(cbuf, 0, 50);

    String result = new String(cbuf);

    logger.trace("Received power response: {}", result);

    if (result.contains("Off")) {
        eventPublisher.postUpdate(itemName, OnOffType.OFF);
        logger.debug("Setting power item {} on OFF", itemName);
    } else if (result.contains("On")) {
        eventPublisher.postUpdate(itemName, OnOffType.ON);
        logger.debug("Setting power item {} on ON", itemName);
    } else {
        logger.trace("Error sending power command {}, received this: {}", command, result);
    }
}

From source file:org.apache.hadoop.io.TestBufferedByteInputOutput.java

/**
 * Test if writing to closed buffer fails.
 */// w  ww .  java2  s .c o m
@Test
public void testCloseOutput() throws IOException {
    LOG.info("Running test close output");
    ByteArrayOutputStream os = new ByteArrayOutputStream(1000);
    DataOutputStream dos = BufferedByteOutputStream.wrapOutputStream(os, 100, 10);

    dos.close();
    dos.close(); // can close multiple times

    try {
        // this will cause to flush BufferedOutputStream
        for (int i = 0; i < 10000; i++) {
            dos.write(1);
        }
        fail("Write should fail");
    } catch (Exception e) {
        LOG.info("Expected exception " + e.getMessage());
    }

    try {
        // this will cause to flush BufferedOutputStream
        for (int i = 0; i < 1000; i++) {
            dos.write(new byte[10], 0, 10);
        }
        fail("Write should fail");
    } catch (Exception e) {
        LOG.info("Expected exception " + e.getMessage());
    }

    try {
        dos.flush();
        fail("Flush should fail");
    } catch (Exception e) {
        LOG.info("Expected exception " + e.getMessage());
    }
}

From source file:org.apache.hadoop.io.TestBufferedByteInputOutput.java

private void testOutputStream(int inputSize, int bufferSize, int writeBufferSize, boolean closeAndCheck)
        throws IOException {
    TestBufferedByteInputOutputInjectionHandler h = new TestBufferedByteInputOutputInjectionHandler();
    InjectionHandler.set(h);//from w w w.  j a va2  s  . c  om
    LOG.info("Running test output stream with inputSize: " + inputSize + ", bufferSize: " + bufferSize
            + ", readBufferSize: " + writeBufferSize);
    setUp(inputSize);
    ByteArrayOutputStream os = new ByteArrayOutputStream(inputSize);
    DataOutputStream dos = BufferedByteOutputStream.wrapOutputStream(os, bufferSize, writeBufferSize);

    int totalWritten = 0;
    int inputCursor = 0;
    while (totalWritten < inputSize) {
        if (rand.nextBoolean()) {
            // write single byte
            dos.write(input[inputCursor++]);
            totalWritten++;
        } else {
            int count = rand.nextInt(inputSize - totalWritten) + 1;
            dos.write(input, inputCursor, count);
            inputCursor += count;
            totalWritten += count;
        }

        // random flush
        if (rand.nextBoolean()) {
            h.bytesFlushed = -1;
            dos.flush();
            assertEquals(totalWritten, h.bytesFlushed);
        }
    }

    if (closeAndCheck) {
        // we either close
        dos.close();
    } else {
        // or need to flush the stream
        dos.flush();
    } // in either case data must be out

    assertEquals(inputSize, totalWritten);
    assertTrue(Arrays.equals(input, os.toByteArray()));

    // close
    dos.close();
    dos.close(); // should be fine to call it multiple times
    dos.close();
}

From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java

private String queryDMS(String DMS_endpoint, String postObject, String cookie) {
    HttpURLConnection connectionDMS = null;
    try {/*from   w  w  w. ja  v a2 s  . c o  m*/

        String postObjectString = postObject;
        byte[] postObjectByte = postObjectString.getBytes(StandardCharsets.UTF_8);
        int postDataLength = postObjectByte.length;
        URL DMS_Url = new URL(dms_URL + "/" + DMS_endpoint);

        // prepare header
        connectionDMS = (HttpURLConnection) DMS_Url.openConnection();
        connectionDMS.setDoOutput(true);
        connectionDMS.setDoInput(true);
        connectionDMS.setConnectTimeout(5000);
        connectionDMS.setReadTimeout(5000);
        connectionDMS.setRequestProperty("Content-Type", "application/json");
        connectionDMS.setRequestProperty("Accept", "application/json");
        connectionDMS.setRequestProperty("charset", "utf-8");
        connectionDMS.setRequestProperty("vitalAccessToken", cookie);
        connectionDMS.setRequestMethod("POST");
        connectionDMS.setRequestProperty("Content-Length", Integer.toString(postDataLength));

        DataOutputStream wr = new DataOutputStream(connectionDMS.getOutputStream());
        wr.write(postObjectByte);
        wr.flush();
        int HttpResult = connectionDMS.getResponseCode();
        if (HttpResult == HttpURLConnection.HTTP_OK) {
            Object obj = new InputStreamReader(connectionDMS.getInputStream(), "utf-8");

            return obj.toString();

        } else {
            return null;
        }
    } catch (Exception e) {
        //logger.error(e.toString());
        //throw new ConnectionErrorException("Error in connection with DMSManager");
    } finally {
        if (connectionDMS != null) {
            connectionDMS.disconnect();
        }
    }
    return "";
}

From source file:com.github.gcauchis.scalablepress4j.api.AbstractRestApi.java

/**
 * Call request for entity./* w w w .j  a v a2s  .co  m*/
 *
 * @param <T> the generic type
 * @param url the url
 * @param requestMethod the http request method
 * @param request the request
 * @param responseType the response type
 * @param urlVariables the url variables
 * @return the response
 */
private <T> Response<T> forEntity(String url, String requestMethod, Object request, Class<T> responseType,
        Map<String, ?> urlVariables) {
    StringBuilder response = new StringBuilder();
    HttpURLConnection connection = prepareConnection(url, requestMethod, urlVariables);
    try {

        // // Send request
        DataOutputStream wr = null;
        if (request != null) {
            String content = objectMapper.writeValueAsString(request);
            wr = new DataOutputStream(connection.getOutputStream());
            wr.write(content.getBytes(StandardCharsets.UTF_8));
            wr.flush();
        }

        // Get Response
        BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }

        if (wr != null) {
            wr.close();
        }
        rd.close();
        log.trace("Response {}", response);
    } catch (IOException e) {
        log.error("Fail to send request", e);
        ErrorResponse errorResponse = new ErrorResponse();
        try {
            errorResponse.setStatusCode(connection.getResponseCode() + "");
            errorResponse.setMessage(connection.getResponseMessage());
        } catch (IOException e1) {
            errorResponse.setStatusCode("500");
            errorResponse.setMessage(e.getMessage());
        }
        throw new ScalablePressBadRequestException(errorResponse);
    }

    Response<T> responseEntity = new Response<>();
    responseEntity.headers = connection.getHeaderFields();
    log.debug("Header: {}", responseEntity.headers);
    try {
        responseEntity.body = objectMapper.readValue(response.toString(), responseType);
    } catch (IOException e) {
        log.error("Fail to parse response", e);
        ErrorResponse errorResponse = null;
        try {
            log.error("Response error: {} {}", connection.getResponseCode(), connection.getResponseMessage());
            errorResponse = objectMapper.readValue(response.toString(), ErrorResponse.class);
        } catch (IOException ioe) {
            log.error("Fail to parse error", ioe);
        }
        if (errorResponse != null) {
            log.error("Response error object: {}", errorResponse);
            throw new ScalablePressBadRequestException(errorResponse);
        }
    }
    return responseEntity;
}

From source file:ai.eve.volley.Request.java

/**
 * Returns the raw POST or PUT body to be sent.
 * //from   w ww  .ja va 2s .  c om
 * @throws AuthFailureError
 *             in the event of auth failure
 */
public void getBody(HttpURLConnection connection) throws AuthFailureError {
    Map<String, String> params = getParams();
    if (params != null && params.size() > 0) {
        byte[] bs = encodeParameters(params, getParamsEncoding());
        try {
            if (bs != null) {
                connection.setDoOutput(true);
                connection.addRequestProperty(HTTP.CONTENT_TYPE, getBodyContentType());
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(bs);
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:HttpPOSTMIDlet.java

private String requestUsingGET(String URLString) throws IOException {
    HttpConnection hpc = null;/*from   w w  w .  j a  va 2  s .co  m*/
    DataInputStream dis = null;
    DataOutputStream dos = null;

    boolean newline = false;
    String content = "";
    try {
        hpc = (HttpConnection) Connector.open(defaultURL);
        hpc.setRequestMethod(HttpConnection.POST);
        hpc.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
        hpc.setRequestProperty("Content-Language", "zh-tw");
        hpc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        hpc.setRequestProperty("Content-Length", String.valueOf(URLString.length()));

        dos = new DataOutputStream(hpc.openOutputStream());
        dos.write(URLString.getBytes());
        dos.flush();

        InputStreamReader xdis = new InputStreamReader(hpc.openInputStream());

        int character;
        while ((character = xdis.read()) != -1) {
            if ((char) character == '\\') {
                newline = true;
                continue;
            } else {
                if ((char) character == 'n' && newline) {
                    content += "\n";
                    newline = false;
                } else if (newline) {
                    content += "\\" + (char) character;
                    newline = false;
                } else {
                    content += (char) character;
                    newline = false;
                }
            }

        }
        if (hpc != null)
            hpc.close();
        if (dis != null)
            dis.close();
    } catch (IOException e2) {
    }

    return content;
}