Example usage for java.io DataOutputStream writeInt

List of usage examples for java.io DataOutputStream writeInt

Introduction

In this page you can find the example usage for java.io DataOutputStream writeInt.

Prototype

public final void writeInt(int v) throws IOException 

Source Link

Document

Writes an int to the underlying output stream as four bytes, high byte first.

Usage

From source file:marytts.util.io.FileUtils.java

public static void writeBinaryFile(short[] x, String filename) throws IOException {
    DataOutputStream d = new DataOutputStream(new FileOutputStream(new File(filename)));

    d.writeInt(x.length);

    writeBinaryFile(x, d);/*from ww  w  .j a  va  2 s. c  o m*/
}

From source file:marytts.util.io.FileUtils.java

public static void writeBinaryFile(float[] x, String filename) throws IOException {
    DataOutputStream d = new DataOutputStream(new FileOutputStream(new File(filename)));

    d.writeInt(x.length);

    writeBinaryFile(x, d);// w  w w .  j a v a2  s. co  m
}

From source file:marytts.util.io.FileUtils.java

public static void writeBinaryFile(double[] x, String filename) throws IOException {
    DataOutputStream d = new DataOutputStream(new FileOutputStream(new File(filename)));

    d.writeInt(x.length);

    writeBinaryFile(x, d);/* w  ww . jav  a  2  s.  c  o  m*/
}

From source file:marytts.util.io.FileUtils.java

public static void writeBinaryFile(int[] x, String filename) throws IOException {
    DataOutputStream d = new DataOutputStream(new FileOutputStream(new File(filename)));

    d.writeInt(x.length);

    writeBinaryFile(x, d);/*w w w.  j  a  v  a  2 s  .co  m*/
}

From source file:org.apache.jackrabbit.core.persistence.util.Serializer.java

/**
 * Serializes the specified <code>NodeState</code> object to the given
 * binary <code>stream</code>.
 *
 * @param state  <code>state</code> to serialize
 * @param stream the stream where the <code>state</code> should be
 *               serialized to//from   w ww.  j av a  2s .com
 * @throws Exception if an error occurs during the serialization
 * @see #deserialize(NodeState, InputStream)
 */
public static void serialize(NodeState state, OutputStream stream) throws Exception {
    DataOutputStream out = new DataOutputStream(stream);

    // primaryType
    out.writeUTF(state.getNodeTypeName().toString());
    // parentUUID
    if (state.getParentId() == null) {
        out.write(NULL_UUID_PLACEHOLDER_BYTES);
    } else {
        out.write(state.getParentId().getRawBytes());
    }
    // definitionId
    out.writeUTF("");
    // mixin types
    Collection<Name> c = state.getMixinTypeNames();
    out.writeInt(c.size()); // count
    for (Iterator<Name> iter = c.iterator(); iter.hasNext();) {
        out.writeUTF(iter.next().toString()); // name
    }
    // modCount
    out.writeShort(state.getModCount());
    // properties (names)
    c = state.getPropertyNames();
    out.writeInt(c.size()); // count
    for (Iterator<Name> iter = c.iterator(); iter.hasNext();) {
        Name propName = iter.next();
        out.writeUTF(propName.toString()); // name
    }
    // child nodes (list of name/uuid pairs)
    Collection<ChildNodeEntry> collChildren = state.getChildNodeEntries();
    out.writeInt(collChildren.size()); // count
    for (Iterator<ChildNodeEntry> iter = collChildren.iterator(); iter.hasNext();) {
        ChildNodeEntry entry = iter.next();
        out.writeUTF(entry.getName().toString()); // name
        out.write(entry.getId().getRawBytes()); // uuid
    }
}

From source file:org.apache.hadoop.hbase.io.hfile.TestHFileBlock.java

static void writeTestBlockContents(DataOutputStream dos) throws IOException {
    // This compresses really well.
    for (int i = 0; i < 1000; ++i)
        dos.writeInt(i / 100);
}

From source file:org.apache.hive.hcatalog.streaming.mutate.client.AcidTableSerializer.java

/** Returns a base 64 encoded representation of the supplied {@link AcidTable}. */
public static String encode(AcidTable table) throws IOException {
    DataOutputStream data = null;
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    try {/*from   w  w w. j a  v  a 2 s .co m*/
        data = new DataOutputStream(bytes);
        data.writeUTF(table.getDatabaseName());
        data.writeUTF(table.getTableName());
        data.writeBoolean(table.createPartitions());
        if (table.getTransactionId() <= 0) {
            LOG.warn("Transaction ID <= 0. The recipient is probably expecting a transaction ID.");
        }
        data.writeLong(table.getTransactionId());
        data.writeByte(table.getTableType().getId());

        Table metaTable = table.getTable();
        if (metaTable != null) {
            byte[] thrift = new TSerializer(new TCompactProtocol.Factory()).serialize(metaTable);
            data.writeInt(thrift.length);
            data.write(thrift);
        } else {
            LOG.warn("Meta store table is null. The recipient is probably expecting an instance.");
            data.writeInt(0);
        }
    } catch (TException e) {
        throw new IOException("Error serializing meta store table.", e);
    } finally {
        data.close();
    }

    return PROLOG_V1 + new String(Base64.encodeBase64(bytes.toByteArray()), Charset.forName("UTF-8"));
}

From source file:org.jboss.as.test.integration.security.loginmodules.negotiation.Krb5ConfServerSetupTask.java

/**
 * Creates a keytab file for given principal.
 * /*w w  w  .jav  a 2  s  . c  o  m*/
 * @param principalName
 * @param passPhrase
 * @param keytabFile
 * @throws IOException
 */
public static void createKeytab(final String principalName, final String passPhrase, final File keytabFile)
        throws IOException {
    LOGGER.info("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:org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferEncryptor.java

/**
 * Factory method for clients, where the encryption token is already created.
 * //from w ww . java 2s .c o  m
 * Establishes a secure connection assuming that the party on the other end
 * has the same shared secret. This does a SASL connection handshake, but not
 * a general-purpose one. It's specific to the MD5-DIGEST SASL mechanism with
 * auth-conf enabled. In particular, it doesn't support an arbitrary number of
 * challenge/response rounds, and we know that the client will never have an
 * initial response, so we don't check for one.
 *
 * @param underlyingOut output stream to write to the other party
 * @param underlyingIn input stream to read from the other party
 * @param encryptionKey all info required to establish an encrypted stream
 * @return a pair of streams which wrap the given streams and encrypt/decrypt
 *         all data read/written
 * @throws IOException in the event of error
 */
public static IOStreamPair getEncryptedStreams(OutputStream underlyingOut, InputStream underlyingIn,
        DataEncryptionKey encryptionKey) throws IOException {

    Map<String, String> saslProps = Maps.newHashMap(SASL_PROPS);
    saslProps.put("com.sun.security.sasl.digest.cipher", encryptionKey.encryptionAlgorithm);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Client using encryption algorithm " + encryptionKey.encryptionAlgorithm);
    }

    DataOutputStream out = new DataOutputStream(underlyingOut);
    DataInputStream in = new DataInputStream(underlyingIn);

    String userName = getUserNameFromEncryptionKey(encryptionKey);
    SaslParticipant sasl = new SaslParticipant(
            Sasl.createSaslClient(new String[] { MECHANISM }, userName, PROTOCOL, SERVER_NAME, saslProps,
                    new SaslClientCallbackHandler(encryptionKey.encryptionKey, userName)));

    out.writeInt(ENCRYPTED_TRANSFER_MAGIC_NUMBER);
    out.flush();

    try {
        // Start of handshake - "initial response" in SASL terminology.
        sendSaslMessage(out, new byte[0]);

        // step 1
        performSaslStep1(out, in, sasl);

        // step 2 (client-side only)
        byte[] remoteResponse = readSaslMessage(in);
        byte[] localResponse = sasl.evaluateChallengeOrResponse(remoteResponse);
        assert localResponse == null;

        // SASL handshake is complete
        checkSaslComplete(sasl);

        return sasl.createEncryptedStreamPair(out, in);
    } catch (IOException ioe) {
        sendGenericSaslErrorMessage(out, ioe.getMessage());
        throw ioe;
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.FSImageSerialization.java

public static void writeCacheDirectiveInfo(DataOutputStream out, CacheDirectiveInfo directive)
        throws IOException {
    writeLong(directive.getId(), out);/*from  w w  w . j a  va  2 s . co m*/
    int flags = ((directive.getPath() != null) ? 0x1 : 0) | ((directive.getReplication() != null) ? 0x2 : 0)
            | ((directive.getPool() != null) ? 0x4 : 0) | ((directive.getExpiration() != null) ? 0x8 : 0);
    out.writeInt(flags);
    if (directive.getPath() != null) {
        writeString(directive.getPath().toUri().getPath(), out);
    }
    if (directive.getReplication() != null) {
        writeShort(directive.getReplication(), out);
    }
    if (directive.getPool() != null) {
        writeString(directive.getPool(), out);
    }
    if (directive.getExpiration() != null) {
        writeLong(directive.getExpiration().getMillis(), out);
    }
}