Java Code Examples for java.io.DataOutputStream#writeInt()

The following examples show how to use java.io.DataOutputStream#writeInt() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jeecg   File: MsgConnect.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * .
 * 
 * @return byte[]
 */
public byte[] toByteArry() {
	ByteArrayOutputStream bous = new ByteArrayOutputStream();
	DataOutputStream dous = new DataOutputStream(bous);
	try {
		dous.writeInt(this.getTotalLength());
		dous.writeInt(this.getCommandId());
		dous.writeInt(this.getSequenceId());
		MsgUtils.writeString(dous, this.sourceAddr, 6);
		dous.write(authenticatorSource);
		dous.writeByte(0x30);
		dous.writeInt(Integer.parseInt(MsgUtils.getTimestamp()));
		dous.close();
	} catch (IOException e) {
		logger.error("封装链接二进制数组失败。");
	}
	return bous.toByteArray();
}
 
Example 2
Source Project: incubator-pinot   File: NumberUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void addToDataOutputStream(DataOutputStream dataOutputStream, Number value,
    MetricType type) throws IOException {
  switch (type) {
  case SHORT:
    dataOutputStream.writeShort(value.shortValue());
    break;
  case INT:
    dataOutputStream.writeInt(value.intValue());
    break;
  case LONG:
    dataOutputStream.writeLong(value.longValue());
    break;
  case FLOAT:
    dataOutputStream.writeFloat(value.floatValue());
    break;
  case DOUBLE:
    dataOutputStream.writeDouble(value.doubleValue());
    break;
  }
}
 
Example 3
Source Project: httpclient-android   File: PRNGFixes.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generates a device- and invocation-specific seed to be mixed into the
 * Linux PRNG.
 */
private static byte[] generateSeed() {
    try {
        ByteArrayOutputStream seedBuffer = new ByteArrayOutputStream();
        DataOutputStream seedBufferOut =
                new DataOutputStream(seedBuffer);
        seedBufferOut.writeLong(System.currentTimeMillis());
        seedBufferOut.writeLong(System.nanoTime());
        seedBufferOut.writeInt(Process.myPid());
        seedBufferOut.writeInt(Process.myUid());
        seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_SERIAL);
        seedBufferOut.close();
        return seedBuffer.toByteArray();
    } catch (IOException e) {
        throw new SecurityException("Failed to generate seed", e);
    }
}
 
Example 4
/**
 * This method allows us to store a package image into a persistent stream easily
 * thus allowing us to store the image in RMS.
 * 
 * @return a byte array that can be loaded using the load method
 */
public byte[] toByteArray() {
    try {
        ByteArrayOutputStream array = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(array);
        out.writeShort(width);
        out.writeShort(height);
        out.writeByte(palette.length);
        int plen = palette.length;
        for (int iter = 0; iter < plen; iter++) {
            out.writeInt(palette[iter]);
        }
        out.write(imageDataByte);
        out.close();
        return array.toByteArray();
    } catch (IOException ex) {
        // will never happen since IO is purely in memory
        ex.printStackTrace();
        return null;
    }
}
 
Example 5
Source Project: fluo   File: SerializedSplits.java    License: Apache License 2.0 6 votes vote down vote up
private static byte[] serializeInternal(List<Bytes> splits) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  GZIPOutputStream gzOut = new GZIPOutputStream(baos);
  BufferedOutputStream bos = new BufferedOutputStream(gzOut, 1 << 16);
  DataOutputStream dos = new DataOutputStream(bos);

  dos.writeInt(splits.size());
  for (Bytes split : splits) {
    dos.writeInt(split.length());
    split.writeTo(dos);
  }

  dos.close();

  return baos.toByteArray();
}
 
Example 6
public void write(DataOutputStream out) throws IOException {
    if (value instanceof String) {
        out.writeByte(CONSTANT_UTF8);
        out.writeUTF((String) value);
    } else if (value instanceof Integer) {
        out.writeByte(CONSTANT_INTEGER);
        out.writeInt(((Integer) value).intValue());
    } else if (value instanceof Float) {
        out.writeByte(CONSTANT_FLOAT);
        out.writeFloat(((Float) value).floatValue());
    } else if (value instanceof Long) {
        out.writeByte(CONSTANT_LONG);
        out.writeLong(((Long) value).longValue());
    } else if (value instanceof Double) {
        out.writeDouble(CONSTANT_DOUBLE);
        out.writeDouble(((Double) value).doubleValue());
    } else {
        throw new InternalError("bogus value entry: " + value);
    }
}
 
Example 7
Source Project: Java   File: DataStreamDemo.java    License: Artistic License 2.0 6 votes vote down vote up
private static void write() throws IOException {
	// DataOutputStream(OutputStream out)
	DataOutputStream dos = new DataOutputStream(new FileOutputStream(
			"dos.txt"));

	// ���
	dos.writeByte(1);
	dos.writeShort(10);
	dos.writeInt(100);
	dos.writeLong(1000);
	dos.writeFloat(1.1f);
	dos.writeDouble(2.2);
	dos.writeChar('a');
	dos.writeBoolean(true);

	// �ͷ���Դ
	dos.close();
}
 
Example 8
@Override
public void saveScreenState(DataOutputStream dos) throws IOException {
	Toc toc = Toc.read(game.getFileIO().readPrivateFile("library/toc.xml"), game.getFileIO());
	TocEntry[] entries = toc.getEntries();
	int index = findTocEntryIndex(entries, tocEntry.getName(), 0);
	if (index < 0) {
		index = 0;
	}
	dos.writeInt(index);		 
	dos.writeInt(currentFilter == null ? 0 : currentFilter.length());
	if (currentFilter != null) {
		dos.writeChars(currentFilter);
	}
	dos.writeInt(yPosition);

}
 
Example 9
Source Project: Bytecoder   File: JSR_W.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Dump instruction as byte code to stream out.
 * @param out Output stream
 */
@Override
public void dump( final DataOutputStream out ) throws IOException {
    super.setIndex(getTargetOffset());
    out.writeByte(super.getOpcode());
    out.writeInt(super.getIndex());
}
 
Example 10
/**
 * {@inheritDoc}
 */
public void writeWire(final DataOutputStream out) throws IOException {

   super.writeWire(out);
   SerializerUtils.writeAddress(representative, out);
   SerializerUtils.writeString(clusterName, out);

   out.writeBoolean(operationalCluster);
   out.writeInt(markerListSize);
}
 
Example 11
/** Writes the entire state of the MersenneTwister RNG to the stream */
public synchronized 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);
    }
 
Example 12
Source Project: flink   File: SavepointV2Serializer.java    License: Apache License 2.0 5 votes vote down vote up
private static void serializeSubtaskState(OperatorSubtaskState subtaskState, DataOutputStream dos) throws IOException {

		dos.writeLong(-1);

		int len = 0;
		dos.writeInt(len);

		OperatorStateHandle operatorStateBackend = extractSingleton(subtaskState.getManagedOperatorState());

		len = operatorStateBackend != null ? 1 : 0;
		dos.writeInt(len);
		if (len == 1) {
			serializeOperatorStateHandle(operatorStateBackend, dos);
		}

		OperatorStateHandle operatorStateFromStream = extractSingleton(subtaskState.getRawOperatorState());

		len = operatorStateFromStream != null ? 1 : 0;
		dos.writeInt(len);
		if (len == 1) {
			serializeOperatorStateHandle(operatorStateFromStream, dos);
		}

		KeyedStateHandle keyedStateBackend = extractSingleton(subtaskState.getManagedKeyedState());
		serializeKeyedStateHandle(keyedStateBackend, dos);

		KeyedStateHandle keyedStateStream = extractSingleton(subtaskState.getRawKeyedState());
		serializeKeyedStateHandle(keyedStateStream, dos);
	}
 
Example 13
Source Project: nifi   File: RemoteResourceFactory.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T extends ClientProtocol> T receiveClientProtocolNegotiation(final DataInputStream dis, final DataOutputStream dos) throws IOException, HandshakeException {
    final String protocolName = dis.readUTF();
    final int version = dis.readInt();

    final T protocol = (T) RemoteResourceManager.createClientProtocol(protocolName);
    final VersionNegotiator negotiator = protocol.getVersionNegotiator();
    if (negotiator.isVersionSupported(version)) {
        dos.write(RESOURCE_OK);
        dos.flush();

        negotiator.setVersion(version);
        return protocol;
    } else {
        final Integer preferred = negotiator.getPreferredVersion(version);
        if (preferred == null) {
            dos.write(ABORT);
            dos.flush();
            throw new HandshakeException("Unable to negotiate an acceptable version of the ClientProtocol " + protocolName);
        }
        dos.write(DIFFERENT_RESOURCE_VERSION);
        dos.writeInt(preferred);
        dos.flush();

        return receiveClientProtocolNegotiation(dis, dos);
    }
}
 
Example 14
private static void initiateVersionNegotiation(final VersionNegotiator negotiator, final DataInputStream dis, final DataOutputStream dos) throws IOException, HandshakeException {
    // Write the classname of the RemoteStreamCodec, followed by its version
    dos.writeInt(negotiator.getVersion());
    dos.flush();

    // wait for response from server.
    final int statusCode = dis.read();
    switch (statusCode) {
        case RESOURCE_OK:   // server accepted our proposal of codec name/version
            return;
        case DIFFERENT_RESOURCE_VERSION:    // server accepted our proposal of codec name but not the version
            // Get server's preferred version
            final int newVersion = dis.readInt();

            // Determine our new preferred version that is no greater than the server's preferred version.
            final Integer newPreference = negotiator.getPreferredVersion(newVersion);
            // If we could not agree with server on a version, fail now.
            if (newPreference == null) {
                throw new HandshakeException("Could not agree on protocol version");
            }

            negotiator.setVersion(newPreference);

            // Attempt negotiation of resource based on our new preferred version.
            initiateVersionNegotiation(negotiator, dis, dos);
            return;
        case ABORT:
            throw new HandshakeException("Remote destination aborted connection with message: " + dis.readUTF());
        default:
            throw new HandshakeException("Received unexpected response code " + statusCode + " when negotiating version with remote server");
    }
}
 
Example 15
Source Project: whyline   File: FieldAssignmentHistory.java    License: MIT License 5 votes vote down vote up
public void write(DataOutputStream out) throws IOException {

		out.writeInt(fieldAssignmentsByName.size());
		for(String unqualifiedName : fieldAssignmentsByName.keySet()) {
			out.writeUTF(unqualifiedName);
			fieldAssignmentsByName.get(unqualifiedName).write(out);
		}		

	}
 
Example 16
Source Project: credhub   File: CertificateFormatter.java    License: Apache License 2.0 4 votes vote down vote up
private static void writeBytesToDataStream(final byte[] bytes, final DataOutputStream dataStream)
  throws IOException {
  dataStream.writeInt(bytes.length);
  dataStream.write(bytes);
}
 
Example 17
private void writeRecord(DataOutputStream os, CloverBuffer buffer) throws IOException {
	os.writeInt(buffer.remaining());
	os.write(buffer.array(), 0, buffer.limit());
}
 
Example 18
Source Project: btree4j   File: BTree.java    License: Apache License 2.0 4 votes vote down vote up
private void write() throws IOException, BTreeException {
    if (!dirty) {
        return;
    }
    if (LOG.isTraceEnabled()) {
        LOG.trace((ph.getStatus() == LEAF ? "Leaf " : "Branch ") + "Node#"
                + page.getPageNum() + " - " + Arrays.toString(keys));
    }
    final FastMultiByteArrayOutputStream bos =
            new FastMultiByteArrayOutputStream(_fileHeader.getWorkSize());
    final DataOutputStream os = new DataOutputStream(bos);

    // write out the prefix
    final short prefixlen = ph.getPrefixLength();
    if (prefixlen > 0) {
        prefix.writeTo(os);
    }
    // Write out the Values
    Value prevKey = null;
    for (int i = 0; i < keys.length; i++) {
        final Value v = keys[i];
        if (v == prevKey) {
            os.writeInt(-1);
        } else {
            final int len = v.getLength();
            final int size = len - prefixlen;
            os.writeInt(size);
            if (size > 0) {
                v.writeTo(os, prefixlen, size);
            }
        }
        prevKey = v;
    }
    // Write out the pointers
    for (int i = 0; i < ptrs.length; i++) {
        VariableByteCodec.encodeUnsignedLong(ptrs[i], os);
    }
    // Write out link if current node is a leaf
    if (ph.getStatus() == LEAF) {
        os.writeLong(_prev);
        os.writeLong(_next);
    }

    writeValue(page, new Value(bos.toByteArray()));
    this.parentCache = null;
    setDirty(false);
}
 
Example 19
public void
serialise(
	DataOutputStream	os )

	throws IOException
{
	super.serialise(os);
	
	if ( getProtocolVersion() >= DHTTransportUDP.PROTOCOL_VERSION_ANTI_SPOOF ){
		
		os.writeInt( random_id );
	}
	
	DHTUDPUtils.serialiseByteArrayArray( os, keys, MAX_KEYS_PER_PACKET );
	
	try{
		DHTUDPUtils.serialiseTransportValuesArray( this, os, value_sets, 0, MAX_KEYS_PER_PACKET );
		
	}catch( DHTTransportException e ){
		
		throw( new IOException( e.getMessage()));
	}
	
	super.postSerialise( os );
}
 
Example 20
@Override
public void
serialise(
	DataOutputStream	os )

	throws IOException
{
	super.serialise(os);

	os.writeByte( packet_type );
	DHTUDPUtils.serialiseByteArray( os, transfer_key, 64 );

	int	max_key_size;

	if ( getProtocolVersion() >= DHTTransportUDP.PROTOCOL_VERSION_REPLICATION_CONTROL ){

		max_key_size = 255;

	}else{

		max_key_size = 64;
	}

	DHTUDPUtils.serialiseByteArray( os, key, max_key_size );
	os.writeInt( start_position );
	os.writeInt( length );
	os.writeInt( total_length );

	if ( data.length > 0 ){

		DHTUDPUtils.serialiseByteArray( os, data, start_position, length, 65535 );

	}else{

		DHTUDPUtils.serialiseByteArray( os, data,  65535 );
	}
}