/** * Converts this chunk into an array of bytes representation. Normally you will not need to * override this method unless your header changes based on the contents / size of the payload. */ @Override public final byte[] toByteArray(boolean shrink) throws IOException { ByteBuffer header = ByteBuffer.allocate(getHeaderSize()).order(ByteOrder.LITTLE_ENDIAN); writeHeader(header, 0); // The chunk size isn't known yet. This will be filled in later. ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (LittleEndianDataOutputStream payload = new LittleEndianDataOutputStream(baos)) { writePayload(payload, header, shrink); } byte[] payloadBytes = baos.toByteArray(); int chunkSize = getHeaderSize() + payloadBytes.length; header.putInt(CHUNK_SIZE_OFFSET, chunkSize); // Combine results ByteBuffer result = ByteBuffer.allocate(chunkSize).order(ByteOrder.LITTLE_ENDIAN); result.put(header.array()); result.put(payloadBytes); return result.array(); }
@Override protected void writePayload(DataOutput output, ByteBuffer header, boolean shrink) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int stringOffset = 0; ByteBuffer offsets = ByteBuffer.allocate(getOffsetSize()); offsets.order(ByteOrder.LITTLE_ENDIAN); // Write to a temporary payload so we can rearrange this and put the offsets first try (LittleEndianDataOutputStream payload = new LittleEndianDataOutputStream(baos)) { stringOffset = writeStrings(payload, offsets, shrink); writeStyles(payload, offsets, shrink); } output.write(offsets.array()); output.write(baos.toByteArray()); if (!styles.isEmpty()) { header.putInt(STYLE_START_OFFSET, getHeaderSize() + getOffsetSize() + stringOffset); } }
@Override public byte[] toByteArray(boolean shrink) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (LittleEndianDataOutputStream payload = new LittleEndianDataOutputStream(baos)) { for (StringPoolSpan span : spans()) { byte[] encodedSpan = span.toByteArray(shrink); if (encodedSpan.length != StringPoolSpan.SPAN_LENGTH) { throw new IllegalStateException("Encountered a span of invalid length."); } payload.write(encodedSpan); } payload.writeInt(RES_STRING_POOL_SPAN_END); } return baos.toByteArray(); }
@Override public boolean writeMessage(OutputStream outputStream, ProgressReporter progressReporter) throws IOException { dataOutputStream = new LittleEndianDataOutputStream(outputStream); switch (mode) { case START: if (!writeStart()) { mode = Mode.END; return false; } mode = Mode.DATA; break; case DATA: if (!writeData()) { mode = Mode.END; return false; } break; case END: return false; default: break; } return true; }
public IfcGeomServerClient(String executableFilename) throws RenderEngineException { try { process = Runtime.getRuntime().exec(executableFilename); dos = new LittleEndianDataOutputStream(process.getOutputStream()); dis = new LittleEndianDataInputStream(process.getInputStream()); if (dis.readInt() != HELLO) { terminate(); LOGGER.error("Invalid welcome message received"); return; } Hello h = new Hello(); h.read(dis); String reportedVersion = h.getString(); if (!VERSION.equals(reportedVersion)) { terminate(); LOGGER.error(String.format("Version mismatch: Plugin version %s does not match IfcOpenShell version %s", VERSION, reportedVersion)); return; } } catch (IOException e) { throw new RenderEngineException(e); } }
public void testReadShort() throws IOException { byte a[] = new byte[]{0,1,2,3}; ByteArrayInputStream bais = new ByteArrayInputStream(a); int bos = ByteOp.readShort(bais); System.out.format("BO.Read short(%d)\n", bos); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(a)); int disv = dis.readUnsignedShort(); System.out.format("DI.Read short(%d)\n", disv); for(int i = 0; i < 256 * 256; i++) { ByteArrayOutputStream baos = new ByteArrayOutputStream(2); LittleEndianDataOutputStream dos = new LittleEndianDataOutputStream(baos); dos.writeShort(i); ByteArrayInputStream bais2 = new ByteArrayInputStream(baos.toByteArray()); int gotI = ByteOp.readShort(bais2); assertEquals(i, gotI); } }
@Override protected void writePayload(DataOutput output, ByteBuffer header, boolean shrink) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteBuffer offsets = ByteBuffer.allocate(getOffsetSize()).order(ByteOrder.LITTLE_ENDIAN); try (LittleEndianDataOutputStream payload = new LittleEndianDataOutputStream(baos)) { writeEntries(payload, offsets, shrink); } output.write(offsets.array()); output.write(baos.toByteArray()); }
@Override public boolean writeMessage(OutputStream outputStream, ProgressReporter progressReporter) throws IOException, SerializerException, InterruptedException, ExecutionException { this.progressReporter = progressReporter; dataOutputStream = new LittleEndianDataOutputStream(outputStream); switch (mode) { case LOAD: { load(); mode = Mode.START; // Explicitly no break here, move on to start right away } case START: writeStart(); mode = Mode.DATA; break; case DATA: if (!writeData()) { mode = Mode.END; return true; } break; case END: writeEnd(); return false; default: break; } return true; }
@Override public void writeTo(OutputStream outputStream) throws IOException { LittleEndianDataOutputStream out = new LittleEndianDataOutputStream(outputStream); for (Metric metric : metrics) { writeMetric(metric, out); } }
/** * (metric, value, timestamp, date, updated) * * @param metric * @param out * @throws IOException */ private void writeMetric(Metric metric, LittleEndianDataOutputStream out) throws IOException { writeUnsignedLeb128(metric.getMetricDescription().getNameLength(), out); metric.getMetricDescription().writeName(out); out.writeDouble(metric.getValue()); out.writeInt((int) Integer.toUnsignedLong(metric.getTimestampSeconds())); out.writeShort(getUnsignedDaysSinceEpoch(metric.getTimestampSeconds())); out.writeInt((int) Integer.toUnsignedLong(metric.getUpdatedSeconds())); }
private static void writeUnsignedLeb128(int value, LittleEndianDataOutputStream out) throws IOException { int remaining = value >>> 7; while (remaining != 0) { out.write((byte) ((value & 0x7f) | 0x80)); value = remaining; remaining >>>= 7; } out.write((byte) (value & 0x7f)); }
public byte[] serialize() { ByteArrayOutputStream out; out = new ByteArrayOutputStream(getSerializedSize()); try { write(new LittleEndianDataOutputStream(out)); } catch (IOException ioe) { throw new RuntimeException("Unexpected exception", ioe); } return out.toByteArray(); }
void write(LittleEndianDataOutputStream s) throws IOException { s.writeInt(iden); ByteArrayOutputStream oss = new ByteArrayOutputStream(); write_contents(new LittleEndianDataOutputStream(oss)); // Comment Ruben: It seems redundant to send the size twice (when sending a String, LittleEndianness should not change the size I think) // Also storing the intermediate results in another buffer can be avoided I think, why not send the original s variable to write_contents? s.writeInt(oss.size()); s.write(oss.toByteArray()); s.flush(); }
protected void writeString(LittleEndianDataOutputStream s, String str) throws IOException { byte[] b = str.getBytes(Charsets.UTF_8); int len = b.length; s.writeInt(len); s.write(b); while (len++ % 4 != 0) s.write(0); }
@Override void write_contents(LittleEndianDataOutputStream s) throws IOException { if (length == -1) { // This is now the point where memory problems will arise for large models ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(ifcInputStream, baos); writeStringBinary(s, baos.toByteArray()); } else { writeStringBinary(s, ifcInputStream, (int) length); } }
public Output(OutputStream base, int nBufferSize) { if(nBufferSize < 0) throw new ArrayIndexOutOfBoundsException("nBufferSize"); if(nBufferSize == 0) nBufferSize = m_nDefaultBufferSize; m_bwOutput = new LittleEndianDataOutputStream(base); m_pbBuffer = new byte[nBufferSize]; }
public String encode() { final StringWriter outputWriter = new StringWriter(); try (final LittleEndianDataOutputStream outputStream = new LittleEndianDataOutputStream( new DeflaterOutputStream(BASE64_ENCODER.encodingStream(outputWriter)))) { outputStream.writeInt(length); outputStream.write(labelData.array()); outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } return outputWriter.toString() + ";"; }
@Test public void whenWriteReadLittleEndian_thenCorrect() throws IOException { final int value = 100; final LittleEndianDataOutputStream writer = new LittleEndianDataOutputStream(new FileOutputStream("src/test/resources/test_le.txt")); writer.writeInt(value); writer.close(); final LittleEndianDataInputStream reader = new LittleEndianDataInputStream(new DataInputStream(new FileInputStream("src/test/resources/test_le.txt"))); final int result = reader.readInt(); reader.close(); assertEquals(value, result); }
@Override public void serialize(int[] a, File file) throws IOException { LittleEndianDataOutputStream os = new LittleEndianDataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); for (int val : a) { os.writeInt(val); } os.close(); }
/** * @param path root lsm tree index directory * @param iterator the iterator * @param keySerializer the key serializer * @param valueSerializer the value serializer * @param blocksize block size * @param keepDeletions true to keep deletion * @param <K> the key type * @param <V> the value type * @throws IOException if an I/O error occurs */ public static <K, V> void write( Path path, Iterator<Generation.Entry<K,V>> iterator, Serializer<K> keySerializer, Serializer<V> valueSerializer, final int blocksize, boolean keepDeletions ) throws IOException { if (blocksize > 65536) throw new IllegalArgumentException("block size must be less than 65536"); Files.createDirectories(path); final BufferedFileDataOutputStream fileOut = new BufferedFileDataOutputStream(path.resolve("index.bin")); final CountingOutputStream out = new CountingOutputStream(fileOut); //tempFile is deleted in writeIndex final Path tempPath = Files.createTempFile("tmp", ".bin"); final WriteLevelResult result = writeLevel(out, tempPath, iterator, keySerializer, valueSerializer, blocksize, keepDeletions); final int tmpCount = result.tmpCount; final long size = result.size; final long valueLevelLength = out.getCount(); final Header header = writeIndex(out, tempPath, tmpCount, keySerializer, blocksize); header.valueLevelLength = valueLevelLength; header.size = size; header.hasDeletions = keepDeletions; new HeaderSerializer().write(header, new LittleEndianDataOutputStream(out)); fileOut.sync(); out.close(); }
@Override public void write(OutputStream outputStream) throws Exception { LittleEndianDataOutputStream out = new LittleEndianDataOutputStream(outputStream); for (Event event : value) { GenericRecord record = event.properties(); Object time = record.get(projectConfig.getTimeColumn()); writeValue(time == null ? 0 : ((int) (((long) time) / 86400)), DATE, out); for (int i = 0; i < schema.size(); i++) { writeValue(record.get(i), schema.get(i).getType(), out); } } }
/** * Stores the texture map in the specified output stream, storing the integers * in little endian byte order * @param out the output stream to write the texture map into * @param textureMap the texture map to write * @throws MapGeneratorException when the size of the texture map is invalid * @throws IOException when the resulting map can't be written */ protected void storeByteStream(OutputStream out, int[][] textureMap) throws MapGeneratorException, IOException { if (isValidSize(textureMap)) { // byte outputput stream, wrapped by a little endian integer processor ByteArrayOutputStream bos = new ByteArrayOutputStream(byteAmount); LittleEndianDataOutputStream dos = new LittleEndianDataOutputStream(bos); // pass the resulting integers to the little endian byte output stream for (int y = 0; y < edgeLength; y++) { for (int x = 0; x < edgeLength; x++) { dos.writeInt(textureMap[x][y]); } } // writeTo to the user defined output streame bos.writeTo(out); // close streams dos.close(); bos.close(); } else { throw new MapGeneratorException("The size of the texture map is invalid. " + "Only Maps with 2048 * 2048 blocks are allowed"); } }
/** * Stores the relief map in the specified output stream, transforming * the floats to little endian 32 bit integers. * @param out the output stream to write the relief map into * @param reliefMap the relief map to write * @throws MapGeneratorException when the size of the relief map is invalid * @throws IOException when the resulting map can't be written */ protected void storeByteStream(OutputStream out, float[][] reliefMap) throws MapGeneratorException, IOException { if (isValidSize(reliefMap)) { // byte outputput stream, wrapped by a little endian integer processor ByteArrayOutputStream bos = new ByteArrayOutputStream(byteAmount); LittleEndianDataOutputStream dos = new LittleEndianDataOutputStream(bos); // pass the resulting integers to the little endian byte output stream for (int y = 0; y < edgeLength; y++) { for (int x = 0; x < edgeLength; x++) { // convert the floats (meter) to integers (millimeter) dos.writeInt((int) (reliefMap[y][x] * 1000)); } } // write to the user defined output stream bos.writeTo(out); // close streams dos.close(); bos.close(); } else { throw new MapGeneratorException("The size of the relief map is invalid. " + "Only Maps with 2049 * 2049 control points are allowed"); } }
public void writeTo(LittleEndianDataOutputStream dataOutputStream) throws IOException { min.writeTo(dataOutputStream); max.writeTo(dataOutputStream); }
public void writeTo(LittleEndianDataOutputStream dataOutputStream) throws IOException { dataOutputStream.writeDouble(x); dataOutputStream.writeDouble(y); dataOutputStream.writeDouble(z); }
public void writeTo(LittleEndianDataOutputStream dataOutputStream) throws IOException { dataOutputStream.writeFloat(x); dataOutputStream.writeFloat(y); dataOutputStream.writeFloat(z); }
public boolean writeToGameEngineActivity(int attempt, String user, String pass, String code) { if (attempt > 5) { KRFAM.Toast("Failed to write to '" + codeName + "' A.D File.\nHave you allowed KRFAM to have root access?"); return false; } if (installed == true) { SaveData value = new SaveData(); value.m_UUID = user; value.m_AccessToken = pass; value.m_MyCode = code; value.m_ConfirmedVer = 0; String _iv = createPassword(); byte[] iv = _iv.getBytes(); KRFAM.log("iv " + _iv); try { MessagePack.PackerConfig config = new MessagePack.PackerConfig().withStr8FormatSupport(false); ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory(config)); byte[] bytes = objectMapper.writeValueAsBytes(value); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec skeySpec = new SecretKeySpec(this.EncryptKey.getBytes(), "AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv)); byte[] encrypted = cipher.doFinal(bytes); OutputStream is = new FileOutputStream(SaveFile); LittleEndianDataOutputStream binaryWriter = new LittleEndianDataOutputStream(is); int num1 = new Random().nextInt(); byte num2 = (byte) (num1 & 127); int num3 = (int) ((long) num1 & 4294902015L) | 65280 & 19 << 8; // 19 denotes 171101 /* 16 - 20: _170404, _170713, _171101, _latest, */ binaryWriter.writeInt(num3); for (int index = 0; index < iv.length; ++index) iv[index] += (byte) (96 + (int) (byte) index); binaryWriter.writeByte((byte) ((int) iv.length + (int) num2)); binaryWriter.write(iv); binaryWriter.writeInt(encrypted.length); binaryWriter.write(encrypted); } catch (Exception ex) { KRFAM.log(ex); KRFAM.log(codeName + " > Failed to Write A.D File"); KRFAM.forcePermission(adFile); KRFAM.forcePermission(adFile.getParentFile()); } KRFAM.log("saved uu " + uuid); KRFAM.log("saved at " + accessToken); updateFromADFile(); if (uuid.equals(user) && accessToken.equals(pass)) { return true; } else { KRFAM.forcePermission(adFile); KRFAM.forcePermission(adFile.getParentFile()); return writeToGameEngineActivity(attempt + 1, user, pass, code); } } else { KRFAM.Toast(codeName + " not installed"); return false; } }