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.openmrs.module.odkconnector.serialization.web.PatientWebConnectorTest.java

@Test
public void serialize_shouldDisplayAllPatientInformation() throws Exception {

    // compose url
    URL u = new URL(SERVER_URL + "/module/odkconnector/download/patients.form");

    // setup http url connection
    HttpURLConnection connection = (HttpURLConnection) u.openConnection();
    connection.setDoOutput(true);/*  w w w . j  a va  2s  .  c o m*/
    connection.setRequestMethod("POST");
    connection.setConnectTimeout(10000);
    connection.setReadTimeout(10000);
    connection.addRequestProperty("Content-type", "application/octet-stream");

    // write auth details to connection
    DataOutputStream outputStream = new DataOutputStream(new GZIPOutputStream(connection.getOutputStream()));
    outputStream.writeUTF("admin");
    outputStream.writeUTF("test");
    outputStream.writeBoolean(true);
    outputStream.writeInt(2);
    outputStream.writeInt(1);
    outputStream.close();

    DataInputStream inputStream = new DataInputStream(new GZIPInputStream(connection.getInputStream()));
    Integer responseStatus = inputStream.readInt();

    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();

    int count = 0;
    byte[] buffer = new byte[1024];
    while ((count = inputStream.read(buffer)) > 0) {
        arrayOutputStream.write(buffer, 0, count);
    }
    arrayOutputStream.close();
    inputStream.close();

    File file = new File("/home/nribeka/connector.data");
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(arrayOutputStream.toByteArray());
    fos.close();

    inputStream = new DataInputStream(new FileInputStream(file));

    if (responseStatus == HttpURLConnection.HTTP_OK) {

        // total number of patients
        Integer patientCounter = inputStream.readInt();
        System.out.println("Patient Counter: " + patientCounter);
        for (int j = 0; j < patientCounter; j++) {
            System.out.println("=================Patient=====================");
            System.out.println("Patient Id: " + inputStream.readInt());
            System.out.println("Family Name: " + inputStream.readUTF());
            System.out.println("Middle Name: " + inputStream.readUTF());
            System.out.println("Last Name: " + inputStream.readUTF());
            System.out.println("Gender: " + inputStream.readUTF());
            System.out.println("Birth Date: " + inputStream.readUTF());
            System.out.println("Identifier: " + inputStream.readUTF());
            System.out.println("Patients: " + j + " out of " + patientCounter);
        }

        Integer obsCounter = inputStream.readInt();
        System.out.println("Observation Counter: " + obsCounter);
        for (int j = 0; j < obsCounter; j++) {
            System.out.println("==================Observation=================");
            System.out.println("Patient Id: " + inputStream.readInt());
            System.out.println("Concept Name: " + inputStream.readUTF());

            byte type = inputStream.readByte();
            if (type == ObsSerializer.TYPE_STRING)
                System.out.println("Value: " + inputStream.readUTF());
            else if (type == ObsSerializer.TYPE_INT)
                System.out.println("Value: " + inputStream.readInt());
            else if (type == ObsSerializer.TYPE_DOUBLE)
                System.out.println("Value: " + inputStream.readDouble());
            else if (type == ObsSerializer.TYPE_DATE)
                System.out.println("Value: " + inputStream.readUTF());
            System.out.println("Time: " + inputStream.readUTF());
            System.out.println("Obs: " + j + " out of: " + obsCounter);
        }
        Integer formCounter = inputStream.readInt();
        System.out.println("Form Counter: " + formCounter);
        for (int j = 0; j < formCounter; j++) {
            System.out.println("==================Observation=================");
            System.out.println("Patient Id: " + inputStream.readInt());
            System.out.println("Concept Name: " + inputStream.readUTF());

            byte type = inputStream.readByte();
            if (type == ObsSerializer.TYPE_STRING)
                System.out.println("Value: " + inputStream.readUTF());
            else if (type == ObsSerializer.TYPE_INT)
                System.out.println("Value: " + inputStream.readInt());
            else if (type == ObsSerializer.TYPE_DOUBLE)
                System.out.println("Value: " + inputStream.readDouble());
            else if (type == ObsSerializer.TYPE_DATE)
                System.out.println("Value: " + inputStream.readUTF());
            System.out.println("Time: " + inputStream.readUTF());
            System.out.println("Form: " + j + " out of: " + formCounter);
        }
    }
    inputStream.close();
}

From source file:net.sf.keystore_explorer.crypto.x509.X509ExtensionSet.java

/**
 * Save X.509 extension set.//  w ww  .ja  v a2 s  . c om
 *
 * @param os
 *            Stream to save to
 * @throws IOException
 *             If an I/O problem occurred
 */
public void save(OutputStream os) throws IOException {
    DataOutputStream dos = null;

    try {
        dos = new DataOutputStream(os);

        dos.writeLong(FILE_MAGIC_NUMBER);
        dos.writeInt(FILE_VERSION);

        saveExtensions(criticalExtensions, dos);
        saveExtensions(nonCriticalExtensions, dos);
    } finally {
        IOUtils.closeQuietly(dos);
    }
}

From source file:CoolBarExamples.java

private void saveState(CoolBar coolBar, File file) throws IOException {
    DataOutputStream out = new DataOutputStream(new FileOutputStream(file));

    try {/* www  .  j a va2 s.c o m*/
        // Orders of items. 
        System.out.println("Item order: " + intArrayToString(coolBar.getItemOrder()));
        int[] order = coolBar.getItemOrder();
        out.writeInt(order.length);
        for (int i = 0; i < order.length; i++)
            out.writeInt(order[i]);

        // Wrap indices.
        System.out.println("Wrap indices: " + intArrayToString(coolBar.getWrapIndices()));
        int[] wrapIndices = coolBar.getWrapIndices();
        out.writeInt(wrapIndices.length);
        for (int i = 0; i < wrapIndices.length; i++)
            out.writeInt(wrapIndices[i]);

        // Sizes. 
        Point[] sizes = coolBar.getItemSizes();
        out.writeInt(sizes.length);
        for (int i = 0; i < sizes.length; i++) {
            out.writeInt(sizes[i].x);
            out.writeInt(sizes[i].y);
        }
    } finally {
        out.close();
    }

}

From source file:org.outerrim.snippad.ui.swt.dnd.WikiTransfer.java

/**
 * Converts an array of WikiWords into a byte array.
 *
 * @param words/*w  ww . j av  a 2s. c  o  m*/
 *            Array of WikiWords
 * @return byte array representation of the WikiWord array
 */
private byte[] toByteArray(final WikiWord[] words) {
    /*
     * Transfer data is an array of words. Serialized version is: (int)
     * number of words (WikiWord) word 1 (WikiWord) word 2 ... repeat as
     * needed see writeWikiWord() for the (WikiWord) format
     */
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(byteOut);

    byte[] bytes = null;

    try {
        // write out number of markers
        LOG.debug("Writing " + words.length + " words to byte array");
        out.writeInt(words.length);

        for (int i = 0; i < words.length; ++i) {
            writeWikiWord((WikiWord) words[i], out);
        }
        out.close();
        bytes = byteOut.toByteArray();
    } catch (IOException e) {
        LOG.debug("toByteArray()", e);
        // when in doubt send nothing
    }

    return bytes;
}

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

protected void testChecksumCorruptionInternals(boolean useTags) throws IOException {
    for (Compression.Algorithm algo : COMPRESSION_ALGORITHMS) {
        for (boolean pread : new boolean[] { false, true }) {
            LOG.info("testChecksumCorruption: Compression algorithm: " + algo + ", pread=" + pread);
            Path path = new Path(TEST_UTIL.getDataTestDir(), "blocks_v2_" + algo);
            FSDataOutputStream os = fs.create(path);
            HFileContext meta = new HFileContextBuilder().withCompression(algo).withIncludesMvcc(true)
                    .withIncludesTags(useTags).withChecksumType(HFile.DEFAULT_CHECKSUM_TYPE)
                    .withBytesPerCheckSum(HFile.DEFAULT_BYTES_PER_CHECKSUM).build();
            HFileBlock.Writer hbw = new HFileBlock.Writer(null, meta);
            long totalSize = 0;
            for (int blockId = 0; blockId < 2; ++blockId) {
                DataOutputStream dos = hbw.startWriting(BlockType.DATA);
                for (int i = 0; i < 1234; ++i)
                    dos.writeInt(i);
                hbw.writeHeaderAndData(os);
                totalSize += hbw.getOnDiskSizeWithHeader();
            }/*from   w ww .j ava  2s.com*/
            os.close();

            // Use hbase checksums. 
            assertEquals(true, hfs.useHBaseChecksum());

            // Do a read that purposely introduces checksum verification failures.
            FSDataInputStreamWrapper is = new FSDataInputStreamWrapper(fs, path);
            meta = new HFileContextBuilder().withCompression(algo).withIncludesMvcc(true)
                    .withIncludesTags(useTags).withHBaseCheckSum(true).build();
            HFileBlock.FSReader hbr = new FSReaderV2Test(is, totalSize, fs, path, meta);
            HFileBlock b = hbr.readBlockData(0, -1, -1, pread);
            b.sanityCheck();
            assertEquals(4936, b.getUncompressedSizeWithoutHeader());
            assertEquals(algo == GZ ? 2173 : 4936, b.getOnDiskSizeWithoutHeader() - b.totalChecksumBytes());
            // read data back from the hfile, exclude header and checksum
            ByteBuffer bb = b.getBufferWithoutHeader(); // read back data
            DataInputStream in = new DataInputStream(
                    new ByteArrayInputStream(bb.array(), bb.arrayOffset(), bb.limit()));

            // assert that we encountered hbase checksum verification failures
            // but still used hdfs checksums and read data successfully.
            assertEquals(1, HFile.getChecksumFailuresCount());
            validateData(in);

            // A single instance of hbase checksum failure causes the reader to
            // switch off hbase checksum verification for the next 100 read
            // requests. Verify that this is correct.
            for (int i = 0; i < HFileBlock.CHECKSUM_VERIFICATION_NUM_IO_THRESHOLD + 1; i++) {
                b = hbr.readBlockData(0, -1, -1, pread);
                assertEquals(0, HFile.getChecksumFailuresCount());
            }
            // The next read should have hbase checksum verification reanabled,
            // we verify this by assertng that there was a hbase-checksum failure.
            b = hbr.readBlockData(0, -1, -1, pread);
            assertEquals(1, HFile.getChecksumFailuresCount());

            // Since the above encountered a checksum failure, we switch
            // back to not checking hbase checksums.
            b = hbr.readBlockData(0, -1, -1, pread);
            assertEquals(0, HFile.getChecksumFailuresCount());
            is.close();

            // Now, use a completely new reader. Switch off hbase checksums in 
            // the configuration. In this case, we should not detect
            // any retries within hbase. 
            HFileSystem newfs = new HFileSystem(TEST_UTIL.getConfiguration(), false);
            assertEquals(false, newfs.useHBaseChecksum());
            is = new FSDataInputStreamWrapper(newfs, path);
            hbr = new FSReaderV2Test(is, totalSize, newfs, path, meta);
            b = hbr.readBlockData(0, -1, -1, pread);
            is.close();
            b.sanityCheck();
            assertEquals(4936, b.getUncompressedSizeWithoutHeader());
            assertEquals(algo == GZ ? 2173 : 4936, b.getOnDiskSizeWithoutHeader() - b.totalChecksumBytes());
            // read data back from the hfile, exclude header and checksum
            bb = b.getBufferWithoutHeader(); // read back data
            in = new DataInputStream(new ByteArrayInputStream(bb.array(), bb.arrayOffset(), bb.limit()));

            // assert that we did not encounter hbase checksum verification failures
            // but still used hdfs checksums and read data successfully.
            assertEquals(0, HFile.getChecksumFailuresCount());
            validateData(in);
        }
    }
}

From source file:MixedRecordEnumerationExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*from  w  w w  . java  2 s. c  om*/
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
        } catch (Exception error) {
            alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            byte[] outputRecord;
            String outputString[] = { "First Record", "Second Record", "Third Record" };
            int outputInteger[] = { 15, 10, 5 };
            boolean outputBoolean[] = { true, false, true };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeBoolean(outputBoolean[x]);
                outputDataStream.writeInt(outputInteger[x]);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
            }
            outputStream.reset();
            outputStream.close();
            outputDataStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            StringBuffer buffer = new StringBuffer();
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            recordEnumeration = recordstore.enumerateRecords(null, null, false);
            while (recordEnumeration.hasNextElement()) {
                recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                buffer.append(inputDataStream.readUTF());
                buffer.append("\n");
                buffer.append(inputDataStream.readBoolean());
                buffer.append("\n");
                buffer.append(inputDataStream.readInt());
                buffer.append("\n");
                alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
            inputStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            recordstore.closeRecordStore();
        } catch (Exception error) {
            alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore.deleteRecordStore("myRecordStore");
                recordEnumeration.destroy();
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}

From source file:com.igormaznitsa.jhexed.renders.svg.SVGImage.java

public void write(final OutputStream out, final boolean zipped) throws IOException {
    final DataOutputStream dout = out instanceof DataOutputStream ? (DataOutputStream) out
            : new DataOutputStream(out);
    if (zipped) {
        final byte[] packedImage = Utils.packByteArray(this.originalNonParsedImageData);

        dout.writeInt(packedImage.length);
        dout.write(packedImage);//from  w ww. ja va2  s  . c  o m
    } else {
        dout.write(this.originalNonParsedImageData);
    }
    dout.writeBoolean(this.quality);
}

From source file:org.veronicadb.core.memorygraph.storage.SimpleLocalFileStorageSink.java

protected void writeElementLabel(DataOutputStream stream, VElement element) throws IOException {
    if (element.getLabel() == null) {
        stream.writeInt(-1);
    } else {/*w w  w  .  j av a 2s . c  om*/
        stream.writeInt(element.getLabel().length());
        stream.write(element.getLabel().getBytes());
    }
}

From source file:org.hydracache.server.data.versioning.VectorClockVersionFactory.java

@Override
public void writeObject(final Version version, final DataOutputStream dataOut) throws IOException {

    Validate.isTrue(version instanceof VectorClock, "version must be non null and an instance of VectorClock");

    Validate.notNull(dataOut, "dataOut can not be null");

    final VectorClock vectorClock = (VectorClock) version;
    final List<VectorClockEntry> vectorClockEntries = vectorClock.getEntries();

    dataOut.writeInt(vectorClockEntries.size());

    for (final VectorClockEntry vce : vectorClockEntries) {
        getIdentityMarshaller().writeObject(vce.getNodeId(), dataOut);
        dataOut.writeLong(vce.getValue());
        dataOut.writeLong(vce.getTimestamp());
    }//w  ww  .java 2s .c  o  m
}

From source file:hudson.console.ConsoleNote.java

private ByteArrayOutputStream encodeToBytes() throws IOException {
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(new GZIPOutputStream(buf));
    try {/*from  w w w.  j a v  a  2s. co m*/
        oos.writeObject(this);
    } finally {
        oos.close();
    }

    ByteArrayOutputStream buf2 = new ByteArrayOutputStream();

    DataOutputStream dos = new DataOutputStream(new Base64OutputStream(buf2, true, -1, null));
    try {
        buf2.write(PREAMBLE);
        dos.writeInt(buf.size());
        buf.writeTo(dos);
    } finally {
        dos.close();
    }
    buf2.write(POSTAMBLE);
    return buf2;
}