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:hd3gtv.embddb.network.DataBlock.java

byte[] getBytes(Protocol protocol) throws IOException {
    checkIfNotEmpty();//www . j  a  v  a  2 s.  com

    ByteArrayOutputStream byte_array_out_stream = new ByteArrayOutputStream(Protocol.BUFFER_SIZE);

    DataOutputStream dos = new DataOutputStream(byte_array_out_stream);
    dos.write(Protocol.APP_SOCKET_HEADER_TAG);
    dos.writeInt(Protocol.VERSION);

    /**
     * Start header name
     */
    dos.writeByte(0);
    byte[] request_name_data = request_name.getBytes(Protocol.UTF8);
    dos.writeInt(request_name_data.length);
    dos.write(request_name_data);

    /**
     * Start datas payload
     */
    dos.writeByte(1);

    /**
     * Get datas from zip
     */
    ZipOutputStream zos = new ZipOutputStream(dos);
    zos.setLevel(3);
    entries.forEach(entry -> {
        try {
            entry.toZip(zos);
        } catch (IOException e) {
            log.error("Can't add to zip", e);
        }
    });
    zos.flush();
    zos.finish();
    zos.close();

    dos.flush();
    dos.close();

    byte[] result = byte_array_out_stream.toByteArray();

    if (log.isTraceEnabled()) {
        log.trace("Make raw datas for " + request_name + Hexview.LINESEPARATOR + Hexview.tracelog(result));
    }

    return result;
}

From source file:net.sheehantech.cherry.ProtocolTest.java

private byte[] expectedEnhanced(byte command, int identifier, int expiryTime, byte[] deviceToken,
        byte[] payload) {
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    DataOutputStream dataStream = new DataOutputStream(byteStream);
    try {/*from w  ww.  j  a  va 2  s  . c  o  m*/
        dataStream.writeByte(command);
        dataStream.writeInt(identifier);
        dataStream.writeInt(expiryTime);
        dataStream.writeShort(deviceToken.length);
        dataStream.write(deviceToken);
        dataStream.writeShort(payload.length);
        dataStream.write(payload);
        return byteStream.toByteArray();
    } catch (final IOException e) {
        throw new AssertionError();
    }
}

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

public void writeData(DataOutputStream output) throws IOException {
    PacketUtil.writeString(output, (AddonPacket.getPacketId(packet.getClass())));
    output.writeInt(data.length);/*w w  w . j a v a  2 s . co m*/
    output.writeBoolean(compressed);
    output.write(data);
}

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

@Override
public Element generateContentProtection(Document d) throws IOException {
    Element e = super.generateContentProtection(d);

    switch (cpType) {

    case CENC://w ww .j a va  2s . co m
        e.appendChild(generateCENCContentProtectionData(d));
        break;

    case MSPRO:
        Element pro = d.createElement(MSPRO_ELEMENT);

        // Generate base64-encoded PRO
        ByteBuffer ba = ByteBuffer.allocate(4);
        ba.order(ByteOrder.LITTLE_ENDIAN);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);

        // PlayReady Header Object Size field
        ba.putInt(0, proSize);
        dos.write(ba.array());

        // Number of Records field
        ba.putShort(0, (short) wrmHeaders.size());
        dos.write(ba.array(), 0, 2);

        for (WRMHeader header : wrmHeaders) {

            byte[] wrmData = header.getWRMHeaderData();

            // Record Type (always 1 for WRM Headers)
            ba.putShort(0, (short) 1);
            dos.write(ba.array(), 0, 2);

            // Record Length
            ba.putShort(0, (short) wrmData.length);
            dos.write(ba.array(), 0, 2);

            // Data
            dos.write(wrmData);
        }

        pro.setTextContent(Base64.encodeBase64String(baos.toByteArray()));

        e.appendChild(pro);
        break;
    }

    return e;
}

From source file:org.apache.hadoop.registry.client.binding.JsonSerDeser.java

/**
 * Write the json as bytes -then close the file
 * @param dataOutputStream an outout stream that will always be closed
 * @throws IOException on any failure//from w w  w  .  ja  v a  2  s.co m
 */
private void writeJsonAsBytes(T instance, DataOutputStream dataOutputStream) throws IOException {
    try {
        byte[] b = toBytes(instance);
        dataOutputStream.write(b);
    } finally {
        dataOutputStream.close();
    }
}

From source file:com.netflix.aegisthus.tools.StorageHelper.java

public void logCommit(String file) throws IOException {
    Path log = commitPath(getTaskId());
    if (debug) {//from   www .  jav  a  2 s. c  o m
        LOG.info(String.format("logging (%s) to commit log (%s)", file, log.toUri().toString()));
    }
    FileSystem fs = log.getFileSystem(config);
    DataOutputStream os = null;
    if (fs.exists(log)) {
        os = fs.append(log);
    } else {
        os = fs.create(log);
    }
    os.writeBytes(file);
    os.write('\n');
    os.close();
}

From source file:com.vimc.ahttp.HurlWorker.java

private void writeDataEnd(DataOutputStream out, String boundary) throws IOException {
    out.write(LINE_END.getBytes());
    byte[] end_data = (TWO_HYPHENS + boundary + TWO_HYPHENS + LINE_END).getBytes();
    out.write(end_data);/*from w w w  . j  a  v a  2  s .co m*/
}

From source file:org.jboss.as.test.integration.security.common.AbstractKrb5ConfServerSetupTask.java

/**
 * Creates a keytab file for given principal.
 *
 * @param principalName/*from   ww w .  ja  va2s. co m*/
 * @param passPhrase
 * @param keytabFile
 * @throws IOException
 */
protected void createKeytab(final String principalName, final String passPhrase, final File keytabFile)
        throws IOException {
    LOGGER.trace("Principal name: " + principalName);
    final KerberosTime timeStamp = new KerberosTime();

    DataOutputStream dos = null;
    try {
        dos = new DataOutputStream(new FileOutputStream(keytabFile));
        dos.write(Keytab.VERSION_0X502_BYTES);

        for (Map.Entry<EncryptionType, EncryptionKey> keyEntry : KerberosKeyFactory
                .getKerberosKeys(principalName, passPhrase).entrySet()) {
            final EncryptionKey key = keyEntry.getValue();
            final byte keyVersion = (byte) key.getKeyVersion();
            // entries.add(new KeytabEntry(principalName, principalType, timeStamp, keyVersion, key));

            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream entryDos = new DataOutputStream(baos);
            // handle principal name
            String[] spnSplit = principalName.split("@");
            String nameComponent = spnSplit[0];
            String realm = spnSplit[1];

            String[] nameComponents = nameComponent.split("/");
            try {
                // increment for v1
                entryDos.writeShort((short) nameComponents.length);
                entryDos.writeUTF(realm);
                // write components
                for (String component : nameComponents) {
                    entryDos.writeUTF(component);
                }

                entryDos.writeInt(1); // principal type: KRB5_NT_PRINCIPAL
                entryDos.writeInt((int) (timeStamp.getTime() / 1000));
                entryDos.write(keyVersion);

                entryDos.writeShort((short) key.getKeyType().getValue());

                byte[] data = key.getKeyValue();
                entryDos.writeShort((short) data.length);
                entryDos.write(data);
            } finally {
                IOUtils.closeQuietly(entryDos);
            }
            final byte[] entryBytes = baos.toByteArray();
            dos.writeInt(entryBytes.length);
            dos.write(entryBytes);
        }
        // } catch (IOException ioe) {
    } finally {
        IOUtils.closeQuietly(dos);
    }
}

From source file:com.formkiq.core.equifax.service.EquifaxServiceImpl.java

/**
 * Sends request to Equifax.//from   w w w.ja v  a 2 s . c  o  m
 * @param server {@link String}
 * @param send {@link String}
 * @return {@link String}
 * @throws IOException IOException
 */
public String sendToEquifax(final String server, final String send) throws IOException {

    String params = "InputSegments=" + URLEncoder.encode(send, "UTF-8") + "&cmdSubmit=Submit";

    byte[] postData = params.getBytes(StandardCharsets.UTF_8);
    int postDataLength = postData.length;

    URL url = new URL(server);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setInstanceFollowRedirects(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    conn.setRequestProperty("charset", "utf-8");
    conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
    conn.setUseCaches(false);

    Reader in = null;
    DataOutputStream wr = null;

    try {
        wr = new DataOutputStream(conn.getOutputStream());
        wr.write(postData);

        StringBuilder sb = new StringBuilder();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        for (int c = in.read(); c != -1; c = in.read()) {
            sb.append((char) c);
        }

        String receive = sb.toString();

        return receive;

    } finally {

        if (in != null) {
            in.close();
        }

        if (wr != null) {
            wr.close();
        }
    }
}

From source file:de.hybris.platform.cuppytrail.impl.DefaultSecureTokenService.java

@Override
public String encryptData(final SecureToken data) {
    if (data == null || StringUtils.isBlank(data.getData())) {
        throw new IllegalArgumentException("missing token");
    }//from  w  ww .  ja v a2s . c o m
    try {
        final SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM);
        final int[] paddingSizes = computePaddingLengths(random);

        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        final DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
        dataOutputStream.write(generatePadding(paddingSizes[0], random));
        dataOutputStream.writeUTF(data.getData());
        dataOutputStream.writeUTF(createChecksum(data.getData()));
        dataOutputStream.writeLong(data.getTimeStamp());
        dataOutputStream.write(generatePadding(paddingSizes[1], random));

        dataOutputStream.flush();
        final byte[] unsignedDataBytes = byteArrayOutputStream.toByteArray();

        final byte[] md5SigBytes = generateSignature(unsignedDataBytes, 0, unsignedDataBytes.length,
                signatureKeyBytes);
        byteArrayOutputStream.write(md5SigBytes);
        byteArrayOutputStream.flush();

        final byte[] signedDataBytes = byteArrayOutputStream.toByteArray();

        return encrypt(signedDataBytes, encryptionKeyBytes, random);
    } catch (final IOException e) {
        LOG.error("Could not encrypt", e);
        throw new SystemException(e.toString(), e);
    } catch (final GeneralSecurityException e) {
        LOG.error("Could not encrypt", e);
        throw new SystemException(e.toString(), e);
    }
}