Example usage for java.io DataOutputStream writeLong

List of usage examples for java.io DataOutputStream writeLong

Introduction

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

Prototype

public final void writeLong(long v) throws IOException 

Source Link

Document

Writes a long to the underlying output stream as eight bytes, high byte first.

Usage

From source file:org.mobisocial.corral.CorralDownloadClient.java

private static String hashToString(long hash) {
    try {//  w w w  . j  ava2 s .  c  om
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);
        dos.writeLong(hash);
        dos.writeInt(-4);
        byte[] data = bos.toByteArray();
        return Base64.encodeToString(data, Base64.DEFAULT).substring(0, 11);
    } catch (IOException e) {
        return null;
    }
}

From source file:org.eclipse.swt.snippets.Snippet319.java

static byte[] convertToByteArray(MyType type) {
    DataOutputStream dataOutStream = null;
    try {/*  w w  w  . j  av  a2 s.c  om*/
        ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
        dataOutStream = new DataOutputStream(byteOutStream);
        byte[] bytes = type.name.getBytes();
        dataOutStream.writeInt(bytes.length);
        dataOutStream.write(bytes);
        dataOutStream.writeLong(type.time);
        return byteOutStream.toByteArray();
    } catch (IOException e) {
        return null;
    } finally {
        if (dataOutStream != null) {
            try {
                dataOutStream.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.google.gwt.dev.javac.CachedCompilationUnit.java

public static void save(SourceFileCompilationUnit unit, OutputStream outputStream) throws Exception {
    DataOutputStream dos = null;
    try {//from w  w w  . ja v a 2 s.c om
        dos = new DataOutputStream(new BufferedOutputStream(outputStream));
        // version
        dos.writeLong(CompilationUnitDiskCache.CACHE_VERSION);
        // simple stuff
        dos.writeLong(unit.getLastModified());
        dos.writeUTF(unit.getDisplayLocation());
        dos.writeUTF(unit.getTypeName());
        dos.writeUTF(unit.getContentId().get());
        dos.writeBoolean(unit.isSuperSource());
        // compiled classes
        {
            Collection<CompiledClass> compiledClasses = unit.getCompiledClasses();
            int size = compiledClasses.size();
            dos.writeInt(size);
            if (size > 0) {
                // sort in enclosing order to be able to restore enclosing classes by name
                CompiledClass[] compiledClassesArray = compiledClasses
                        .toArray(new CompiledClass[compiledClasses.size()]);
                Arrays.sort(compiledClassesArray, new Comparator<CompiledClass>() {
                    public int compare(CompiledClass o1, CompiledClass o2) {
                        int o1count = countMatches(o1.getInternalName(), Signature.C_DOLLAR);
                        int o2count = countMatches(o2.getInternalName(), Signature.C_DOLLAR);
                        return o1count - o2count;
                    }
                });
                // store
                for (CompiledClass compiledClass : compiledClassesArray) {
                    // internal name
                    dos.writeUTF(compiledClass.getInternalName());
                    // is local
                    dos.writeBoolean(compiledClass.isLocal());
                    // bytes
                    byte[] bytes = compiledClass.getBytes();
                    dos.writeInt(bytes.length);
                    dos.write(bytes);
                    // enclosing class, write the name only
                    CompiledClass enclosingClass = compiledClass.getEnclosingClass();
                    String enclosingClassName = enclosingClass != null ? enclosingClass.getInternalName() : "";
                    dos.writeUTF(enclosingClassName);
                }
            }
        }
        // dependencies
        {
            Set<ContentId> dependencies = unit.getDependencies();
            int size = dependencies.size();
            dos.writeInt(size);
            if (size > 0) {
                for (ContentId contentId : dependencies) {
                    dos.writeUTF(contentId.get());
                }
            }
        }
        // JSNI methods
        {
            List<JsniMethod> jsniMethods = unit.getJsniMethods();
            int size = jsniMethods.size();
            dos.writeInt(size);
            if (size > 0) {
                for (JsniMethod jsniMethod : jsniMethods) {
                    dos.writeUTF(jsniMethod.name());
                    JsFunction function = jsniMethod.function();
                    SourceInfo sourceInfo = function.getSourceInfo();
                    dos.writeInt(sourceInfo.getStartPos());
                    dos.writeInt(sourceInfo.getEndPos());
                    dos.writeInt(sourceInfo.getStartLine());
                    dos.writeUTF(function.toSource());
                }
            }
        }
        // Method lookup
        {
            MethodArgNamesLookup methodArgs = unit.getMethodArgs();
            MethodArgNamesLookup.save(methodArgs, dos);
        }
    } finally {
        IOUtils.closeQuietly(dos);
    }
}

From source file:gridool.util.xfer.TransferUtils.java

public static void send(@Nonnull final FastByteArrayOutputStream data, @Nonnull final String fileName,
        @Nullable final String writeDirPath, @Nonnull final InetAddress dstAddr, final int dstPort,
        final boolean append, final boolean sync, @Nullable final TransferClientHandler handler)
        throws IOException {
    final SocketAddress dstSockAddr = new InetSocketAddress(dstAddr, dstPort);
    SocketChannel channel = null;
    Socket socket = null;/*from w  w  w.  j a v  a2  s.com*/
    final OutputStream out;
    try {
        channel = SocketChannel.open();
        socket = channel.socket();
        socket.connect(dstSockAddr);
        out = socket.getOutputStream();
    } catch (IOException e) {
        LOG.error("failed to connect: " + dstSockAddr, e);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
        throw e;
    }

    DataInputStream din = null;
    if (sync) {
        InputStream in = socket.getInputStream();
        din = new DataInputStream(in);
    }
    final DataOutputStream dos = new DataOutputStream(out);
    final StopWatch sw = new StopWatch();
    try {
        IOUtils.writeString(fileName, dos);
        IOUtils.writeString(writeDirPath, dos);
        long nbytes = data.size();
        dos.writeLong(nbytes);
        dos.writeBoolean(append);
        dos.writeBoolean(sync);
        if (handler == null) {
            dos.writeBoolean(false);
        } else {
            dos.writeBoolean(true);
            handler.writeAdditionalHeader(dos);
        }

        // send file using zero-copy send
        data.writeTo(out);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Sent a file data '" + fileName + "' of " + nbytes + " bytes to " + dstSockAddr.toString()
                    + " in " + sw.toString());
        }

        if (sync) {// receive ack in sync mode
            long remoteRecieved = din.readLong();
            if (remoteRecieved != nbytes) {
                throw new IllegalStateException(
                        "Sent " + nbytes + " bytes, but remote node received " + remoteRecieved + " bytes");
            }
        }
    } catch (FileNotFoundException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } finally {
        IOUtils.closeQuietly(din, dos);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
    }
}

From source file:net.datenwerke.transloader.primitive.WrapperConverter.java

private static void write(Object wrapper, DataOutputStream dataStream) throws IOException {
    char typeCode = getTypeCode(wrapper);
    switch (typeCode) {
    case 'B':
        dataStream.writeByte(intValue(wrapper));
        break;/*from w  w  w .  j  a va  2  s .c om*/
    case 'C':
        dataStream.writeChar(charValue(wrapper));
        break;
    case 'S':
        dataStream.writeShort(intValue(wrapper));
        break;
    case 'I':
        dataStream.writeInt(intValue(wrapper));
        break;
    case 'J':
        dataStream.writeLong(number(wrapper).longValue());
        break;
    case 'F':
        dataStream.writeFloat(number(wrapper).floatValue());
        break;
    case 'D':
        dataStream.writeDouble(number(wrapper).doubleValue());
        break;
    case 'Z':
        dataStream.writeBoolean(booleanValue(wrapper));
    }
}

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  . c  o 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.jax.haplotype.io.SnpStreamUtil.java

/**
 * Write the snp positions as a binary file using the given base directory
 * @param chromosome// w w w  .  j ava  2s  .co  m
 *          the chromosome to write
 * @throws IOException
 *          if the write operation fails
 */
private static void writeBinarySnpPositions(StrainChromosome chromosome, DataOutputStream dataOutputStream,
        StreamDirection streamDirection) throws IOException {
    SingleNucleotidePolymorphism[] snps = chromosome.getSingleNucleotidePolymorphisms();
    dataOutputStream.write(StreamDirection.streamDirectionToByte(streamDirection));
    dataOutputStream.writeInt(chromosome.getChromosomeNumber());
    dataOutputStream.writeLong(snps[0].getPositionInBasePairs());
    dataOutputStream
            .writeLong(1L + snps[snps.length - 1].getPositionInBasePairs() - snps[0].getPositionInBasePairs());
    dataOutputStream.writeLong(snps.length);
    if (streamDirection == StreamDirection.FORWARD) {
        for (int i = 0; i < snps.length; i++) {
            dataOutputStream.writeLong(snps[i].getPositionInBasePairs());
        }
    } else {
        assert streamDirection == StreamDirection.REVERSE;
        for (int i = snps.length - 1; i >= 0; i--) {
            dataOutputStream.writeLong(snps[i].getPositionInBasePairs());
        }
    }
}

From source file:org.apache.activemq.bugs.AMQ7067Test.java

protected static XATransactionId createXATransaction() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream os = new DataOutputStream(baos);
    os.writeLong(r.nextInt());
    os.close();//from  www.  j  a  va 2s  . c o  m
    byte[] bs = baos.toByteArray();

    XATransactionId xid = new XATransactionId();
    xid.setBranchQualifier(bs);
    xid.setGlobalTransactionId(bs);
    xid.setFormatId(55);
    return xid;
}

From source file:org.hyperic.hq.measurement.agent.server.SenderThread.java

private static String encodeRecord(Record record) throws IOException {
    ByteArrayOutputStream bOs;//  w  w  w  .jav  a  2  s  .  c o  m
    DataOutputStream dOs;

    bOs = new ByteArrayOutputStream();
    dOs = new DataOutputStream(bOs);

    dOs.writeInt(record.derivedID);
    dOs.writeLong(record.data.getTimestamp());
    dOs.writeInt(record.dsnId);
    dOs.writeDouble(record.data.getValue());
    return Base64.encode(bOs.toByteArray());
}

From source file:gridool.util.xfer.TransferUtils.java

public static void sendfile(@Nonnull final File file, final long fromPos, final long count,
        @Nullable final String writeDirPath, @Nonnull final InetAddress dstAddr, final int dstPort,
        final boolean append, final boolean sync, @Nonnull final TransferClientHandler handler)
        throws IOException {
    if (!file.exists()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " does not exist");
    }/*from w  w  w.j  a  v  a2  s.  co m*/
    if (!file.isFile()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " is not file");
    }
    if (!file.canRead()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " cannot read");
    }

    final SocketAddress dstSockAddr = new InetSocketAddress(dstAddr, dstPort);
    SocketChannel channel = null;
    Socket socket = null;
    final OutputStream out;
    try {
        channel = SocketChannel.open();
        socket = channel.socket();
        socket.connect(dstSockAddr);
        out = socket.getOutputStream();
    } catch (IOException e) {
        LOG.error("failed to connect: " + dstSockAddr, e);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
        throw e;
    }

    DataInputStream din = null;
    if (sync) {
        InputStream in = socket.getInputStream();
        din = new DataInputStream(in);
    }
    final DataOutputStream dos = new DataOutputStream(out);
    final StopWatch sw = new StopWatch();
    FileInputStream src = null;
    final long nbytes;
    try {
        src = new FileInputStream(file);
        FileChannel fc = src.getChannel();

        String fileName = file.getName();
        IOUtils.writeString(fileName, dos);
        IOUtils.writeString(writeDirPath, dos);
        long xferBytes = (count == -1L) ? fc.size() : count;
        dos.writeLong(xferBytes);
        dos.writeBoolean(append); // append=false
        dos.writeBoolean(sync);
        if (handler == null) {
            dos.writeBoolean(false);
        } else {
            dos.writeBoolean(true);
            handler.writeAdditionalHeader(dos);
        }

        // send file using zero-copy send
        nbytes = fc.transferTo(fromPos, xferBytes, channel);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sent a file '" + file.getAbsolutePath() + "' of " + nbytes + " bytes to "
                    + dstSockAddr.toString() + " in " + sw.toString());
        }

        if (sync) {// receive ack in sync mode
            long remoteRecieved = din.readLong();
            if (remoteRecieved != xferBytes) {
                throw new IllegalStateException(
                        "Sent " + xferBytes + " bytes, but remote node received " + remoteRecieved + " bytes");
            }
        }

    } catch (FileNotFoundException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } finally {
        IOUtils.closeQuietly(src);
        IOUtils.closeQuietly(din, dos);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
    }
}