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:org.csc.phynixx.loggersystem.logrecord.XADataLogger.java

/**
 *
 *
 * @param dataRecorder//from   w w w  .ja v  a 2s .  c o m
 *            DataRecorder that uses /operates on the current physical
 *            logger
 *
 * @param message
 *            message to be written
 * @throws IOException
 */
void writeData(PhynixxXADataRecorder dataRecorder, IDataRecord message) throws IOException {
    DataOutputStream io = null;
    try {

        ByteArrayOutputStream byteIO = new ByteArrayOutputStream(HEADER_SIZE);
        io = new DataOutputStream(byteIO);

        io.writeLong(message.getXADataRecorderId());
        io.writeInt(message.getOrdinal().intValue());
        byte[] header = byteIO.toByteArray();

        byte[][] data = message.getData();
        byte[][] content = null;
        if (data == null) {
            content = new byte[][] { header };
        } else {
            content = new byte[data.length + 1][];
            content[0] = header;
            for (int i = 0; i < data.length; i++) {
                content[i + 1] = data[i];
            }
        }

        try {
            this.dataLogger.write(message.getLogRecordType().getType(), content);
        } catch (Exception e) {
            throw new DelegatedRuntimeException(
                    "writing message " + message + "\n" + ExceptionUtils.getStackTrace(e), e);
        }
    } finally {
        if (io != null) {
            io.close();
        }
    }

    // Add the messageSequence to the set og messageSequences ...
}

From source file:me.cybermaxke.merchants.v16r3.SMerchant.java

@Override
public boolean addCustomer(Player player) {
    checkNotNull(player, "player");

    if (this.customers.add(player)) {
        EntityPlayer player0 = ((CraftPlayer) player).getHandle();
        Container container0 = null;

        try {/*www  .j av  a2  s .  c  o m*/
            container0 = new SContainerMerchant(player0, this);
            container0 = CraftEventFactory.callInventoryOpenEvent(player0, container0);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (container0 == null) {
            this.customers.remove(player);
            return false;
        }

        int window = player0.nextContainerCounter();

        player0.activeContainer = container0;
        player0.activeContainer.windowId = window;
        player0.activeContainer.addSlotListener(player0);

        // Open the window
        player0.playerConnection.sendPacket(new Packet100OpenWindow(window, 6, this.sendTitle, 3, true));

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);

        try {
            // Write the window id
            dos.writeInt(window);
            // Write the offers
            this.offers.a(dos);
            // Flush and close data stream
            dos.flush();
            dos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Send the offers
        player0.playerConnection.sendPacket(new Packet250CustomPayload("MC|TrList", baos.toByteArray()));
        return true;
    }

    return false;
}

From source file:org.carbondata.processing.util.LevelSortIndexWriterThread.java

private void writeUpdatedLevelFile() throws IOException {
    DataOutputStream dataOutputStream = null;
    try {/*from w  w w . j av a2s  . c  om*/
        int lastIndexOf = levelFilePath.lastIndexOf(".level");
        String path = levelFilePath.substring(0, lastIndexOf);

        dataOutputStream = FileFactory.getDataOutputStream(
                path + CarbonCommonConstants.LEVEL_SORT_INDEX_FILE_EXT, FileFactory.getFileType(path));

        dataOutputStream.writeInt(sortOrderIndex.length);
        for (int i = 0; i < sortOrderIndex.length; i++) {
            dataOutputStream.writeInt(sortOrderIndex[i]);
        }
        dataOutputStream.writeInt(sortReverseOrderIndex.length);
        for (int i = 0; i < sortReverseOrderIndex.length; i++) {
            dataOutputStream.writeInt(sortReverseOrderIndex[i]);
        }
    } catch (IOException e) {
        LOGGER.error(e, "problem while writing the level sort index file");
        throw e;
    } finally {
        CarbonUtil.closeStreams(dataOutputStream);
    }
}

From source file:org.sakaiproject.util.serialize.Type1BaseResourcePropertiesSerializer.java

/**
 * @see org.sakaiproject.entity.api.serialize.DataStreamEntitySerializer#serialize(org.sakaiproject.entity.api.serialize.SerializableEntity,
 *      java.io.DataOutputStream)/* ww w. j ava2s .c  om*/
 */
public void serialize(SerializableEntity se, DataOutputStream ds) throws EntityParseException {
    if (!(se instanceof SerializablePropertiesAccess)) {
        throw new EntityParseException("Cant serialize " + se + " as it is not a SerializableProperties ");
    }
    SerializablePropertiesAccess sp = (SerializablePropertiesAccess) se;
    Map<String, Object> properties = sp.getSerializableProperties();
    try {
        ds.writeInt(TYPE1);
        ds.writeInt(BLOCK1);
        int ps = properties.keySet().size();
        for (Iterator<String> i = properties.keySet().iterator(); i.hasNext();) {
            if (i.next() == null) {
                ps--;
            }
        }
        ds.writeInt(ps);
        for (Entry<String, Object> entry : properties.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value != null) {
                if (value instanceof String) {
                    ds.writeInt(BLOCK2);
                    ds.writeUTF(key);
                    ds.writeUTF((String) value);
                } else if (value instanceof List) {
                    ds.writeInt(BLOCK3);
                    ds.writeUTF(key);
                    List<?> l = (List<?>) value;
                    int s = l.size();
                    for (Iterator<?> il = l.iterator(); il.hasNext();) {
                        if (il.next() == null) {
                            s--;
                        }
                    }
                    ds.writeInt(s);
                    for (Iterator<?> il = l.iterator(); il.hasNext();) {
                        Object v = il.next();
                        if (v != null) {
                            if (v instanceof String) {
                                ds.writeUTF((String) v);
                            } else {
                                log.warn("Non String found in property list " + v);
                            }
                        }
                    }
                } else {
                    log.warn("Non String found in property " + value);
                }
            }
        }
    } catch (Exception ex) {
        throw new EntityParseException("Failed to serialize properties ", ex);
    }

}

From source file:org.apache.hadoop.security.SaslRpcClient.java

/**
 * Do client side SASL authentication with server via the given InputStream
 * and OutputStream/*from   w w  w.j ava 2s .com*/
 * 
 * @param inS
 *          InputStream to use
 * @param outS
 *          OutputStream to use
 * @return true if connection is set up, or false if needs to switch 
 *             to simple Auth.
 * @throws IOException
 */
public boolean saslConnect(InputStream inS, OutputStream outS) throws IOException {
    DataInputStream inStream = new DataInputStream(new BufferedInputStream(inS));
    DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(outS));

    try {
        byte[] saslToken = new byte[0];
        if (saslClient.hasInitialResponse())
            saslToken = saslClient.evaluateChallenge(saslToken);
        if (saslToken != null) {
            outStream.writeInt(saslToken.length);
            outStream.write(saslToken, 0, saslToken.length);
            outStream.flush();
            if (LOG.isDebugEnabled())
                LOG.debug("Have sent token of size " + saslToken.length + " from initSASLContext.");
        }
        if (!saslClient.isComplete()) {
            readStatus(inStream);
            int len = inStream.readInt();
            if (len == SaslRpcServer.SWITCH_TO_SIMPLE_AUTH) {
                if (LOG.isDebugEnabled())
                    LOG.debug("Server asks us to fall back to simple auth.");
                saslClient.dispose();
                return false;
            }
            saslToken = new byte[len];
            if (LOG.isDebugEnabled())
                LOG.debug("Will read input token of size " + saslToken.length
                        + " for processing by initSASLContext");
            inStream.readFully(saslToken);
        }

        while (!saslClient.isComplete()) {
            saslToken = saslClient.evaluateChallenge(saslToken);
            if (saslToken != null) {
                if (LOG.isDebugEnabled())
                    LOG.debug("Will send token of size " + saslToken.length + " from initSASLContext.");
                outStream.writeInt(saslToken.length);
                outStream.write(saslToken, 0, saslToken.length);
                outStream.flush();
            }
            if (!saslClient.isComplete()) {
                readStatus(inStream);
                saslToken = new byte[inStream.readInt()];
                if (LOG.isDebugEnabled())
                    LOG.debug("Will read input token of size " + saslToken.length
                            + " for processing by initSASLContext");
                inStream.readFully(saslToken);
            }
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("SASL client context established. Negotiated QoP: "
                    + saslClient.getNegotiatedProperty(Sasl.QOP));
        }
        return true;
    } catch (IOException e) {
        try {
            saslClient.dispose();
        } catch (SaslException ignored) {
            // ignore further exceptions during cleanup
        }
        throw e;
    }
}

From source file:org.wso2.carbon.mediator.cache.digest.HttpRequestHashGenerator.java

/**
 * This is an overloaded method for the digest generation for OMElement.
 *
 * @param element         - OMElement to be subjected to the key generation
 * @param digestAlgorithm - digest algorithm as a String
 * @return byte[] representing the calculated digest over the provided element
 * @throws CachingException if there is an io error or the specified algorithm is incorrect
 *//*from  www.ja v a  2  s. c o  m*/
public byte[] getDigest(OMElement element, String toAddress, Map<String, String> headers,
        String digestAlgorithm) throws CachingException {
    byte[] digest = new byte[0];

    try {

        MessageDigest md = MessageDigest.getInstance(digestAlgorithm);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.writeInt(1);
        dos.write(getExpandedName(element).getBytes(charsetName));
        dos.write((byte) 0);
        dos.write((byte) 0);

        dos.write(toAddress.getBytes(charsetName));
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                dos.write(getDigest(entry.getKey(), entry.getValue(), digestAlgorithm));
            }
        }

        Collection attrs = getAttributesWithoutNS(element);
        dos.writeInt(attrs.size());

        Iterator itr = attrs.iterator();
        while (itr.hasNext()) {
            dos.write(getDigest((OMAttribute) itr.next(), digestAlgorithm));
        }
        OMNode node = element.getFirstOMChild();

        // adjoining Texts are merged,
        // there is  no 0-length Text, and
        // comment nodes are removed.
        int length = 0;
        itr = element.getChildElements();
        while (itr.hasNext()) {
            length++;
            itr.next();
        }
        dos.writeInt(length);

        while (node != null) {
            dos.write(getDigest(node, toAddress, headers, digestAlgorithm));
            node = node.getNextOMSibling();
        }
        dos.close();
        md.update(baos.toByteArray());

        digest = md.digest();

    } catch (NoSuchAlgorithmException e) {
        handleException(
                "Can not locate the algorithm " + "provided for the digest generation : " + digestAlgorithm, e);
    } catch (IOException e) {
        handleException("Error in calculating the " + "digest value for the OMElement : " + element, e);
    }

    return digest;
}

From source file:cn.ac.ncic.mastiff.io.coding.DeltaBinaryPackingStringReader.java

@Override
public byte[] ensureDecompressed() throws IOException {
    System.out.println("280    inBuf.length   " + inBuf.getLength());
    FlexibleEncoding.Parquet.DeltaByteArrayReader reader = new FlexibleEncoding.Parquet.DeltaByteArrayReader();
    DataOutputBuffer transfer = new DataOutputBuffer();
    transfer.write(inBuf.getData(), 12, inBuf.getLength() - 12);
    byte[] data = transfer.getData();
    System.out.println("286   byte [] data  " + data.length + "  numPairs  " + numPairs);
    inBuf.close();/*w  ww.  j a va  2  s  .  c om*/
    Binary[] bin = new Utils().readData(reader, data, numPairs);
    System.out.println("2998   Binary[] bin   " + bin.length);
    ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
    DataOutputStream dos1 = new DataOutputStream(bos1);
    ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
    DataOutputStream dos2 = new DataOutputStream(bos2);
    //    DataOutputBuffer   decoding = new DataOutputBuffer();
    //    DataOutputBuffer   offset = new DataOutputBuffer();
    dos1.writeInt(decompressedSize);
    dos1.writeInt(numPairs);
    dos1.writeInt(startPos);
    int dataoffset = 12;
    String str;
    for (int i = 0; i < numPairs; i++) {
        str = bin[i].toStringUsingUTF8();
        dos1.writeUTF(str);
        dataoffset = dos1.size();
        dos2.writeInt(dataoffset);
    }
    System.out.println("315  offset.size() " + bos2.size() + "  decoding.szie   " + bos2.toByteArray().length);
    System.out.println("316  dataoffet   " + dataoffset);
    dos1.write(bos2.toByteArray(), 0, bos2.size());
    inBuf.close();
    System.out.println("316   bos1  " + bos1.toByteArray().length + "    " + bos1.size());
    byte[] bytes = bos1.toByteArray();
    dos2.close();
    bos2.close();
    bos1.close();
    dos1.close();
    return bytes;
}

From source file:org.carbondata.processing.globalsurrogategenerator.LevelGlobalSurrogateGeneratorThread.java

private void writeGlobalSurrogateKeyFile(String string, int[] key, int[] value, String fileName,
        int currentMaxKey, int minValue) {
    DataOutputStream stream = null;
    try {//from w w  w .jav a 2 s  .c  o  m
        stream = FileFactory.getDataOutputStream(string + '/' + fileName,
                FileFactory.getFileType(string + '/' + fileName), 10240);
        int size = key.length;
        stream.writeInt(currentMaxKey);
        stream.writeInt(minValue);
        stream.writeInt(size);
        for (int i = 0; i < size; i++) {
            stream.writeInt(key[i]);
            stream.writeInt(value[i]);
        }
    } catch (FileNotFoundException e) {
        LOGGER.error(e, e.getMessage());
    } catch (IOException e) {
        LOGGER.error(e, e.getMessage());
    } finally {
        CarbonUtil.closeStreams(stream);
    }
}

From source file:ubic.basecode.io.ByteArrayConverter.java

/**
 * @param iarray//  ww w .  j  a  va 2 s. co m
 * @return byte[]
 */
public byte[] intArrayToBytes(int[] iarray) {
    if (iarray == null)
        return null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    try {
        for (int element : iarray) {
            dos.writeInt(element);
        }
        dos.close();
        bos.close();
    } catch (IOException e) {
        // do nothing
    }
    return bos.toByteArray();
}

From source file:com.linkedin.pinot.core.common.datatable.DataTableImplV2.java

private byte[] serializeMetadata() throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);

    dataOutputStream.writeInt(_metadata.size());
    for (Entry<String, String> entry : _metadata.entrySet()) {
        byte[] keyBytes = entry.getKey().getBytes(UTF_8);
        dataOutputStream.writeInt(keyBytes.length);
        dataOutputStream.write(keyBytes);

        byte[] valueBytes = entry.getValue().getBytes(UTF_8);
        dataOutputStream.writeInt(valueBytes.length);
        dataOutputStream.write(valueBytes);
    }/*from w ww .  j av a2 s. c  o m*/

    return byteArrayOutputStream.toByteArray();
}