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.prorefactor.refactor.PUB.java

private void writeExportSegment(DataOutputStream out, List rootSymbols) throws IOException {
    for (Iterator it = rootSymbols.iterator(); it.hasNext();) {
        Symbol symbol = (Symbol) it.next();
        if (symbol.isExported())
            writeSymbol(out, symbol);//from  w w w  .j av  a2s. c  om
    }
    out.writeInt(-1);
    out.writeUTF("");
}

From source file:org.prorefactor.refactor.PUB.java

private void writeImportSegment(DataOutputStream out, List rootSymbols) throws IOException {
    for (Iterator it = rootSymbols.iterator(); it.hasNext();) {
        Symbol symbol = (Symbol) it.next();
        if (symbol.isImported())
            writeSymbol(out, symbol);/*from  www .  j  ava 2s .com*/
    }
    out.writeInt(-1);
    out.writeUTF("");
}

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

/**
 * Serializes a <code>PropertyState</code> to the data output stream
 *
 * @param out the output stream/* w w w  . j  a va  2s  . c o m*/
 * @param state the property entry to store
 * @throws IOException if an I/O error occurs.
 */
public void writeState(DataOutputStream out, NodePropBundle.PropertyEntry state) throws IOException {
    // type & mod count
    out.writeInt(state.getType() | (state.getModCount() << 16));
    // multiValued
    out.writeBoolean(state.isMultiValued());
    // definitionId
    out.writeUTF(state.getPropDefId().toString());
    // values
    InternalValue[] values = state.getValues();
    out.writeInt(values.length); // count
    for (int i = 0; i < values.length; i++) {
        InternalValue val = values[i];
        switch (state.getType()) {
        case PropertyType.BINARY:
            try {
                long size = val.getLength();
                if (dataStore != null) {
                    int maxMemorySize = dataStore.getMinRecordLength() - 1;
                    if (size < maxMemorySize) {
                        writeSmallBinary(out, val, state, i);
                    } else {
                        out.writeInt(BINARY_IN_DATA_STORE);
                        val.store(dataStore);
                        out.writeUTF(val.toString());
                    }
                    break;
                }
                // special handling required for binary value:
                // spool binary value to file in blob store
                if (size < 0) {
                    log.warn("Blob has negative size. Potential loss of data. " + "id={} idx={}", state.getId(),
                            String.valueOf(i));
                    out.writeInt(0);
                    values[i] = InternalValue.create(new byte[0]);
                    val.discard();
                } else if (size > minBlobSize) {
                    out.writeInt(BINARY_IN_BLOB_STORE);
                    String blobId = state.getBlobId(i);
                    if (blobId == null) {
                        try {
                            InputStream in = val.getStream();
                            try {
                                blobId = blobStore.createId(state.getId(), i);
                                blobStore.put(blobId, in, size);
                                state.setBlobId(blobId, i);
                            } finally {
                                IOUtils.closeQuietly(in);
                            }
                        } catch (Exception e) {
                            String msg = "Error while storing blob. id=" + state.getId() + " idx=" + i
                                    + " size=" + size;
                            log.error(msg, e);
                            throw new IOException(msg);
                        }
                        try {
                            // replace value instance with value
                            // backed by resource in blob store and delete temp file
                            if (blobStore instanceof ResourceBasedBLOBStore) {
                                values[i] = InternalValue
                                        .create(((ResourceBasedBLOBStore) blobStore).getResource(blobId));
                            } else {
                                values[i] = InternalValue.create(blobStore.get(blobId));
                            }
                        } catch (Exception e) {
                            log.error("Error while reloading blob. truncating. id=" + state.getId() + " idx="
                                    + i + " size=" + size, e);
                            values[i] = InternalValue.create(new byte[0]);
                        }
                        val.discard();
                    }
                    // store id of blob as property value
                    out.writeUTF(blobId); // value
                } else {
                    // delete evt. blob
                    byte[] data = writeSmallBinary(out, val, state, i);
                    // replace value instance with value
                    // backed by resource in blob store and delete temp file
                    values[i] = InternalValue.create(data);
                    val.discard();
                }
            } catch (RepositoryException e) {
                String msg = "Error while storing blob. id=" + state.getId() + " idx=" + i + " value=" + val;
                log.error(msg, e);
                throw new IOException(msg);
            }
            break;
        case PropertyType.DOUBLE:
            try {
                out.writeDouble(val.getDouble());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing DOUBLE value.");
            }
            break;
        case PropertyType.DECIMAL:
            try {
                writeDecimal(out, val.getDecimal());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing DECIMAL value.");
            }
            break;
        case PropertyType.LONG:
            try {
                out.writeLong(val.getLong());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing LONG value.");
            }
            break;
        case PropertyType.BOOLEAN:
            try {
                out.writeBoolean(val.getBoolean());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing BOOLEAN value.");
            }
            break;
        case PropertyType.NAME:
            try {
                writeQName(out, val.getName());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing NAME value.");
            }
            break;
        case PropertyType.WEAKREFERENCE:
        case PropertyType.REFERENCE:
            writeID(out, val.getNodeId());
            break;
        default:
            // because writeUTF(String) has a size limit of 64k,
            // we're using write(byte[]) instead
            byte[] bytes = val.toString().getBytes("UTF-8");
            out.writeInt(bytes.length); // length of byte[]
            out.write(bytes); // byte[]
        }
    }
}

From source file:runtime.starter.MPJRun.java

private void pack(int nProcesses, int start_rank, Socket sockClient) {

    if (wdir == null) {
        wdir = System.getProperty("user.dir");
    }/*from ww  w.  j a  v  a 2s.c om*/

    MPJProcessTicket ticket = new MPJProcessTicket();
    ticket.setMpjHomeDir(mpjHomeDir);
    ticket.setClassPath(new String(urlArray));
    ticket.setProcessCount(nProcesses);
    ticket.setStartingRank(start_rank);
    ticket.setWorkingDirectory(wdir);
    ticket.setUserID(System.getProperty("user.name"));
    if (this.zippedSource) {
        String zipFileName = UUID.randomUUID() + ".zip";
        this.sourceFolder = wdir;
        IOHelper.zipFolder(this.sourceFolder, zipFileName);
        byte[] zipContents = IOHelper.ReadBinaryFile(zipFileName);
        String encodedString = Base64.encodeBase64String(zipContents);
        ticket.setSourceCode(encodedString);
        IOHelper.deleteFile(zipFileName);
        ticket.setZippedSource(true);
    }
    ticket.setMainClass(className);
    ticket.setConfFileContents(CONF_FILE_CONTENTS);
    ticket.setDeviceName(deviceName);
    IOMessagesThread ioMessages = new IOMessagesThread(sockClient);
    ioMessages.start();
    ArrayList<String> jvmArgs = new ArrayList<String>();
    for (int j = 0; j < jArgs.length; j++) {
        jvmArgs.add(jArgs[j]);
    }
    ticket.setJvmArgs(jvmArgs);

    ArrayList<String> appArgs = new ArrayList<String>();
    for (int j = 0; j < aArgs.length; j++) {
        appArgs.add(aArgs[j]);
    }
    ticket.setAppArgs(appArgs);

    if (deviceName.equals("hybdev")) {
        ticket.setNetworkProcessCount(networkProcesscount);
        ticket.setTotalProcessCount(nprocs);
        ticket.setNetworkDevice(networkDevice);
    }

    if (ADEBUG) {
        ticket.setDebug(true);
        ticket.setDebugPort(DEBUG_PORT);
    }

    if (APROFILE) {
        ticket.setProfiler(true);
    }
    String ticketString = ticket.ToXML().toXmlString();
    OutputStream outToServer = null;
    try {
        outToServer = sockClient.getOutputStream();
    } catch (IOException e) {
        logger.info(" Unable to get deamon stream-");
        e.printStackTrace();
    }
    DataOutputStream out = new DataOutputStream(outToServer);

    try {
        int length = ticketString.getBytes().length;
        out.writeInt(length);
        if (DEBUG && logger.isDebugEnabled()) {
            logger.info("Machine Name: " + sockClient.getInetAddress().getHostName() + " Startting Rank: "
                    + ticket.getStartingRank() + " Process Count: " + ticket.getProcessCount());
        }
        out.write(ticketString.getBytes(), 0, length);
        out.flush();
    } catch (IOException e) {

        logger.info(" Unable to write on deamon stream-");
        e.printStackTrace();
    }
}

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

/**
 * Serializes a <code>PropertyState</code> to the data output stream
 *
 * @param out the output stream//from   w  ww  .  j  a va  2s.  c om
 * @param state the property entry to store
 * @throws IOException if an I/O error occurs.
 */
public void writeState(DataOutputStream out, NodePropBundle.PropertyEntry state) throws IOException {
    // type & mod count
    out.writeInt(state.getType() | (state.getModCount() << 16));
    // multiValued
    out.writeBoolean(state.isMultiValued());
    // definitionId
    out.writeUTF(state.getPropDefId().toString());
    // values
    InternalValue[] values = state.getValues();
    out.writeInt(values.length); // count
    for (int i = 0; i < values.length; i++) {
        InternalValue val = values[i];
        switch (state.getType()) {
        case PropertyType.BINARY:
            try {
                long size = val.getLength();
                if (dataStore != null) {
                    int maxMemorySize = dataStore.getMinRecordLength() - 1;
                    if (size < maxMemorySize) {
                        writeSmallBinary(out, val, state, i);
                    } else {
                        out.writeInt(BINARY_IN_DATA_STORE);
                        val.store(dataStore);
                        out.writeUTF(val.toString());
                    }
                    break;
                }
                // special handling required for binary value:
                // spool binary value to file in blob store
                if (size < 0) {
                    log.warn("Blob has negative size. Potential loss of data. " + "id={} idx={}", state.getId(),
                            String.valueOf(i));
                    out.writeInt(0);
                    values[i] = InternalValue.create(new byte[0]);
                    val.discard();
                } else if (size > minBlobSize) {
                    out.writeInt(BINARY_IN_BLOB_STORE);
                    String blobId = state.getBlobId(i);
                    if (blobId == null) {
                        try {
                            InputStream in = val.getStream();
                            try {
                                blobId = blobStore.createId(state.getId(), i);
                                blobStore.put(blobId, in, size);
                                state.setBlobId(blobId, i);
                            } finally {
                                IOUtils.closeQuietly(in);
                            }
                        } catch (Exception e) {
                            String msg = "Error while storing blob. id=" + state.getId() + " idx=" + i
                                    + " size=" + size;
                            log.error(msg, e);
                            throw new IOException(msg);
                        }
                        try {
                            // replace value instance with value
                            // backed by resource in blob store and delete temp file
                            if (blobStore instanceof ResourceBasedBLOBStore) {
                                values[i] = InternalValue
                                        .create(((ResourceBasedBLOBStore) blobStore).getResource(blobId));
                            } else {
                                values[i] = InternalValue.create(blobStore.get(blobId));
                            }
                        } catch (Exception e) {
                            log.error("Error while reloading blob. truncating. id=" + state.getId() + " idx="
                                    + i + " size=" + size, e);
                            values[i] = InternalValue.create(new byte[0]);
                        }
                        val.discard();
                    }
                    // store id of blob as property value
                    out.writeUTF(blobId); // value
                } else {
                    // delete evt. blob
                    byte[] data = writeSmallBinary(out, val, state, i);
                    // replace value instance with value
                    // backed by resource in blob store and delete temp file
                    values[i] = InternalValue.create(data);
                    val.discard();
                }
            } catch (RepositoryException e) {
                String msg = "Error while storing blob. id=" + state.getId() + " idx=" + i + " value=" + val;
                log.error(msg, e);
                throw new IOException(msg);
            }
            break;
        case PropertyType.DOUBLE:
            try {
                out.writeDouble(val.getDouble());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing DOUBLE value.");
            }
            break;
        case PropertyType.DECIMAL:
            try {
                writeDecimal(out, val.getDecimal());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing DECIMAL value.");
            }
            break;
        case PropertyType.LONG:
            try {
                out.writeLong(val.getLong());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing LONG value.");
            }
            break;
        case PropertyType.BOOLEAN:
            try {
                out.writeBoolean(val.getBoolean());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing BOOLEAN value.");
            }
            break;
        case PropertyType.NAME:
            try {
                writeQName(out, val.getName());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing NAME value.");
            }
            break;
        case PropertyType.WEAKREFERENCE:
        case PropertyType.REFERENCE:
            writeUUID(out, val.getUUID());
            break;
        default:
            // because writeUTF(String) has a size limit of 64k,
            // we're using write(byte[]) instead
            byte[] bytes = val.toString().getBytes("UTF-8");
            out.writeInt(bytes.length); // length of byte[]
            out.write(bytes); // byte[]
        }
    }
}

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

private void writeUint32(DataOutputStream out, long l) throws IOException {
    out.writeInt((int) l);
}

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

/**
 * Creates a keytab file for given principal.
 *
 * @param principalName//from  w  ww.  ja v a 2 s  . com
 * @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:org.apache.hadoop.hbase.io.hfile.TestHFileBlock.java

private long writeBlocks(Random rand, Compression.Algorithm compressAlgo, Path path, List<Long> expectedOffsets,
        List<Long> expectedPrevOffsets, List<BlockType> expectedTypes, List<ByteBuffer> expectedContents)
        throws IOException {
    boolean cacheOnWrite = expectedContents != null;
    FSDataOutputStream os = fs.create(path);
    HFileContext meta = new HFileContextBuilder().withHBaseCheckSum(true).withIncludesMvcc(includesMemstoreTS)
            .withIncludesTags(includesTag).withCompression(compressAlgo)
            .withBytesPerCheckSum(HFile.DEFAULT_BYTES_PER_CHECKSUM)
            .withChecksumType(HFile.DEFAULT_CHECKSUM_TYPE).build();
    HFileBlock.Writer hbw = new HFileBlock.Writer(null, meta);
    Map<BlockType, Long> prevOffsetByType = new HashMap<BlockType, Long>();
    long totalSize = 0;
    for (int i = 0; i < NUM_TEST_BLOCKS; ++i) {
        long pos = os.getPos();
        int blockTypeOrdinal = rand.nextInt(BlockType.values().length);
        if (blockTypeOrdinal == BlockType.ENCODED_DATA.ordinal()) {
            blockTypeOrdinal = BlockType.DATA.ordinal();
        }/*  w w  w  .j  a  v a 2s. c o m*/
        BlockType bt = BlockType.values()[blockTypeOrdinal];
        DataOutputStream dos = hbw.startWriting(bt);
        int size = rand.nextInt(500);
        for (int j = 0; j < size; ++j) {
            // This might compress well.
            dos.writeShort(i + 1);
            dos.writeInt(j + 1);
        }

        if (expectedOffsets != null)
            expectedOffsets.add(os.getPos());

        if (expectedPrevOffsets != null) {
            Long prevOffset = prevOffsetByType.get(bt);
            expectedPrevOffsets.add(prevOffset != null ? prevOffset : -1);
            prevOffsetByType.put(bt, os.getPos());
        }

        expectedTypes.add(bt);

        hbw.writeHeaderAndData(os);
        totalSize += hbw.getOnDiskSizeWithHeader();

        if (cacheOnWrite)
            expectedContents.add(hbw.getUncompressedBufferWithHeader());

        if (detailedLogging) {
            LOG.info("Written block #" + i + " of type " + bt + ", uncompressed size "
                    + hbw.getUncompressedSizeWithoutHeader() + " at offset " + pos);
        }
    }
    os.close();
    LOG.info("Created a temporary file at " + path + ", " + fs.getFileStatus(path).getLen()
            + " byte, compression=" + compressAlgo);
    return totalSize;
}

From source file:org.apache.hadoop.io.TestArrayOutputStream.java

private void runComparison(ArrayOutputStream aos, DataOutputStream dos, ByteArrayOutputStream bos)
        throws IOException {
    Random r = new Random();
    // byte//from ww w.  ja v a 2 s .c om
    int b = r.nextInt(128);
    aos.write(b);
    dos.write(b);

    // byte[]
    byte[] bytes = new byte[10];
    r.nextBytes(bytes);
    aos.write(bytes, 0, 10);
    dos.write(bytes, 0, 10);

    // Byte
    aos.writeByte(b);
    dos.writeByte(b);

    // boolean
    boolean bool = r.nextBoolean();
    aos.writeBoolean(bool);
    dos.writeBoolean(bool);

    // short
    short s = (short) r.nextInt();
    aos.writeShort(s);
    dos.writeShort(s);

    // char
    int c = r.nextInt();
    aos.writeChar(c);
    dos.writeChar(c);

    // int
    int i = r.nextInt();
    aos.writeInt(i);
    dos.writeInt(i);

    // long
    long l = r.nextLong();
    aos.writeLong(l);
    dos.writeLong(l);

    // float
    float f = r.nextFloat();
    aos.writeFloat(f);
    dos.writeFloat(f);

    // double
    double d = r.nextDouble();
    aos.writeDouble(d);
    dos.writeDouble(d);

    // strings
    String str = RandomStringUtils.random(20);
    aos.writeBytes(str);
    aos.writeChars(str);
    aos.writeUTF(str);
    dos.writeBytes(str);
    dos.writeChars(str);
    dos.writeUTF(str);

    byte[] expected = bos.toByteArray();
    assertEquals(expected.length, aos.size());

    byte[] actual = new byte[aos.size()];
    System.arraycopy(aos.getBytes(), 0, actual, 0, actual.length);
    // serialized bytes should be the same
    assertTrue(Arrays.equals(expected, actual));
}

From source file:org.openxdata.server.service.impl.FormDownloadServiceImpl.java

@Override
public void submitForms(InputStream is, OutputStream os, String serializerName) {
    //When submitting data, we need all the form versions and not just the default ones
    //because the user can change the default form version which already has data on
    //mobile devices. So getting all versions shields us from such problems.
    List<FormData> formDataList = new ArrayList<FormData>();
    User user = userService.getLoggedInUser();
    XformSerializer formSerializer = serializationService.getFormSerializer(serializerName);
    Map<Integer, String> formsVersionXmlMap = getFormsVersionXmlMap();
    List<String> xforms = (List<String>) formSerializer.deSerialize(is, formsVersionXmlMap);
    if (xforms == null || xforms.size() == 0) {
        throw new UnexpectedException("Problem encountered while deserializing data.");
    }/*from  w  ww .  jav  a  2  s . com*/
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        for (String xml : xforms) {
            Document doc = db.parse(IOUtils.toInputStream(xml, "UTF-8"));
            Integer formId = Integer
                    .valueOf(doc.getDocumentElement().getAttribute(OpenXDataConstants.ATTRIBUTE_NAME_FORMID));
            String descTemplate = doc.getDocumentElement()
                    .getAttribute(OpenXDataConstants.ATTRIBUTE_NAME_DESCRIPTION_TEMPLATE);
            FormData formData = saveFormData(formId, xml,
                    XmlUtil.getDescriptionTemplate(doc.getDocumentElement(), descTemplate), user, new Date());
            formDataList.add(formData);
        }
        // serialize the summaries
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeByte(formDataList.size());
        for (FormData fd : formDataList) {
            String description = fd.getDescription();
            if (description != null) {
                dos.writeUTF(description);
            } else {
                dos.writeUTF("form {" + fd.getFormDefVersionId() + "}"); // description can be null
            }
            dos.writeInt(fd.getFormDataId());
        }
    } catch (ParserConfigurationException ex) {
        throw new UnexpectedException(ex);
    } catch (SAXException ex) {
        throw new UnexpectedException(ex);
    } catch (IOException ex) {
        throw new UnexpectedException(ex);
    }
}