List of usage examples for java.io DataOutputStream writeShort
public final void writeShort(int v) throws IOException
short
to the underlying output stream as two bytes, high byte first. From source file:it.jnrpe.net.JNRPEProtocolPacket.java
/** * Converts the packet object to its byte array representation. * /*from w w w. j av a2s. co m*/ * @return The byte array representation of this packet. */ public byte[] toByteArray() { ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); try { dout.writeShort(packetVersion); dout.writeShort(packetTypeCode); dout.writeInt(crcValue); dout.writeShort(resultCode); dout.write(byteBufferAry); dout.write(dummyBytesAry); dout.close(); } catch (IOException e) { // Never happens... throw new IllegalStateException(e.getMessage(), e); } return bout.toByteArray(); }
From source file:edu.umn.cs.spatialHadoop.nasa.StockQuadTree.java
/** * Constructs an aggregate quad tree out of a two-dimensional array of values. * //from w ww . j av a 2 s. co m * @param values * @param out * - the output stream to write the constructed quad tree to * @throws IOException */ public static void build(NASADataset metadata, short[] values, short fillValue, DataOutputStream out) throws IOException { int length = Array.getLength(values); int resolution = (int) Math.round(Math.sqrt(length)); // Write tree header out.writeInt(resolution); // resolution out.writeShort(fillValue); out.writeInt(1); // cardinality out.writeLong(metadata.time); // Timestamp // Fetch the stock quad tree of the associated resolution StockQuadTree stockQuadTree = getOrCreateStockQuadTree(resolution); // Sort values by their respective Z-Order values in linear time short[] sortedValues = new short[length]; for (int i = 0; i < length; i++) sortedValues[i] = values[stockQuadTree.r[i]]; // Write all sorted values for (short v : sortedValues) out.writeShort(v); // Compute aggregate values for all nodes in the tree // Go in reverse ID order to ensure children are computed before parents Node[] nodes = new Node[stockQuadTree.nodesID.length]; for (int iNode = stockQuadTree.nodesID.length - 1; iNode >= 0; iNode--) { // Initialize all aggregate values nodes[iNode] = new Node(); int firstChildId = stockQuadTree.nodesID[iNode] * 4; int firstChildPos = Arrays.binarySearch(stockQuadTree.nodesID, firstChildId); boolean isLeaf = firstChildPos < 0; if (isLeaf) { for (int iVal = stockQuadTree.nodesStartPosition[iNode]; iVal < stockQuadTree.nodesEndPosition[iNode]; iVal++) { short value; Object val = Array.get(sortedValues, iVal); if (val instanceof Short) { value = (Short) val; } else { throw new RuntimeException("Cannot handle values of type " + val.getClass()); } if (value != fillValue) nodes[iNode].accumulate(value); } } else { // Compute from the four children for (int iChild = 0; iChild < 4; iChild++) { int childPos = firstChildPos + iChild; nodes[iNode].accumulate(nodes[childPos]); } } } // Write nodes to file in sorted order for (int iNode = 0; iNode < nodes.length; iNode++) nodes[iNode].write(out); }
From source file:it.jnrpe.net.JNRPEProtocolPacket.java
/** * Validates the packet CRC.// w ww. j a va2s. co m * * @throws BadCRCException * If the CRC can't be validated */ public void validate() throws BadCRCException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); try { dout.writeShort(packetVersion); dout.writeShort(packetTypeCode); dout.writeInt(0); // NO CRC dout.writeShort(resultCode); dout.write(byteBufferAry); dout.write(dummyBytesAry); dout.close(); byte[] vBytes = bout.toByteArray(); CRC32 crcAlg = new CRC32(); crcAlg.update(vBytes); if (!(((int) crcAlg.getValue()) == crcValue)) { throw new BadCRCException("Bad CRC"); } } catch (IOException e) { // Never happens... throw new IllegalStateException(e.getMessage(), e); } }
From source file:com.msopentech.thali.utilities.universal.HttpKeySocksProxyClientConnOperator.java
@Override public void openConnection(final OperatedClientConnection conn, final HttpHost target, final InetAddress local, final HttpContext context, final HttpParams params) throws IOException { Socket socket = null;/*from w ww .j a v a 2 s .c o m*/ Socket sslSocket = null; try { if (conn == null || target == null || params == null) { throw new IllegalArgumentException("Required argument may not be null"); } if (conn.isOpen()) { throw new IllegalStateException("Connection must not be open"); } // The original NetCipher code uses a SchemeSocketFactory class that isn't supported by the version // of Apache that ships standard with Android. It also doesn't support the layered socket factory // interface either. We work around this later on but for now we just get our HttpKeySSLSocketFactory Scheme scheme = schemeRegistry.getScheme(target.getSchemeName()); HttpKeySSLSocketFactory httpKeySSLSocketFactory = (HttpKeySSLSocketFactory) scheme.getSocketFactory(); int port = scheme.resolvePort(target.getPort()); String host = target.getHostName(); // Perform explicit SOCKS4a connection request. SOCKS4a supports remote host name resolution // (i.e., Tor resolves the hostname, which may be an onion address). // The Android (Apache Harmony) Socket class appears to support only SOCKS4 and throws an // exception on an address created using INetAddress.createUnresolved() -- so the typical // technique for using Java SOCKS4a/5 doesn't appear to work on Android: // https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/java/net/PlainSocketImpl.java // See also: http://www.mit.edu/~foley/TinFoil/src/tinfoil/TorLib.java, for a similar implementation // From http://en.wikipedia.org/wiki/SOCKS#SOCKS4a: // // field 1: SOCKS version number, 1 byte, must be 0x04 for this version // field 2: command code, 1 byte: // 0x01 = establish a TCP/IP stream connection // 0x02 = establish a TCP/IP port binding // field 3: network byte order port number, 2 bytes // field 4: deliberate invalid IP address, 4 bytes, first three must be 0x00 and the last one must not be 0x00 // field 5: the user ID string, variable length, terminated with a null (0x00) // field 6: the domain name of the host we want to contact, variable length, terminated with a null (0x00) socket = new Socket(); conn.opening(socket, target); socket.setSoTimeout(READ_TIMEOUT_MILLISECONDS); socket.connect(proxy.address(), CONNECT_TIMEOUT_MILLISECONDS); DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream()); outputStream.write((byte) 0x04); outputStream.write((byte) 0x01); outputStream.writeShort((short) port); outputStream.writeInt(0x01); outputStream.write((byte) 0x00); outputStream.write(host.getBytes()); outputStream.write((byte) 0x00); DataInputStream inputStream = new DataInputStream(socket.getInputStream()); if (inputStream.readByte() != (byte) 0x00 || inputStream.readByte() != (byte) 0x5a) { throw new IOException("SOCKS4a connect failed"); } inputStream.readShort(); inputStream.readInt(); // In the NetCipher code we cast to SchemeLayeredSocketFactory and call createLayeredSocket which amongst // other things takes 'params' as an argument. But none of this is supported in Android. When I looked in // Java at what createLayeredSocket was actually doing it was just calling createSocket with exactly the // arguments used below (it ignored params completely). So we should be good. sslSocket = ((HttpKeySSLSocketFactory) httpKeySSLSocketFactory).createSocket(socket, host, port, true); conn.opening(sslSocket, target); sslSocket.setSoTimeout(READ_TIMEOUT_MILLISECONDS); prepareSocket(sslSocket, context, params); conn.openCompleted(httpKeySSLSocketFactory.isSecure(sslSocket), params); // TODO: clarify which connection throws java.net.SocketTimeoutException? } catch (IOException e) { try { if (sslSocket != null) { sslSocket.close(); } if (socket != null) { socket.close(); } } catch (IOException ioe) { } throw e; } }
From source file:org.apache.jackrabbit.core.journal.FileRecordLog.java
/** * Write signature and major/minor.//from w w w .j a v a 2 s . c o m * * @param out input stream * @throws java.io.IOException if an I/O error occurs. */ private void writeHeader(DataOutputStream out) throws IOException { out.write(SIGNATURE); out.writeShort(MAJOR_VERSION); out.writeShort(MINOR_VERSION); }
From source file:SafeUTF.java
public void safeWriteUTF(DataOutputStream out, String str) throws IOException { if (str == null) { out.writeByte(NULL);//from ww w.j av a 2 s . co m } else { int len = str.length(); short numChunks; if (len == 0) { numChunks = 0; } else { numChunks = (short) (((len - 1) / chunkSize) + 1); } out.writeByte(NOT_NULL); out.writeShort(numChunks); int i = 0; while (len > 0) { int beginCopy = i * chunkSize; int endCopy = len <= chunkSize ? beginCopy + len : beginCopy + chunkSize; String theChunk = str.substring(beginCopy, endCopy); out.writeUTF(theChunk); len -= chunkSize; i++; } } }
From source file:com.ning.arecibo.util.timeline.times.TimelineCoderImpl.java
private void writeRepeatedDelta(final int delta, final int repeatCount, final DataOutputStream dataStream) throws IOException { if (repeatCount > 1) { if (repeatCount > MAX_BYTE_REPEAT_COUNT) { dataStream.writeByte(TimelineOpcode.REPEATED_DELTA_TIME_SHORT.getOpcodeIndex()); dataStream.writeShort(repeatCount); } else if (repeatCount == 2) { dataStream.writeByte(delta); } else {// ww w . ja v a 2 s .co m dataStream.writeByte(TimelineOpcode.REPEATED_DELTA_TIME_BYTE.getOpcodeIndex()); dataStream.writeByte(repeatCount); } } dataStream.writeByte(delta); }
From source file:com.igormaznitsa.jhexed.hexmap.HexFieldLayer.java
public void write(final OutputStream out) throws IOException { final DataOutputStream dout = out instanceof DataOutputStream ? (DataOutputStream) out : new DataOutputStream(out); dout.writeUTF(this.name); dout.writeUTF(this.comments); dout.writeShort(this.values.size()); for (int i = 0; i < this.values.size(); i++) { this.values.get(i).write(dout); }/*from w ww . ja v a 2 s . c o m*/ dout.writeInt(this.columns); dout.writeInt(this.rows); dout.writeBoolean(this.visible); final byte[] packed = Utils.packByteArray(this.array); dout.writeInt(packed.length); dout.write(packed); dout.flush(); }
From source file:com.tc.simple.apn.factories.PushByteFactory.java
@Override public byte[] buildPushBytes(int id, Payload payload) { byte[] byteMe = null; ByteArrayOutputStream baos = null; DataOutputStream dos = null; try {//from www.jav a2 s .c o m baos = new ByteArrayOutputStream(); dos = new DataOutputStream(baos); int expiry = 0; // (int) ((System.currentTimeMillis () / 1000L) + 7200); char[] cars = payload.getToken().trim().toCharArray(); byte[] tokenBytes = Hex.decodeHex(cars); //command dos.writeByte(1); //id dos.writeInt(id); //expiry dos.writeInt(expiry); //token length. dos.writeShort(tokenBytes.length); //token dos.write(tokenBytes); //payload length dos.writeShort(payload.getJson().length()); logger.log(Level.FINE, payload.getJson()); //payload. dos.write(payload.getJson().getBytes()); byteMe = baos.toByteArray(); } catch (Exception e) { logger.log(Level.SEVERE, null, e); } finally { CloseUtils.close(dos); CloseUtils.close(baos); } return byteMe; }
From source file:com.sky.drovik.player.media.DiskCache.java
private void writeIndex() { File tempFile = null;/*from w w w. java 2 s .c o m*/ final String tempFilePath = mCacheDirectoryPath; final String indexFilePath = getIndexFilePath(); try { tempFile = File.createTempFile("DiskCache", null, new File(tempFilePath)); } catch (Exception e) { Log.e(TAG, "Unable to create or tempFile " + tempFilePath); return; } try { final FileOutputStream fileOutput = new FileOutputStream(tempFile); final BufferedOutputStream bufferedOutput = new BufferedOutputStream(fileOutput, 1024); final DataOutputStream dataOutput = new DataOutputStream(bufferedOutput); // Write the index header. final int numRecords = mIndexMap.size(); dataOutput.writeInt(INDEX_HEADER_MAGIC); dataOutput.writeInt(INDEX_HEADER_VERSION); dataOutput.writeShort(mTailChunk); dataOutput.writeInt(numRecords); // Write the records. for (int i = 0; i < numRecords; ++i) { final long key = mIndexMap.keyAt(i); final Record record = mIndexMap.valueAt(i); dataOutput.writeLong(key); dataOutput.writeShort(record.chunk); dataOutput.writeInt(record.offset); dataOutput.writeInt(record.size); dataOutput.writeInt(record.sizeOnDisk); dataOutput.writeLong(record.timestamp); } // Close the file. dataOutput.close(); // Log.d(TAG, "Wrote index with " + numRecords + " records."); // Atomically overwrite the old index file. tempFile.renameTo(new File(indexFilePath)); } catch (Exception e) { // Was unable to perform the operation, we delete the temp file Log.e(TAG, "Unable to write the index file " + indexFilePath); tempFile.delete(); } }