List of usage examples for java.nio ByteBuffer wrap
public static ByteBuffer wrap(byte[] array)
From source file:byps.test.TestSerializeInlineInstances.java
public ByteBuffer readAll(String fileName) throws IOException { FileInputStream fis = null;//from ww w . ja va2s.co m File file = new File(fileName); try { fis = new FileInputStream(file); byte[] buf = new byte[(int) file.length()]; fis.read(buf); return ByteBuffer.wrap(buf); } finally { if (fis != null) fis.close(); } }
From source file:au.org.ala.delta.translation.dist.DistItemsFileWriter.java
protected Pair<List<Integer>, List<Integer>> writeItems(int[] wordOffsets, int[] bitOffsets) { final int BYTES_IN_WORD = 4; List<Integer> itemRecords = new ArrayList<Integer>(); List<Integer> nameLengths = new ArrayList<Integer>(); int size = BinaryKeyFile.RECORD_LENGTH_BYTES; for (int offset : wordOffsets) { size = Math.max(size, offset); }/*from w ww .jav a 2 s . c om*/ Iterator<Item> items = _dataSet.unfilteredItems(); while (items.hasNext()) { Item item = items.next(); String description = _itemFormatter.formatItemDescription(item); nameLengths.add(description.length()); byte[] bytes = new byte[(size + 1) * BYTES_IN_WORD]; Arrays.fill(bytes, (byte) 0); ByteBuffer work = ByteBuffer.wrap(bytes); work.order(ByteOrder.LITTLE_ENDIAN); Iterator<IdentificationKeyCharacter> chars = _dataSet.unfilteredIdentificationKeyCharacterIterator(); while (chars.hasNext()) { IdentificationKeyCharacter keyChar = chars.next(); int charNum = keyChar.getCharacterNumber(); if (!keyChar.getCharacterType().isText()) { int offset = wordOffsets[keyChar.getCharacterNumber() - 1] - 1; if (!(keyChar.getCharacterType() == CharacterType.UnorderedMultiState)) { work.putFloat(offset * BYTES_IN_WORD, -9999.0f); } Attribute attribute = item.getAttribute(keyChar.getCharacter()); if (attribute == null || attribute.isUnknown()) { continue; } switch (keyChar.getCharacterType()) { case UnorderedMultiState: encodeUnorderedMultistateAttribute(work, wordOffsets[charNum - 1] - 1, bitOffsets[charNum - 1], keyChar, (MultiStateAttribute) attribute); break; case OrderedMultiState: encodeOrderedMultistateAttribute(work, wordOffsets[charNum - 1] - 1, keyChar, (MultiStateAttribute) attribute); break; case IntegerNumeric: case RealNumeric: encodeNumericAttribute(work, wordOffsets[charNum - 1] - 1, keyChar, (NumericAttribute) attribute); break; } } } itemRecords.add(_itemsFile.writeItem(description, work)); } return new Pair<List<Integer>, List<Integer>>(itemRecords, nameLengths); }
From source file:com.twitter.distributedlog.service.balancer.TestClusterBalancer.java
private void writeStreams(String namePrefix, int numStreams, int streamId) throws Exception { for (int i = 0; i < numStreams; i++) { String name = namePrefix + (streamId++); try {/*w ww . ja v a 2 s. c o m*/ Await.result(((DistributedLogClient) client.dlClient).write(name, ByteBuffer.wrap(name.getBytes(UTF_8)))); } catch (Exception e) { logger.error("Error writing stream {} : ", name, e); throw e; } } }
From source file:etc.CloudStorage.java
/** * * This upload method expects a file and simply displays the file in the * multipart upload again to the user (in the correct mime encoding). * * * @return// ww w . j a v a 2 s .co m * @throws Exception * @param context */ public Mp3 uploadMp3(Context context) throws Exception { // make sure the context really is a multipart context... Mp3 mp3 = null; if (context.isMultipart()) { // This is the iterator we can use to iterate over the contents of the request. try { FileItemIterator fileItemIterator = context.getFileItemIterator(); while (fileItemIterator.hasNext()) { FileItemStream item = fileItemIterator.next(); String name = item.getName(); // Store audio file GcsFilename filename = new GcsFilename("musaemachine.com", name); // Store generated waveform image GcsFilename waveImageFile = new GcsFilename("musaemachine.com", removeExtension(name).concat(".png")); InputStream stream = item.openStream(); String contentType = item.getContentType(); System.out.println("--- " + contentType); GcsFileOptions options = new GcsFileOptions.Builder().acl("public-read").mimeType(contentType) .build(); byte[] audioBuffer = getByteFromStream(stream); GcsOutputChannel outputChannel = gcsService.createOrReplace(filename, options); outputChannel.write(ByteBuffer.wrap(audioBuffer)); outputChannel.close(); // AudioWaveformCreator awc = new AudioWaveformCreator(); // byte[]waveform= awc.createWavForm(stream); // System.out.println("Buff Image---- "+waveform); // Saving waveform image // GcsOutputChannel waveFormOutputChannel = // gcsService.createOrReplace(waveImageFile, options); // waveFormOutputChannel.write(ByteBuffer.wrap(audioBuffer)); // waveFormOutputChannel.close(); // BodyContentHandler handler = new BodyContentHandler(); ParseContext pcontext = new ParseContext(); Metadata metadata = new Metadata(); mp3Parser.parse(stream, handler, metadata, pcontext); Double duration = Double.parseDouble(metadata.get("xmpDM:duration")); mp3 = new Mp3(name, duration); } } catch (Exception e) { e.printStackTrace(); } } return mp3; }
From source file:de.csdev.ebus.command.EBusCommandRegistry.java
/** * Search for a command method for the given telegram * * @param data The complete unescaped eBUS telegram * @return Returns the a list of all matching configuration methods or an empty list *//*w w w . ja v a 2s . c o m*/ public List<IEBusCommandMethod> find(byte[] data) { ByteBuffer buffer = ByteBuffer.wrap(data); return find(buffer); }
From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
private static void writeToSocket(SocketChannel client, byte[] bytes) throws IOException { client.write(ByteBuffer.wrap(bytes)); client.socket().getOutputStream().flush(); }
From source file:ConversionUtil.java
public static int convertToInt(byte[] array) { ByteBuffer buffer = ByteBuffer.wrap(array); return buffer.getInt(); /*/*from w ww.j a v a2s . c o m*/ int value = 0; for (int i =0;i<array.length; ++i) { int offset = (array.length -i-1) *8; value += (array[i] << offset); // bytes[i] = (byte)((value & (0xff << offset)) >>> offset); } return value; **/ }
From source file:com.rackspacecloud.blueflood.io.serializers.SerializationTest.java
@Test public void testBadSerializationVersion() { byte[] buf = new byte[] { 99, 99 }; // hopefully we won't have 99 different serialization versions. for (Class type : SERIALIZABLE_TYPES) { try {/* ww w. j av a 2s. c o m*/ Object o = NumericSerializer.serializerFor(type).fromByteBuffer(ByteBuffer.wrap(buf)); Assert.fail(String.format("Should have errored out %s", type.getName())); } catch (RuntimeException ex) { Assert.assertTrue(ex.getCause().getMessage().startsWith("Unexpected serialization version")); } } }
From source file:com.github.c77.base_driver.husky.HuskyBaseDevice.java
/** * Called every time there is new data received through the USB-serial interface *//*from ww w .j a v a 2 s .c o m*/ private void updateReceivedData(final byte[] bytes) { HuskyPacket packet = null; try { // Parse the packet packet = packetReader.parse(ByteBuffer.wrap(bytes)); } catch (HuskyParserException e) { log.error("Error parsing incoming packet", e); } // If we did get a new packet if (packet != null) { switch (packet.getMessageType()) { // It's encoder data: update odometry case HuskyPacket.TYPE_ENCODER_DATA: odometryStatus.update(packet.getPayload()); break; // Ignore the rest of the packets default: break; } } }
From source file:pl.allegro.tech.hermes.consumers.consumer.sender.http.ByteBufferEntityTest.java
@Test public void testWriteTo() throws Exception { final ByteBuffer bytes = ByteBuffer.wrap("Message content".getBytes(Consts.ASCII)); final ByteBufferEntity httpentity = new ByteBufferEntity(bytes); ByteArrayOutputStream out = new ByteArrayOutputStream(); httpentity.writeTo(out);//from w ww . ja v a2 s . co m byte[] bytes2 = out.toByteArray(); Assert.assertNotNull(bytes2); Assert.assertEquals(bytes.capacity(), bytes2.length); bytes.position(0); for (int i = 0; i < bytes2.length; i++) { Assert.assertEquals(bytes.get(i), bytes2[i]); } out = new ByteArrayOutputStream(); httpentity.writeTo(out); bytes2 = out.toByteArray(); Assert.assertNotNull(bytes2); Assert.assertEquals(bytes.capacity(), bytes2.length); bytes.position(0); for (int i = 0; i < bytes.capacity(); i++) { Assert.assertEquals(bytes.get(i), bytes2[i]); } try { httpentity.writeTo(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } }