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

The following examples show how to use java.io.DataOutputStream#writeUTF() . 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
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 2
Source Project: hollow   File: HollowObjectSchema.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(OutputStream os) throws IOException {
    DataOutputStream dos = new DataOutputStream(os);

    if (primaryKey != null)
        dos.write(SchemaType.OBJECT.getTypeIdWithPrimaryKey());
    else
        dos.write(SchemaType.OBJECT.getTypeId());

    dos.writeUTF(getName());
    if (primaryKey != null) {
        VarInt.writeVInt(dos, primaryKey.numFields());
        for (int i = 0; i < primaryKey.numFields(); i++) {
            dos.writeUTF(primaryKey.getFieldPath(i));
        }
    }

    dos.writeShort(size);
    for(int i=0;i<size;i++) {
        dos.writeUTF(fieldNames[i]);
        dos.writeUTF(fieldTypes[i].name());
        if(fieldTypes[i] == FieldType.REFERENCE)
            dos.writeUTF(referencedTypes[i]);
    }

}
 
Example 3
public InputStream getMACInput() throws IOException
{
    List<InputStream> inputStreams = new ArrayList<InputStream>();

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(bytes);
    out.writeUTF(ipAddress);
    out.writeByte(SEPARATOR);
    out.writeLong(timestamp);
    inputStreams.add(new ByteArrayInputStream(bytes.toByteArray()));

    if(message != null)
    {
        inputStreams.add(message);
    }

    return new MessageInputStream(inputStreams);
}
 
Example 4
Source Project: zeno   File: ZenoFastBlobHeaderWriter.java    License: Apache License 2.0 6 votes vote down vote up
public void writeHeader(FastBlobHeader header, FastBlobStateEngine stateEngine, DataOutputStream dos) throws IOException {
    /// save 4 bytes to indicate FastBlob version header.  This will be changed to indicate backwards incompatibility.
    dos.writeInt(FastBlobHeader.FAST_BLOB_VERSION_HEADER);

    /// write the version from the state engine
    dos.writeUTF(header.getVersion());

    /// write the header tags -- intended to include input source data versions
    dos.writeShort(header.getHeaderTags().size());

    for (Map.Entry<String, String> headerTag : header.getHeaderTags().entrySet()) {
        dos.writeUTF(headerTag.getKey());
        dos.writeUTF(headerTag.getValue());
    }

    dos.write(header.getDeserializationBufferSizeHint());

    /// flags byte -- reserved for later use
    dos.write(0);

    VarInt.writeVInt(dos, header.getNumberOfTypes());
}
 
Example 5
Source Project: external-nfc-api   File: IAcr1283Binder.java    License: Apache License 2.0 6 votes vote down vote up
private byte[] noReaderException() {

        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            DataOutputStream dout = new DataOutputStream(out);

            dout.writeInt(AcrReader.VERSION);
            dout.writeInt(AcrReader.STATUS_EXCEPTION);
            dout.writeUTF("Reader not connected");

            byte[] response = out.toByteArray();

            Log.d(TAG, "Send exception response length " + response.length + ":" + ACRCommands.toHexString(response));

            return response;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
 
Example 6
Source Project: external-nfc-api   File: CommandWrapper.java    License: Apache License 2.0 6 votes vote down vote up
protected byte[] returnValue(String firmware, Exception exception) {
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(out);

        dout.writeInt(AcrReader.VERSION);

        if (firmware != null) {
            dout.writeInt(AcrReader.STATUS_OK);
            dout.writeUTF(firmware);
        } else {
            dout.writeInt(AcrReader.STATUS_EXCEPTION);
            dout.writeUTF(exception.toString());
        }
        byte[] response = out.toByteArray();

        // Log.d(TAG, "Send response length " + response.length + ":" + ACRCommands.toHexString(response));

        return response;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
/**
 * Compute the "method hash" of a remote method.  The method hash
 * is a long containing the first 64 bits of the SHA digest from
 * the UTF encoded string of the method name and descriptor.
 */
public static long computeMethodHash(Method m) {
    long hash = 0;
    ByteArrayOutputStream sink = new ByteArrayOutputStream(127);
    try {
        MessageDigest md = MessageDigest.getInstance("SHA");
        DataOutputStream out = new DataOutputStream(
            new DigestOutputStream(sink, md));

        String s = getMethodNameAndDescriptor(m);
        if (serverRefLog.isLoggable(Log.VERBOSE)) {
            serverRefLog.log(Log.VERBOSE,
                "string used for method hash: \"" + s + "\"");
        }
        out.writeUTF(s);

        // use only the first 64 bits of the digest for the hash
        out.flush();
        byte hasharray[] = md.digest();
        for (int i = 0; i < Math.min(8, hasharray.length); i++) {
            hash += ((long) (hasharray[i] & 0xFF)) << (i * 8);
        }
    } catch (IOException ignore) {
        /* can't happen, but be deterministic anyway. */
        hash = -1;
    } catch (NoSuchAlgorithmException complain) {
        throw new SecurityException(complain.getMessage());
    }
    return hash;
}
 
Example 8
Source Project: CodenameOne   File: Util.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Writes a string with a null flag, this allows a String which may be null
 *
 * @param s the string to write
 * @param d the destination output stream
 * @throws java.io.IOException
 */
public static void writeUTF(String s, DataOutputStream d) throws IOException {
    if(s == null) {
        d.writeBoolean(false);
        return;
    }
    d.writeBoolean(true);
    d.writeUTF(s);
}
 
Example 9
Source Project: settlers-remake   File: TaskPacket.java    License: MIT License 5 votes vote down vote up
@Override
public final void serialize(DataOutputStream dos) throws IOException {
	ByteArrayOutputStream bufferOutStream = new ByteArrayOutputStream();
	DataOutputStream bufferDataOutStream = new DataOutputStream(bufferOutStream);

	bufferDataOutStream.writeUTF(this.getClass().getName());
	serializeTask(bufferDataOutStream);
	bufferDataOutStream.flush();

	dos.writeInt(bufferOutStream.size());
	bufferOutStream.writeTo(dos);
}
 
Example 10
Source Project: PlusDemo   File: Io.java    License: Apache License 2.0 5 votes vote down vote up
private static void okio2() {
    try {
        Buffer buffer = new Buffer();
        DataOutputStream dataOutputStream = new DataOutputStream(buffer.outputStream());
        dataOutputStream.writeUTF("abab");
        dataOutputStream.writeBoolean(true);
        dataOutputStream.writeChar('b');
        DataInputStream inputStream = new DataInputStream(buffer.inputStream());
        System.out.println(inputStream.readUTF());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 11
protected void buildRequestBody(OutputStream os) throws IOException {
    DataOutputStream d = new DataOutputStream(os);
    d.writeInt(storageQueue.size());
    d.writeUTF(CloudPersona.getCurrentPersona().getToken());
    d.writeUTF(Display.getInstance().getProperty("package_name", null));
    d.writeUTF(Display.getInstance().getProperty("built_by_user", null));
    for(int iter = 0 ; iter < storageQueue.size() ; iter++) {
        Object e = storageQueue.elementAt(iter);
        if(e instanceof String) {
            // delete operation
            d.writeByte(1);
            d.writeUTF((String)e);
        } else {
            CloudObject cl = (CloudObject)e;
            if(cl.getCloudId() == null) {
                // insert operation
                d.writeByte(2);
                d.writeInt(cl.getAccessPermissions());
                Util.writeObject(cl.getValues(), d);
            } else {
                // update operation
                d.writeByte(3);
                d.writeUTF(cl.getCloudId());
                d.writeLong(cl.getLastModified());
                Util.writeObject(cl.getValues(), d);
            }
        }
    }
    d.writeInt(1);
}
 
Example 12
Source Project: GNSS_Compare   File: ObservationSet.java    License: Apache License 2.0 5 votes vote down vote up
public int write(DataOutputStream dos) throws IOException{
	int size = 0;
	dos.writeUTF(MESSAGE_OBSERVATIONS_SET); // 5

	dos.writeInt(STREAM_V); size +=4;
	dos.write(satID);size +=1;		// 1
	dos.write(satType);size +=1;		// 1
	// L1 data
	dos.write((byte)qualityInd[L1]);	size+=1;
	dos.write((byte)lossLockInd[L1]);	size+=1;
	dos.writeDouble(codeC[L1]); size+=8;
	dos.writeDouble(codeP[L1]); size+=8;
	dos.writeDouble(phase[L1]); size+=8;
	dos.writeFloat(signalStrength[L1]); size+=4;
	dos.writeFloat(doppler[L1]); size+=4;
	// write L2 data ?
	boolean hasL2 = false;
	if(!Double.isNaN(codeC[L2])) hasL2 = true;
	if(!Double.isNaN(codeP[L2])) hasL2 = true;
	if(!Double.isNaN(phase[L2])) hasL2 = true;
	if(!Float.isNaN(signalStrength[L2])) hasL2 = true;
	if(!Float.isNaN(doppler[L2])) hasL2 = true;
	dos.writeBoolean(hasL2); size+=1;
	if(hasL2){
		dos.write((byte)qualityInd[L2]);	size+=1;
		dos.write((byte)lossLockInd[L2]);	size+=1;
		dos.writeDouble(codeC[L2]); size+=8;
		dos.writeDouble(codeP[L2]); size+=8;
		dos.writeDouble(phase[L2]); size+=8;
		dos.writeFloat(signalStrength[L2]); size+=4;
		dos.writeFloat(doppler[L2]); size+=4;
	}
	return size;
}
 
Example 13
Source Project: SEANLP   File: CRFModel.java    License: Apache License 2.0 5 votes vote down vote up
public void save(DataOutputStream out) throws Exception {
	out.writeInt(id2tag.length);
	for (String tag : id2tag) {
		out.writeUTF(tag);
	}
	FeatureFunction[] valueArray = featureFunctionTrie
			.getValueArray(new FeatureFunction[0]);
	out.writeInt(valueArray.length);
	for (FeatureFunction featureFunction : valueArray) {
		featureFunction.save(out);
	}
	featureFunctionTrie.save(out);
	out.writeInt(featureTemplateList.size());
	for (FeatureTemplate featureTemplate : featureTemplateList) {
		featureTemplate.save(out);
	}
	if (matrix != null) {
		out.writeInt(matrix.length);
		for (double[] line : matrix) {
			for (double v : line) {
				out.writeDouble(v);
			}
		}
	} else {
		out.writeInt(0);
	}
}
 
Example 14
/**
 * Closes resources pointing to the current journal and begins writing
 * to a new one
 *
 * @throws IOException if failure to rollover
 */
public OutputStream rollover() throws IOException {
    // Note that here we are closing fileOut and NOT dataOut. See the note in the close()
    // method to understand the logic behind this.
    final OutputStream oldOutputStream = fileOut;
    dataOut = null;
    fileOut = null;

    this.serde = serdeFactory.createSerDe(null);
    final Path editPath = getNewEditPath();
    final FileOutputStream fos = new FileOutputStream(editPath.toFile());
    try {
        final DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
        outStream.writeUTF(MinimalLockingWriteAheadLog.class.getName());
        outStream.writeInt(writeAheadLogVersion);
        outStream.writeUTF(serde.getClass().getName());
        outStream.writeInt(serde.getVersion());
        serde.writeHeader(outStream);

        outStream.flush();
        dataOut = outStream;
        fileOut = fos;
    } catch (final IOException ioe) {
        try {
            oldOutputStream.close();
        } catch (final IOException ioe2) {
            ioe.addSuppressed(ioe2);
        }

        logger.error("Failed to create new journal for {} due to {}", new Object[] {this, ioe.toString()}, ioe);
        try {
            fos.close();
        } catch (final IOException innerIOE) {
        }

        dataOut = null;
        fileOut = null;
        blackList();

        throw ioe;
    }

    currentJournalFilename = editPath.toFile().getName();

    blackListed = false;
    return oldOutputStream;
}
 
Example 15
Source Project: ripple-lib-java   File: BcKeyStoreSpi.java    License: ISC License 4 votes vote down vote up
protected void saveStore(
    OutputStream    out)
    throws IOException
{
    Enumeration         e = table.elements();
    DataOutputStream    dOut = new DataOutputStream(out);

    while (e.hasMoreElements())
    {
        StoreEntry  entry = (StoreEntry)e.nextElement();

        dOut.write(entry.getType());
        dOut.writeUTF(entry.getAlias());
        dOut.writeLong(entry.getDate().getTime());

        Certificate[]   chain = entry.getCertificateChain();
        if (chain == null)
        {
            dOut.writeInt(0);
        }
        else
        {
            dOut.writeInt(chain.length);
            for (int i = 0; i != chain.length; i++)
            {
                encodeCertificate(chain[i], dOut);
            }
        }

        switch (entry.getType())
        {
        case CERTIFICATE:
                encodeCertificate((Certificate)entry.getObject(), dOut);
                break;
        case KEY:
                encodeKey((Key)entry.getObject(), dOut);
                break;
        case SEALED:
        case SECRET:
                byte[]  b = (byte[])entry.getObject();

                dOut.writeInt(b.length);
                dOut.write(b);
                break;
        default:
                throw new RuntimeException("Unknown object type in store.");
        }
    }

    dOut.write(NULL);
}
 
Example 16
/**
 * Write the constant to the output stream
 */
void write(Environment env, DataOutputStream out, ConstantPool tab) throws IOException {
    out.writeByte(CONSTANT_UTF8);
    out.writeUTF(str);
}
 
Example 17
public static <T extends VersionedRemoteResource> T
        receiveResourceNegotiation(final Class<T> cls, final DataInputStream dis, final DataOutputStream dos, final Class<?>[] constructorArgClasses, final Object[] constructorArgs)
        throws IOException, HandshakeException {
    final String resourceClassName = dis.readUTF();
    final T resource;
    try {
        @SuppressWarnings("unchecked")
        final Class<T> resourceClass = (Class<T>) Class.forName(resourceClassName);
        if (!cls.isAssignableFrom(resourceClass)) {
            throw new HandshakeException("Expected to negotiate a Versioned Resource of type " + cls.getName() + " but received class name of " + resourceClassName);
        }

        final Constructor<T> ctr = resourceClass.getConstructor(constructorArgClasses);
        resource = ctr.newInstance(constructorArgs);
    } catch (final Throwable t) {
        dos.write(ABORT);
        final String errorMsg = "Unable to instantiate Versioned Resource of type " + resourceClassName;
        dos.writeUTF(errorMsg);
        dos.flush();
        throw new HandshakeException(errorMsg);
    }

    final int version = dis.readInt();
    final VersionNegotiator negotiator = resource.getVersionNegotiator();
    if (negotiator.isVersionSupported(version)) {
        dos.write(RESOURCE_OK);
        dos.flush();

        negotiator.setVersion(version);
        return resource;
    } 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 resource " + resourceClassName);
        }
        dos.write(DIFFERENT_RESOURCE_VERSION);
        dos.writeInt(preferred);
        dos.flush();

        return receiveResourceNegotiation(cls, dis, dos, constructorArgClasses, constructorArgs);
    }
}
 
Example 18
private void serializeModels(DataOutputStream dos) throws IOException {
    dos.writeInt(modelHolder.size());
    for(String model : modelHolder) {
        dos.writeUTF(model);
    }
}
 
Example 19
@Test
public void testEofExceptionMultipleFlowFiles() throws IOException {
    final StandardLoadBalanceProtocol protocol = new StandardLoadBalanceProtocol(flowFileRepo, contentRepo, provenanceRepo, flowController, ALWAYS_AUTHORIZED);

    final PipedInputStream serverInput = new PipedInputStream();
    final PipedOutputStream serverContentSource = new PipedOutputStream();
    serverInput.connect(serverContentSource);

    final ByteArrayOutputStream serverOutput = new ByteArrayOutputStream();

    // Write connection ID
    final Checksum checksum = new CRC32();
    final OutputStream checkedOutput = new CheckedOutputStream(serverContentSource, checksum);
    final DataOutputStream dos = new DataOutputStream(checkedOutput);
    dos.writeUTF("unit-test-connection-id");

    final Map<String, String> attributes = new HashMap<>();
    attributes.put("a", "A");
    attributes.put("uuid", "unit-test-id");
    attributes.put("b", "B");

    // Send 4 FlowFiles.
    dos.write(CHECK_SPACE);
    dos.write(MORE_FLOWFILES);
    writeAttributes(attributes, dos);
    writeContent("hello".getBytes(), dos);

    dos.write(MORE_FLOWFILES);
    writeAttributes(Collections.singletonMap("uuid", "unit-test-id-2"), dos);
    writeContent(null, dos);

    dos.write(MORE_FLOWFILES);
    writeAttributes(Collections.singletonMap("uuid", "unit-test-id-3"), dos);
    writeContent("greetings".getBytes(), dos);

    dos.write(MORE_FLOWFILES);
    writeAttributes(Collections.singletonMap("uuid", "unit-test-id-4"), dos);
    writeContent(new byte[0], dos);

    dos.flush();
    dos.close();

    try {
        protocol.receiveFlowFiles(serverInput, serverOutput, "Unit Test", 1);
        Assert.fail("Expected EOFException but none was thrown");
    } catch (final EOFException eof) {
        // expected
    }

    final byte[] serverResponse = serverOutput.toByteArray();
    assertEquals(1, serverResponse.length);
    assertEquals(SPACE_AVAILABLE, serverResponse[0]);

    assertEquals(1, claimContents.size());
    assertArrayEquals("hellogreetings".getBytes(), claimContents.values().iterator().next());

    assertEquals(0, flowFileRepoUpdateRecords.size());
    assertEquals(0, provRepoUpdateRecords.size());
    assertEquals(0, flowFileQueuePutRecords.size());
}
 
Example 20
private byte[] noReaderException() {


        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            DataOutputStream dout = new DataOutputStream(out);

            dout.writeInt(AcrReader.VERSION);
            dout.writeInt(AcrReader.STATUS_EXCEPTION);
            dout.writeUTF("Reader not connected");

            byte[] response = out.toByteArray();

            Log.d(TAG, "Send exception response length " + response.length + ":" + ACRCommands.toHexString(response));

            return response;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }