@Test public void testSerialization() throws Exception { Set<PersistentMemberID>[] offlineMembers = new Set[5]; for (int i = 0; i < offlineMembers.length; i++) { offlineMembers[i] = new HashSet<PersistentMemberID>(); offlineMembers[i].add(new PersistentMemberID(DiskStoreID.random(), InetAddress.getLocalHost(), "a", System.currentTimeMillis(), (short) 0)); } OfflineMemberDetailsImpl details = new OfflineMemberDetailsImpl(offlineMembers); ByteArrayOutputStream boas = new ByteArrayOutputStream(); DataOutput out = new DataOutputStream(boas); details.toData(out); OfflineMemberDetailsImpl details2 = new OfflineMemberDetailsImpl(); details2.fromData(new DataInputStream(new ByteArrayInputStream(boas.toByteArray()))); }
@Override public void serialise( DataOutputStream os ) throws IOException { super.serialise(os); os.write( hash ); os.write( peer_id ); os.writeLong( downloaded ); os.writeLong( left ); os.writeLong( uploaded ); os.writeInt( event ); os.writeInt( ip_address ); os.writeInt( num_want ); os.writeShort( port ); }
public void writeToStream(OutputStream gribFile) { DataOutputStream dataout = new DataOutputStream(gribFile); try { gribFile.write(magicnumberbytes); dataout.writeShort(reserved); gribFile.write(discipline); gribFile.write(number); dataout.writeLong(totalLength); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * Write the constant to the output stream */ void write(Environment env, DataOutputStream out, ConstantPool tab) throws IOException { if (num instanceof Integer) { out.writeByte(CONSTANT_INTEGER); out.writeInt(num.intValue()); } else if (num instanceof Long) { out.writeByte(CONSTANT_LONG); out.writeLong(num.longValue()); } else if (num instanceof Float) { out.writeByte(CONSTANT_FLOAT); out.writeFloat(num.floatValue()); } else if (num instanceof Double) { out.writeByte(CONSTANT_DOUBLE); out.writeDouble(num.doubleValue()); } }
/** * Transform a long value into its byte representation. * * @param longValue * value The long value to transform. * @return The byte representation of the given value. */ public static byte[] long2VarIntByteArray(long longValue) { try { long value = longValue; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); DataOutput out = new DataOutputStream(byteArrayOutputStream); while ((value & 0xFFFFFFFFFFFFFF80L) != 0L) { out.writeByte(((int) value & 0x7F) | 0x80); value >>>= 7; } out.writeByte((int) value & 0x7F); return byteArrayOutputStream.toByteArray(); } catch (IOException e) { LOG.error("Could not transform the given long value into its VarInt representation - " + "Using BitcoinJ as Fallback. This could cause problems for values > 127.", e); return (new VarInt(longValue)).encode(); } }
private void saveVarMapping(VariableNumber var, ZipOutputStream zos) throws IOException { //System.out.println("VAR "+ filepath + var.getName()+"_Map"+BINext); zos.putNextEntry(new ZipEntry(var.getName() + "_Map" + BINext)); DataOutputStream dos = new DataOutputStream(zos); Mapping[] map = var.getMapping().getMappingValue(); dos.write(map.length); for (Mapping element : map) { dos.writeDouble(element.getConversion()); dos.writeUTF(element.getValue().toString()); } dos.flush(); zos.closeEntry(); }
/** * 执行shell命令 * * @param cmd */ // http://blog.csdn.net/mad1989/article/details/38109689/ public void execShellCmd(String cmd) { L.d("执行命令 " + cmd); try { // 申请获取root权限,这一步很重要,不然会没有作用 Process process = Runtime.getRuntime().exec("su"); // 获取输出流 OutputStream outputStream = process.getOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream( outputStream); dataOutputStream.writeBytes(cmd); dataOutputStream.flush(); dataOutputStream.close(); outputStream.close(); } catch (Throwable t) { t.printStackTrace(); } }
private String excuteCBASQuery(String query) throws Exception { URL url = new URL(getCbasURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("ignore-401", "true"); String encodedQuery = URLEncoder.encode(query, "UTF-8"); String payload = "statement=" + encodedQuery; DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.writeBytes(payload); out.flush(); out.close(); int responseCode = connection.getResponseCode(); BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); }
/** * Tests data serializing a <code>long</code> array */ @Test public void testLongArray() throws Exception { long[] array = new long[] {4, 5, 6}; DataOutputStream out = getDataOutput(); DataSerializer.writeLongArray(array, out); out.flush(); DataInput in = getDataInput(); long[] array2 = DataSerializer.readLongArray(in); assertEquals(array.length, array2.length); for (int i = 0; i < array.length; i++) { assertEquals(array[i], array2[i]); } }
public void testWideWritable2() throws Exception { Writable[] manyWrits = makeRandomWritables(71); TupleWritable sTuple = new TupleWritable(manyWrits); for (int i =0; i<manyWrits.length; i++) { sTuple.setWritten(i); } ByteArrayOutputStream out = new ByteArrayOutputStream(); sTuple.write(new DataOutputStream(out)); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); TupleWritable dTuple = new TupleWritable(); dTuple.readFields(new DataInputStream(in)); assertTrue("Failed to write/read tuple", sTuple.equals(dTuple)); assertEquals("All tuple data has not been read from the stream", -1, in.read()); }
public ListenableFuture<?> sendPlayerToServer(Player player, @Nullable String bungeeName, boolean quiet) { if(localServer.bungee_name().equals(bungeeName) || (localServer.role() == ServerDoc.Role.LOBBY && bungeeName == null)) { return Futures.immediateFuture(null); } final ByteArrayOutputStream message = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(message); try { out.writeUTF(quiet ? "ConnectQuiet" : "Connect"); out.writeUTF(bungeeName == null ? "default" : bungeeName); } catch(IOException e) { return Futures.immediateFailedFuture(e); } player.sendPluginMessage(plugin, PLUGIN_CHANNEL, message.toByteArray()); return quitFuture(player); }
@Override public Hashtable<Integer, byte[]> getClientExtensions() throws IOException { Hashtable<Integer, byte[]> clientExtensions = super.getClientExtensions(); if (clientExtensions == null) { clientExtensions = new Hashtable<Integer, byte[]>(); } //Add host_name byte[] host_name = host.getBytes(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream dos = new DataOutputStream(baos); dos.writeShort(host_name.length + 3); // entry size dos.writeByte(0); // name type = hostname dos.writeShort(host_name.length); dos.write(host_name); dos.close(); clientExtensions.put(ExtensionType.server_name, baos.toByteArray()); return clientExtensions; }
private void tryArrayList(int size) throws IOException, ClassNotFoundException { setUp(); final Random random = getRandom(); final ArrayList list = size == -1 ? null : new ArrayList(size); for (int i = 0; i < size; i++) { list.add(new Long(random.nextLong())); } DataOutputStream out = getDataOutput(); DataSerializer.writeArrayList(list, out); out.flush(); DataInput in = getDataInput(); ArrayList list2 = DataSerializer.readArrayList(in); assertEquals(list, list2); tearDown(); }
/** * Assert that MKeyBase can be serialized and de-serialized as expected. * * @throws IOException * @throws ClassNotFoundException */ @Test public void testSerialize() throws IOException, ClassNotFoundException { final MKeyBase key = new MKeyBase("abc".getBytes()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); key.toData(dos); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bos.toByteArray())); final MKeyBase readKey = new MKeyBase(); readKey.fromData(dis); dis.close(); dos.close(); bos.close(); /** assert that two objects are different but are same for equals and compareTo **/ assertFalse(key == readKey); assertEquals(key, readKey); assertTrue(key.equals(readKey)); assertEquals(key.hashCode(), readKey.hashCode()); assertEquals(0, key.compareTo(key)); }
/** * Serialize a trie2 Header and Index onto an OutputStream. This is * common code used for both the Trie2_16 and Trie2_32 serialize functions. * @param dos the stream to which the serialized Trie2 data will be written. * @return the number of bytes written. */ protected int serializeHeader(DataOutputStream dos) throws IOException { // Write the header. It is already set and ready to use, having been // created when the Trie2 was unserialized or when it was frozen. int bytesWritten = 0; dos.writeInt(header.signature); dos.writeShort(header.options); dos.writeShort(header.indexLength); dos.writeShort(header.shiftedDataLength); dos.writeShort(header.index2NullOffset); dos.writeShort(header.dataNullOffset); dos.writeShort(header.shiftedHighStart); bytesWritten += 16; // Write the index int i; for (i=0; i< header.indexLength; i++) { dos.writeChar(index[i]); } bytesWritten += header.indexLength; return bytesWritten; }
/** * Tests data serializing an {@link HashMap} */ @Test public void testHashMap() throws Exception { Random random = getRandom(); HashMap map = new HashMap(); int size = random.nextInt(50); for (int i = 0; i < size; i++) { Object key = new Long(random.nextLong()); Object value = String.valueOf(random.nextLong()); map.put(key, value); } DataOutputStream out = getDataOutput(); DataSerializer.writeHashMap(map, out); out.flush(); DataInput in = getDataInput(); HashMap map2 = DataSerializer.readHashMap(in); assertEquals(map, map2); }
/** * 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); } }
private void initializeWriting() throws JMSException { checkReadOnlyBody(); if (this.dataOut == null) { this.content = null; this.output = new ByteArrayOutputStream(); this.dataOut = new DataOutputStream(output); } }
@Override public void save(DataOutputStream out) throws IOException { out.writeInt(midi); out.writeLong(start); out.writeLong(end); }
/** * Forge an validate session packet as a LEARNER do * * @return * @throws Exception */ private QuorumPacket createValidateSessionQuorumPacket() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeLong(SESSION_ID); dos.writeInt(3000); dos.close(); QuorumPacket qp = new QuorumPacket(Leader.REVALIDATE, -1, baos.toByteArray(), null); if (LOG.isTraceEnabled()) { ZooTrace.logTraceMessage(LOG, ZooTrace.SESSION_TRACE_MASK, "To validate session 0x" + Long.toHexString(2L)); } return qp; }
@Override 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); } }
@Override public void write(DataOutputStream output) throws IOException { super.write(output); output.writeBoolean(getValue().hasEffect()); if(getValue().hasEffect()) { FireworkEffectStorage storage = new FireworkEffectStorage(getValue().getEffect()); storage.write(output); } }
/** For writing the first key and value bytes directly from the * value iterators, pass the current underlying output stream * @param length The length of the impending write */ public DataOutputStream getOutputStream(int length) throws IOException { if (memCache.reserveSpace(length)) { return memCache.dataOut; } else { fileCache.activate(); return fileCache.writer.getOutputStream(); } }
/** * Tests data serializing a {@link File} using {@link DataSerializer#writeObject}. */ @Test public void testFileObject() throws Exception { File file = new File(System.getProperty("user.dir")); DataOutputStream out = getDataOutput(); DataSerializer.writeObject(file, out); out.flush(); DataInput in = getDataInput(); File file2 = (File) DataSerializer.readObject(in); assertEquals(file, file2); }
@Override public void writeFields(DataOutputStream out) throws IOException { XAttrEditLogProto.Builder b = XAttrEditLogProto.newBuilder(); if (src != null) { b.setSrc(src); } b.addAllXAttrs(PBHelper.convertXAttrProto(xAttrs)); b.build().writeDelimitedTo(out); // clientId and callId writeRpcIds(rpcClientId, rpcCallId, out); }
private static void writeCert(DataOutputStream dout, Certificate cert) throws IOException, CertificateException { dout.writeUTF(cert.getType()); byte[] b = cert.getEncoded(); dout.writeInt(b.length); dout.write(b); }
public void testBadIndex() throws Exception { final int parts = 30; fs.delete(p, true); conf.setInt(TTConfig.TT_INDEX_CACHE, 1); IndexCache cache = new IndexCache(conf); Path f = new Path(p, "badindex"); FSDataOutputStream out = fs.create(f, false); CheckedOutputStream iout = new CheckedOutputStream(out, new CRC32()); DataOutputStream dout = new DataOutputStream(iout); for (int i = 0; i < parts; ++i) { for (int j = 0; j < MapTask.MAP_OUTPUT_INDEX_RECORD_LENGTH / 8; ++j) { if (0 == (i % 3)) { dout.writeLong(i); } else { out.writeLong(i); } } } out.writeLong(iout.getChecksum().getValue()); dout.close(); try { cache.getIndexInformation("badindex", 7, f, UserGroupInformation.getCurrentUser().getShortUserName()); fail("Did not detect bad checksum"); } catch (IOException e) { if (!(e.getCause() instanceof ChecksumException)) { throw e; } } }
@Override public void serialise( DataOutputStream os ) throws IOException { super.serialise(os); byte[] bytes = BEncoder.encode( payload ); os.writeShort( (short)bytes.length ); os.write( bytes ); }
private void writeFile(FileSystem fileSys, Path name, int nBytesToWrite) throws IOException { DataOutputStream out = fileSys.create(name); for (int i = 0; i < nBytesToWrite; ++i) { out.writeByte(0); } out.close(); }
@Override public void dump(final DataOutputStream dos) throws IOException { dos.writeByte(super.getType()); // u1 type of value (ARRAY == '[') dos.writeShort(evalues.length); for (final ElementValue evalue : evalues) { evalue.dump(dos); } }
static Path writeFile(FileSystem fs, Path f) throws IOException { DataOutputStream out = fs.create(f); try { out.writeBytes("test"); } finally { out.close(); } assertTrue(fs.exists(f)); return f; }
@Override public void startBlockEncoding(HFileBlockEncodingContext encodingCtx, DataOutputStream out) throws IOException { if (this.encoding != null && this.encoding != DataBlockEncoding.NONE) { this.encoding.getEncoder().startBlockEncoding(encodingCtx, out); } }
/** * Sends the data to the bStats server. * * @param data The data to send. * @throws Exception If the request failed. */ private static void sendData(JsonObject data) throws Exception { if (data == null) { throw new IllegalArgumentException("Data cannot be null"); } HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); // Compress the data to save bandwidth byte[] compressedData = compress(data.toString()); // Add headers connection.setRequestMethod("POST"); connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Connection", "close"); connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); // Send data connection.setDoOutput(true); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.write(compressedData); outputStream.flush(); outputStream.close(); connection.getInputStream().close(); // We don't care about the response - Just send our data :) }
private void sendPost(String urlParameters, String UUID) throws Exception { String query = DATAFLOW_POST + UUID; URL obj = new URI(PROTOCOL, null, HOST, PORT, PATH, query, null).toURL(); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Content-Type", "text/plain"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); //String urlParameters = "{\"intersection\": [{\"query\": \"?val=test\"},{\"query\": \"?val=87230\"}]}"; //String urlParameters = "{\"item-metadata\": [{\"val\": \"CPUUtil\",\"rel\": \"urn:X-hypercat:rels:hasDescription:en\"},{\"val\": \"200\",\"rel\": \"CPUUtil\"}],\"href\": \"/device/cpu/1\"}"; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); System.out.println(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + obj.toString()); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); }
private void addOrUpdateToken(TokenIdent ident, DelegationTokenInformation info, boolean isUpdate) throws Exception { String nodeCreatePath = getNodePath(ZK_DTSM_TOKENS_ROOT, DELEGATION_TOKEN_PREFIX + ident.getSequenceNumber()); ByteArrayOutputStream tokenOs = new ByteArrayOutputStream(); DataOutputStream tokenOut = new DataOutputStream(tokenOs); ByteArrayOutputStream seqOs = new ByteArrayOutputStream(); try { ident.write(tokenOut); tokenOut.writeLong(info.getRenewDate()); tokenOut.writeInt(info.getPassword().length); tokenOut.write(info.getPassword()); if (LOG.isDebugEnabled()) { LOG.debug((isUpdate ? "Updating " : "Storing ") + "ZKDTSMDelegationToken_" + ident.getSequenceNumber()); } if (isUpdate) { zkClient.setData().forPath(nodeCreatePath, tokenOs.toByteArray()) .setVersion(-1); } else { zkClient.create().withMode(CreateMode.PERSISTENT) .forPath(nodeCreatePath, tokenOs.toByteArray()); } } finally { seqOs.close(); } }
@Test public void testCharArray() throws IOException { char[] value = new char[1]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); DataSerializer.writeObject(value, out); byte[] bytes = baos.toByteArray(); String type = DataType.getDataType(bytes); assertEquals("char[]", type); }
/** * Creates an index for reference file * * @param referenceId {@code Long} represents ID of a reference in the system * @param chromosomeName {@code String} represents a container that provides access to major properties * and can be updated by metadata produced as the result of the current call */ public void makeNibIndex(final Long referenceId, final String chromosomeName) throws IOException { try (BlockCompressedDataInputStream streamGC = makeGCInputStream(referenceId, chromosomeName); DataOutputStream indexStream = makeGCIndexOutputStream(referenceId, chromosomeName)) { fillSimpleIndexFile(streamGC, indexStream); } try (BlockCompressedDataInputStream refStream = makeRefInputStream(referenceId, chromosomeName); DataOutputStream indexStream = makeRefIndexOutputStream(referenceId, chromosomeName)) { fillSimpleIndexFile(refStream, indexStream); } }
/** * Send transport header over stream. */ private void writeTransportHeader(DataOutputStream out) throws RemoteException { try { // write out transport header DataOutputStream dataOut = new DataOutputStream(out); dataOut.writeInt(TransportConstants.Magic); dataOut.writeShort(TransportConstants.Version); } catch (IOException e) { throw new ConnectIOException( "error writing JRMP transport header", e); } }
protected static void serialiseAltContacts( DataOutputStream os, DHTTransportAlternativeContact[] contacts ) throws IOException { if ( contacts == null ){ contacts = new DHTTransportAlternativeContact[0]; } serialiseLength( os, contacts.length, 64 ); for (int i=0;i<contacts.length;i++){ try{ serialiseAltContact( os, contacts[i] ); }catch( DHTTransportException e ){ Debug.printStackTrace(e); // not much we can do here to recover - shouldn't fail anyways throw( new IOException(e.getMessage())); } } }
public void writeOut(File f) throws IOException { DataOutputStream out = new DataOutputStream(new FileOutputStream(f)); out.writeUTF(name); out.writeInt(sizeOfSet); out.writeInt(desc.size()); for(int i=0;i<desc.size();i++) { out.writeUTF(desc.get(i).stringData); desc.get(i).descData.writeOut(out); } out.close(); }