List of usage examples for java.nio ByteBuffer wrap
public static ByteBuffer wrap(byte[] array)
From source file:StreamUtility.java
/** * Converts little endian Unicode bytes to a String * @param value byte array of Unicode Little Endian * @return String value of the byte array *//*from www . j a va 2s . com*/ public static String littleEndianToString(byte[] value) { return ByteBuffer.wrap(value).order(ByteOrder.LITTLE_ENDIAN).asCharBuffer().toString(); }
From source file:cn.com.sunjiesh.wechat.handler.WechatBaseHandler.java
/** * ?/*from w w w.jav a 2 s . com*/ * * @param httpResponse httpResponse * @param fileTpye fileTpye * @return File * @throws ServiceException ServiceException */ public static File getFileResponseFromHttpResponse(HttpResponse httpResponse, String fileTpye) throws ServiceException { File file = null; try { StatusLine httpStatusLine = httpResponse.getStatusLine(); HttpEntity httpEntity = httpResponse.getEntity(); int statusCode = httpStatusLine.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { LOGGER.error(DOWNLOAD_FILE_ERROR); throw new ServiceException(DOWNLOAD_FILE_ERROR); } String fileName = UUID.randomUUID().toString(); fileName = fileName + "." + fileTpye; InputStream is = httpEntity.getContent(); if (!StringUtils.isEmpty(fileName)) { //?? file = new File("/var/tmp", fileName); if (file.exists()) { file.delete(); } FileOutputStream fos = new FileOutputStream(file, false); FileChannel fileChannel = fos.getChannel(); ByteBuffer byteBuffer = null; byte[] tempBytes = new byte[4096]; while (is.read(tempBytes) > 0) { byteBuffer = ByteBuffer.wrap(tempBytes); fileChannel.write(byteBuffer); } if (fos != null) { fos.close(); } fileChannel.close(); } } catch (IllegalStateException e) { LOGGER.error(DOWNLOAD_FILE_ERROR, e); throw new ServiceException(DOWNLOAD_FILE_ERROR, e); } catch (FileNotFoundException e) { LOGGER.error(DOWNLOAD_FILE_ERROR, e); throw new ServiceException(DOWNLOAD_FILE_ERROR, e); } catch (IOException e) { LOGGER.error(DOWNLOAD_FILE_ERROR, e); throw new ServiceException(DOWNLOAD_FILE_ERROR, e); } return file; }
From source file:com.rackspacecloud.blueflood.io.serializers.TimerSerializationTest.java
@Test public void testV1RoundTrip() throws IOException { // build up a Timer TimerRollup r0 = new TimerRollup().withSum(42).withCountPS(23.32d).withAverage(56).withVariance(853.3245d) .withMinValue(2).withMaxValue(987).withCount(345); r0.setPercentile("foo", 741.32d); r0.setPercentile("bar", 0.0323d); if (System.getProperty("GENERATE_TIMER_SERIALIZATION") != null) { OutputStream os = new FileOutputStream( "src/test/resources/serializations/timer_version_" + Constants.VERSION_1_TIMER + ".bin", false); os.write(Base64.encodeBase64(new NumericSerializer.TimerRollupSerializer().toByteBuffer(r0).array())); os.write("\n".getBytes()); os.close();/* w ww . j av a 2 s . c o m*/ } Assert.assertTrue(new File("src/test/resources/serializations").exists()); // ensure historical reads work. int version = 0; int maxVersion = Constants.VERSION_1_TIMER; int count = 0; while (version <= maxVersion) { BufferedReader reader = new BufferedReader( new FileReader("src/test/resources/serializations/timer_version_" + version + ".bin")); ByteBuffer bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes())); TimerRollup r1 = new NumericSerializer.TimerRollupSerializer().fromByteBuffer(bb); Assert.assertEquals(r0, r1); count++; version++; } Assert.assertTrue("Nothing was tested", count > 0); }
From source file:c5db.client.ProtobufUtil.java
/** * Create a protocol buffer Get based on a client Get. * * @param get The client Get./* w w w. ja v a 2 s. c o m*/ * @param existenceOnly Is this only an existence check. * @return a protocol buffer Get * @throws IOException */ @NotNull public static c5db.client.generated.Get toGet(final Get get, boolean existenceOnly) throws IOException { c5db.client.generated.TimeRange timeRange; ByteBuffer row = ByteBuffer.wrap(get.getRow()); boolean cacheBlocks = get.getCacheBlocks(); int maxVersions = get.getMaxVersions(); List<Column> columns = new ArrayList<>(); List<NameBytesPair> attributes = new ArrayList<>(); int storeLimit; int storeOffset; c5db.client.generated.Filter filter = get.getFilter() == null ? null : ProtobufUtil.toFilter(get.getFilter()); if (!get.getTimeRange().isAllTime()) { timeRange = new c5db.client.generated.TimeRange(get.getTimeRange().getMin(), get.getTimeRange().getMax()); } else { timeRange = new c5db.client.generated.TimeRange(0, Long.MAX_VALUE); } Map<String, byte[]> attributesMap = get.getAttributesMap(); if (!attributes.isEmpty()) { for (Map.Entry<String, byte[]> attribute : attributesMap.entrySet()) { NameBytesPair updatedAttribute = new NameBytesPair(attribute.getKey(), ByteBuffer.wrap(attribute.getValue())); attributes.add(updatedAttribute); } } if (get.hasFamilies()) { Map<byte[], NavigableSet<byte[]>> families = get.getFamilyMap(); for (Map.Entry<byte[], NavigableSet<byte[]>> family : families.entrySet()) { List<ByteBuffer> qualifiers = new ArrayList<>(); if (family.getValue() != null) { for (byte[] qualifier : family.getValue()) { qualifiers.add(ByteBuffer.wrap(qualifier)); } } Column column = new Column(ByteBuffer.wrap(family.getKey()), qualifiers); columns.add(column); } } storeLimit = get.getMaxResultsPerColumnFamily(); storeOffset = get.getRowOffsetPerColumnFamily(); return new c5db.client.generated.Get(row, columns, attributes, filter, timeRange, maxVersions, cacheBlocks, storeLimit, storeOffset, existenceOnly, false); }
From source file:com.codestation.henkakuserver.HenkakuServer.java
private Pair<ArrayList<Integer>, List<Byte>> preprocessRop(byte[] urop) throws Exception { byte[] loader = new byte[urop.length + ((-urop.length) & 3)]; System.arraycopy(urop, 0, loader, 0, urop.length); ByteBuffer buf = ByteBuffer.wrap(loader).order(ByteOrder.LITTLE_ENDIAN); int header_size = 0x40; int dsize = buf.getInt(0x10); int csize = buf.getInt(0x20); int reloc_size = buf.getInt(0x30); int symtab_size = buf.getInt(0x38); if (csize % 4 != 0) { throw new Exception("csize % 4 != 0???"); }// w w w . j av a2 s. c o m int reloc_offset = header_size + dsize + csize; int symtab = reloc_offset + reloc_size; int symtab_n = symtab_size / 8; Map<Integer, String> reloc_map = new HashMap<>(); for (int x = 0; x < symtab_n; ++x) { int sym_id = buf.getInt(symtab + 8 * x); int str_offset = buf.getInt(symtab + 8 * x + 4); int end = str_offset; while (loader[end] != 0) { end += 1; } String name = new String(Arrays.copyOfRange(loader, str_offset, end)); reloc_map.put(sym_id, name); } Map<Pair<String, Integer>, Integer> reloc_type_map = new HashMap<>(); reloc_type_map.put(new Pair<>("rop.data", 0), 1); reloc_type_map.put(new Pair<>("SceWebKit", 0), 2); reloc_type_map.put(new Pair<>("SceLibKernel", 0), 3); reloc_type_map.put(new Pair<>("SceLibc", 0), 4); reloc_type_map.put(new Pair<>("SceLibHttp", 0), 5); reloc_type_map.put(new Pair<>("SceNet", 0), 6); reloc_type_map.put(new Pair<>("SceAppMgr", 0), 7); int want_len = 0x40 + dsize + csize; ArrayList<Integer> urop_js = new ArrayList<>(); byte[] relocs = new byte[want_len / 4]; int reloc_n = reloc_size / 8; for (int x = 0; x < reloc_n; ++x) { int reloc_type = buf.getShort(reloc_offset + 8 * x); int sym_id = buf.getShort(reloc_offset + 8 * x + 2); int offset = buf.getInt(reloc_offset + 8 * x + 4); if (offset % 4 != 0) { throw new Exception("offset % 4 != 0???"); } if (relocs[offset / 4] != 0) { throw new Exception("symbol relocated twice, not supported"); } Integer wk_reloc_type = reloc_type_map.get(new Pair<>(reloc_map.get(sym_id), reloc_type)); if (wk_reloc_type == null) { throw new Exception("unsupported relocation type"); } relocs[offset / 4] = wk_reloc_type.byteValue(); } for (int x = 0; x < want_len; x += 4) { urop_js.add(buf.getInt(x)); } List<Byte> relocsArray = Arrays.asList(ArrayUtils.toObject(relocs)); return new Pair<>(urop_js, relocsArray); }
From source file:org.hawkular.metrics.core.api.Availability.java
@JsonIgnore public ByteBuffer getBytes() { return ByteBuffer.wrap(new byte[] { type.getCode() }); }
From source file:com.rackspacecloud.blueflood.io.serializers.astyanax.StringSerializerTest.java
@Test(expected = UnexpectedStringSerializationException.class) public void testDeserializeStringDoesNotFail() throws Throwable { // this is what a string looked like previously. try {// www .j av a 2 s . c o m String serialized = "AHMWVGhpcyBpcyBhIHRlc3Qgc3RyaW5nLg=="; ByteBuffer bb = ByteBuffer.wrap(Base64.decodeBase64(serialized.getBytes())); Serializers.serializerFor(SimpleNumber.class).fromByteBuffer(bb); } catch (RuntimeException ex) { throw ex.getCause(); } }
From source file:cfa.vo.interop.EncodeDoubleArray.java
public static double[] decodeBase64(String dataString, boolean swapByteOrder) throws IOException { byte[] encodedData = dataString.getBytes(); Base64 codec = new Base64(); byte[] decodedData = codec.decode(encodedData); if (swapByteOrder) { ByteBuffer buf = ByteBuffer.wrap(decodedData); buf = buf.order(ByteOrder.LITTLE_ENDIAN); buf.get(decodedData);/*from w w w . j a va 2 s. c o m*/ } double[] result = byteToDouble(decodedData); return result; }
From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java
/** * This test cannot run on Windows without extra privileges *//* w w w . ja v a2s . c o m*/ @Test public void testSymlink() throws IOException { assumeFalse(Platform.isWindows()); final Path tempDir = Files.createTempDirectory("ds3_file_object_putter_"); final Path tempPath = Files.createTempFile(tempDir, "temp_", ".txt"); try { try (final SeekableByteChannel channel = Files.newByteChannel(tempPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) { channel.write(ByteBuffer.wrap(testData)); } final Path symLinkPath = tempDir.resolve("sym_" + tempPath.getFileName().toString()); Files.createSymbolicLink(symLinkPath, tempPath); getFileWithPutter(tempDir, symLinkPath); } finally { Files.deleteIfExists(tempPath); Files.deleteIfExists(tempDir); } }
From source file:com.jordanwilliams.heftydb.test.generator.KeyValueGenerator.java
private ByteBuffer randomValue(int size) { String randomString = RandomStringUtils.randomAlphanumeric(size); return ByteBuffer.wrap(randomString.getBytes(Charset.defaultCharset())); }