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.apache.jmeter.protocol.mqtt.client.MqttPublisher.java

private byte[] createBigVolume(String useTimeStamp, String useNumberSeq, String format, String charset,
        String sizeArray) throws IOException, NumberFormatException {
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    DataOutputStream d = new DataOutputStream(b);
    // flags     
    byte flags = 0x00;
    if ("TRUE".equals(useTimeStamp))
        flags |= 0x80;//ww  w. j a v  a 2  s .c o m
    if ("TRUE".equals(useNumberSeq))
        flags |= 0x40;
    d.writeByte(flags);
    // TimeStamp
    if ("TRUE".equals(useTimeStamp)) {
        Date date = new java.util.Date();
        d.writeLong(date.getTime());
    }
    // Number Sequence
    if ("TRUE".equals(useNumberSeq)) {
        d.writeInt(numSeq++);

    }
    int size = Integer.parseInt(sizeArray);
    byte[] content = new byte[size];

    for (int i = 0; i < size; i++) {
        content[i] = (byte) (i % 10);
    }
    d.write(content);
    // Format: Encoding        
    if (MQTTPublisherGui.BINARY.equals(format)) {
        BinaryCodec encoder = new BinaryCodec();
        return encoder.encode(b.toByteArray());
    } else if (MQTTPublisherGui.BASE64.equals(format)) {
        return Base64.encodeBase64(b.toByteArray());
    } else if (MQTTPublisherGui.BINHEX.equals(format)) {
        Hex encoder = new Hex();
        return encoder.encode(b.toByteArray());
    } else if (MQTTPublisherGui.PLAIN_TEXT.equals(format)) {
        String s = new String(b.toByteArray(), charset);
        return s.getBytes();

    } else

        return b.toByteArray();

}

From source file:org.mhisoft.wallet.service.AttachmentService.java

/**
 * Read the attachments from the old attachment store and write to the new attachment store.
 * It is really copy attachments from one store to another.
 * use case: export, change password;//from ww  w . j av a2 s.c o  m
 *     store version change
 *
 *     DELETED   entries are not transfered.
 *
 * @param oldStoreName      The old store name, needed to read the attachment content out.
 * @param model             The old model, need the encryptor from it to read old attachment for transfer.
 * @param expModel          the new store model, items list is from the new model.
 * @param expModelEncryptor The encryptor for writing the new attachment store.
 * @param resetModelAttachmentEntries  do not reset for upgrade scenario.
 */

public boolean transferAttachmentStore(final String oldStoreName, String newStoreName, final WalletModel model,
        final WalletModel expModel, final PBEEncryptor expModelEncryptor,
        final boolean resetModelAttachmentEntries) {

    logger.fine("transferAttachmentStore()");

    File newFile = new File(newStoreName);
    if (newFile.exists()) {
        if (!newFile.delete()) {
            DialogUtils.getInstance().error("Can't delete the tmp file:" + newStoreName);
            return false;
        }
    }

    FileAccessTable t = new FileAccessTable();
    double deleteCount = 0, totalCount = 0;
    for (WalletItem item : expModel.getItemsFlatList()) {
        if (item.getAttachmentEntry() != null) {
            totalCount++;

            if (item.getAttachmentEntry().getAccessFlag() == FileAccessFlag.Delete
                    || item.getAttachmentEntry().getAccessFlag() == FileAccessFlag.Update)
                //these are new deleted attachments
                deleteCount++;
            else if (item.getAttachmentEntry().getFileName() != null)
                t.addEntry(item.getAttachmentEntry());

        }

    }

    //delete count need to add the orphan records (marked as DELETE) in the attachment store.
    deleteCount += expModel.getDeletedEntriesInStore();

    if (deleteCount == totalCount) {
        //all deleted or updated.
        //nothing new need to be transfered.
        return false;
    }

    DataOutputStream dataOut = null;
    if (t.getSize() > 0) {
        //new store
        //write it out
        try {
            dataOut = new DataOutputStream(new FileOutputStream(new File(newStoreName)));

            //write the total number of entries first
            /*#0*/
            dataOut.writeInt(t.getEntries().size());
            //itemStartPos = 4;

            writeFileEntries(expModel, true, oldStoreName, 4, dataOut, t, model.getEncryptorForRead(),
                    expModelEncryptor);

            dataOut.flush();
            dataOut.close();

        } catch (IOException e) {
            e.printStackTrace();
            DialogUtils.getInstance().error("transferAttachmentStore failed:", e.getMessage());
        } finally {
            if (dataOut != null)
                try {
                    dataOut.close();
                } catch (IOException e) {
                    //e.printStackTrace();
                }
        }

    }

    if (resetModelAttachmentEntries) {
        //now clear the access flag on the item
        for (WalletItem item : model.getItemsFlatList()) {
            if (item.getAttachmentEntry() != null && item.getAttachmentEntry().getFile() != null //
                    && item.getAttachmentEntry().getAccessFlag() != null) {
                item.getAttachmentEntry().setAccessFlag(FileAccessFlag.None);
            }
        }
    }

    return t.getSize() > 0;

}

From source file:com.linkedin.pinot.common.utils.DataTable.java

/**
 * Serialize the data table into a byte-array, as per the specified serialization.
 *
 * @param version Format version to use for serialization.
 * @return Serialized byte-array/*from w ww.  j av  a  2s .  c  o  m*/
 * @throws Exception
 */
public byte[] toBytes(Version version) throws Exception {
    final byte[] dictionaryBytes = serializeDictionary();
    final byte[] metadataBytes = serializeMetadata();
    byte[] schemaBytes = new byte[0];
    if (schema != null) {
        schemaBytes = schema.toBytes();
    }
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final DataOutputStream out = new DataOutputStream(baos);
    // TODO: convert this format into a proper class
    // VERSION|NUM_ROW|NUM_COL|(START|SIZE) -- START|SIZE 5 PAIRS FOR
    // DICTIONARY, METADATA,
    // SCHEMA, DATATABLE, VARIABLE DATA BUFFER --> 4 + 4 + 4 + 5*8 = 52
    // bytes

    out.writeInt(version.getValue());
    out.writeInt(numRows);
    out.writeInt(numCols);
    // dictionary
    int baseOffset = 52;
    out.writeInt(baseOffset);
    out.writeInt(dictionaryBytes.length);
    baseOffset += dictionaryBytes.length;

    // metadata
    out.writeInt(baseOffset);
    out.writeInt(metadataBytes.length);
    baseOffset += metadataBytes.length;

    // schema
    out.writeInt(baseOffset);
    out.writeInt(schemaBytes.length);
    baseOffset += schemaBytes.length;

    // datatable
    out.writeInt(baseOffset);
    if (fixedSizeDataBytes == null) {
        out.writeInt(0);
    } else {
        out.writeInt(fixedSizeDataBytes.length);
        baseOffset += fixedSizeDataBytes.length;
    }

    // variable data
    out.writeInt(baseOffset);
    if (variableSizeDataBytes == null) {
        out.writeInt(0);
    } else {
        out.writeInt(variableSizeDataBytes.length);
    }

    // write them
    out.write(dictionaryBytes);
    out.write(metadataBytes);
    out.write(schemaBytes);
    if (fixedSizeDataBytes != null) {
        out.write(fixedSizeDataBytes);
    }
    if (variableSizeDataBytes != null) {
        out.write(variableSizeDataBytes);
    }
    byte[] byteArray = baos.toByteArray();
    long end = System.currentTimeMillis();
    return byteArray;
}

From source file:org.openymsg.network.HTTPConnectionHandler.java

/**
 * The only time Yahoo can actually send us any packets is when we send it some. Yahoo encodes its packets in a POST
 * body - the format is the same binary representation used for direct connections (with one or two extra codes).
 * /* ww  w  .j a  va 2 s  . c o  m*/
 * After posting a packet, the connection will receive a HTTP response who's payload consists of four bytes followed
 * by zero or more packets. The first byte of the four is a count of packets encoded in the following body.
 * 
 * Each incoming packet is transfered to a queue, where receivePacket() takes them off - thus preserving the effect
 * that input and output packets are being received independently, as with other connection handlers. As
 * readPacket() can throw an exception, these are caught and transfered onto the queue too, then rethrown by
 * receivePacket() .
 */
@Override
synchronized void sendPacket(PacketBodyBuffer body, ServiceType service, long status, long sessionID)
        throws IOException, IllegalStateException {
    if (!connected)
        throw new IllegalStateException("Not logged in");

    if (filterOutput(body, service))
        return;
    byte[] b = body.getBuffer();

    Socket soc = new Socket(proxyHost, proxyPort);
    PushbackInputStream pbis = new PushbackInputStream(soc.getInputStream());
    DataOutputStream dos = new DataOutputStream(soc.getOutputStream());

    // HTTP header
    dos.writeBytes(HTTP_HEADER_POST);
    dos.writeBytes("Content-length: " + (b.length + NetworkConstants.YMSG9_HEADER_SIZE) + NetworkConstants.END);
    dos.writeBytes(HTTP_HEADER_AGENT);
    dos.writeBytes(HTTP_HEADER_HOST);
    if (HTTP_HEADER_PROXY_AUTH != null)
        dos.writeBytes(HTTP_HEADER_PROXY_AUTH);
    if (cookie != null)
        dos.writeBytes("Cookie: " + cookie + NetworkConstants.END);
    dos.writeBytes(NetworkConstants.END);
    // YMSG9 header
    dos.write(NetworkConstants.MAGIC, 0, 4);
    dos.write(NetworkConstants.VERSION_HTTP, 0, 4);
    dos.writeShort(b.length & 0xffff);
    dos.writeShort(service.getValue() & 0xffff);
    dos.writeInt((int) (status & 0xffffffff));
    dos.writeInt((int) (sessionID & 0xffffffff));
    // YMSG9 body
    dos.write(b, 0, b.length);
    dos.flush();

    // HTTP response header
    String s = readLine(pbis);
    if (s == null || s.indexOf(" 200 ") < 0) // Not "HTTP/1.0 200 OK"
    {
        throw new IOException("HTTP request returned didn't return OK (200): " + s);
    }
    while (s != null && s.trim().length() > 0)
        // Read past header
        s = readLine(pbis);
    // Payload count
    byte[] code = new byte[4];
    int res = pbis.read(code, 0, 4); // Packet count (Little-Endian?)
    if (res < 4) {
        throw new IOException("Premature end of HTTP data");
    }
    int count = code[0];
    // Payload body
    YMSG9InputStream yip = new YMSG9InputStream(pbis);
    YMSG9Packet pkt;
    for (int i = 0; i < count; i++) {
        pkt = yip.readPacket();
        if (!filterInput(pkt)) {
            if (!packets.add(pkt)) {
                throw new IllegalArgumentException("Unable to add data to the packetQueue!");
            }
        }
    }

    soc.close();

    // Reset idle timeout
    lastFetch = System.currentTimeMillis();
}

From source file:org.apache.hadoop.ipc.chinamobile.Server.java

/**
 * Setup response for the IPC Call.//from  ww w.ja v a  2  s  .c o  m
 * 
 * @param response buffer to serialize the response into
 * @param call {@link Call} to which we are setting up the response
 * @param status {@link Status} of the IPC call
 * @param rv return value for the IPC Call, if the call was successful
 * @param errorClass error class, if the the call failed
 * @param error error message, if the call failed
 * @throws IOException
 */
private void setupResponse(ByteArrayOutputStream response, Call call, Status status, Writable rv,
        String errorClass, String error) throws IOException {
    response.reset();
    DataOutputStream out = new DataOutputStream(response);
    out.writeInt(call.id); // write call id
    out.writeInt(status.state); // write status

    if (status == Status.SUCCESS) {
        rv.write(out);
    } else {
        WritableUtils.writeString(out, errorClass);
        WritableUtils.writeString(out, error);
    }
    call.setResponse(ByteBuffer.wrap(response.toByteArray()));
}

From source file:eu.stratosphere.nephele.ipc.Server.java

/**
 * Setup response for the IPC Call./*from  w w w .ja va2  s.c  o  m*/
 * 
 * @param response
 *        buffer to serialize the response into
 * @param call
 *        {@link Call} to which we are setting up the response
 * @param status
 *        {@link Status} of the IPC call
 * @param rv
 *        return value for the IPC Call, if the call was successful
 * @param errorClass
 *        error class, if the the call failed
 * @param error
 *        error message, if the call failed
 * @throws IOException
 */
private void setupResponse(ByteArrayOutputStream response, Call call, Status status, IOReadableWritable rv,
        String errorClass, String error) throws IOException {
    response.reset();
    DataOutputStream out = new DataOutputStream(response);
    out.writeInt(call.id); // write call id
    out.writeInt(status.state); // write status

    if (status == Status.SUCCESS) {
        if (rv == null) {
            out.writeBoolean(false);
        } else {
            out.writeBoolean(true);
            StringRecord.writeString(out, rv.getClass().getName());
            rv.write(out);
        }

    } else {
        StringRecord.writeString(out, errorClass);
        StringRecord.writeString(out, error);
    }
    call.setResponse(ByteBuffer.wrap(response.toByteArray()));
}

From source file:org.apache.fontbox.ttf.TTFSubsetter.java

private long writeTableHeader(DataOutputStream out, String tag, long offset, byte[] bytes) throws IOException {
    long checksum = 0;
    for (int nup = 0, n = bytes.length; nup < n; nup++) {
        checksum += (bytes[nup] & 0xffL) << 24 - nup % 4 * 8;
    }// w w  w .ja  v  a  2s.  com
    checksum &= 0xffffffffL;

    byte[] tagbytes = tag.getBytes("US-ASCII");

    out.write(tagbytes, 0, 4);
    out.writeInt((int) checksum);
    out.writeInt((int) offset);
    out.writeInt(bytes.length);

    // account for the checksum twice, once for the header field, once for the content itself
    return toUInt32(tagbytes) + checksum + checksum + offset + bytes.length;
}

From source file:org.apache.flink.runtime.ipc.Server.java

/**
 * Setup response for the IPC Call./*from  www. java2s  . c  om*/
 * 
 * @param response
 *        buffer to serialize the response into
 * @param call
 *        {@link Call} to which we are setting up the response
 * @param status
 *        {@link Status} of the IPC call
 * @param rv
 *        return value for the IPC Call, if the call was successful
 * @param errorClass
 *        error class, if the the call failed
 * @param error
 *        error message, if the call failed
 * @throws IOException
 */
private void setupResponse(ByteArrayOutputStream response, Call call, Status status, IOReadableWritable rv,
        String errorClass, String error) throws IOException {
    response.reset();
    DataOutputStream out = new DataOutputStream(response);
    out.writeInt(call.id); // write call id
    out.writeInt(status.state); // write status

    if (status == Status.SUCCESS) {
        if (rv == null) {
            out.writeBoolean(false);
        } else {
            out.writeBoolean(true);
            StringRecord.writeString(out, rv.getClass().getName());
            rv.write(new OutputViewDataOutputStreamWrapper(out));
        }

    } else {
        StringRecord.writeString(out, errorClass);
        StringRecord.writeString(out, error);
    }
    call.setResponse(ByteBuffer.wrap(response.toByteArray()));
}

From source file:MersenneTwisterFast.java

/** Writes the entire state of the MersenneTwister RNG to the stream
 *  @param stream output stream/*from  w  w  w  .  j a  v  a  2  s.c o m*/
 *  @throws IOException exception from stream reading
 */
public void writeState(DataOutputStream stream) throws IOException {
    int len = mt.length;
    for (int x = 0; x < len; x++)
        stream.writeInt(mt[x]);

    len = mag01.length;
    for (int x = 0; x < len; x++)
        stream.writeInt(mag01[x]);

    stream.writeInt(mti);
    stream.writeDouble(__nextNextGaussian);
    stream.writeBoolean(__haveNextNextGaussian);
}

From source file:IndexService.IndexServer.java

public boolean setindexstatus(String indexloc, int status) {
    if (!testmode) {
        Path indexpath = new Path(indexloc);
        try {// ww  w.  j  av a2 s  .  co  m
            String dbname = indexpath.getParent().getParent().getName();
            if (dbname.endsWith(".db")) {
                dbname = dbname.substring(0, dbname.lastIndexOf(".db"));
            }
            return db.setIndexStatus(dbname, indexpath.getParent().getName(), indexpath.getName(), status);
        } catch (HiveException e1) {
            e1.printStackTrace();
            return false;
        }
    } else {
        try {
            ArrayList<IndexItemStatus> statuss = new ArrayList<IndexItemStatus>();
            File file = new File("indexconf");
            boolean exist = false;
            if (file.exists()) {
                DataInputStream dis = new DataInputStream(new FileInputStream(file));
                int num = dis.readInt();
                for (int i = 0; i < num; i++) {
                    IndexItemStatus itemstatus = new IndexItemStatus();
                    itemstatus.read(dis);
                    if (itemstatus.indexlocation.equals(indexloc)) {
                        itemstatus.status = status;
                        exist = true;
                    }
                    statuss.add(itemstatus);
                }
                dis.close();

                DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
                dos.writeInt(statuss.size());
                for (IndexItemStatus indexItemStatus : statuss) {
                    indexItemStatus.write(dos);
                }
                dos.close();
            }
            if (exist)
                return true;
            return false;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}