List of usage examples for java.nio ByteBuffer wrap
public static ByteBuffer wrap(byte[] array)
From source file:org.apache.cxf.transport.http.asyncclient.CXFHttpAsyncRequestProducer.java
public void produceContent(final ContentEncoder enc, final IOControl ioc) throws IOException { if (content != null) { if (buffer == null) { if (content.getTempFile() == null) { buffer = ByteBuffer.wrap(content.getBytes()); } else { fis = content.getInputStream(); chan = (fis instanceof FileInputStream) ? ((FileInputStream) fis).getChannel() : Channels.newChannel(fis); buffer = ByteBuffer.allocate(8 * 1024); }//from www .j a v a2 s .c o m } int i = -1; buffer.rewind(); if (buffer.hasRemaining() && chan != null) { i = chan.read(buffer); buffer.flip(); } enc.write(buffer); if (!buffer.hasRemaining() && i == -1) { enc.complete(); } } else { buf.produceContent(enc, ioc); } }
From source file:com.cloudera.recordbreaker.learnstructure.test.GenerateRandomData.java
Object generateData(Schema s) { Schema.Type stype = s.getType(); if (stype == Schema.Type.ARRAY) { Schema arrayS = s.getElementType(); int numElts = 1 + r.nextInt(100); GenericData.Array result = new GenericData.Array(numElts, arrayS); for (int i = 0; i < numElts; i++) { result.add(generateData(arrayS)); }/* w ww. java2 s. c om*/ return arrayS; } else if (stype == Schema.Type.BOOLEAN) { return r.nextInt(2) == 0 ? new Boolean(true) : new Boolean(false); } else if (stype == Schema.Type.BYTES) { return ByteBuffer.wrap(new byte[16]); } else if (stype == Schema.Type.DOUBLE) { return new Double(r.nextDouble()); } else if (stype == Schema.Type.ENUM) { List<String> symbols = s.getEnumSymbols(); return symbols.get(r.nextInt(symbols.size())); } else if (stype == Schema.Type.FIXED) { return new GenericData.Fixed(s, new byte[16]); } else if (stype == Schema.Type.FLOAT) { return new Float(r.nextFloat()); } else if (stype == Schema.Type.INT) { return new Integer(r.nextInt()); } else if (stype == Schema.Type.LONG) { return new Long(r.nextLong()); } else if (stype == Schema.Type.MAP) { HashMap<Utf8, Object> result = new HashMap<Utf8, Object>(); Schema valType = s.getValueType(); int maxElts = 1 + r.nextInt(100); for (int i = 0; i < maxElts; i++) { result.put(new Utf8("label-" + i), generateData(valType)); } return result; } else if (stype == Schema.Type.NULL) { return null; } else if (stype == Schema.Type.RECORD) { GenericData.Record result = new GenericData.Record(s); for (Schema.Field f : s.getFields()) { result.put(f.name(), generateData(f.schema())); } return result; } else if (stype == Schema.Type.STRING) { return new Utf8("Rand-" + r.nextInt()); } else if (stype == Schema.Type.UNION) { List<Schema> types = s.getTypes(); return generateData(types.get(r.nextInt(types.size()))); } return null; }
From source file:com.buaa.cfs.common.oncrpc.XDR.java
/** * Wraps a byte array as a read-only XDR message. There's no copy involved, * thus it is the client's responsibility to ensure that the byte array * remains unmodified when using the XDR object. * * @param src/* www . ja v a2 s .c o m*/ * the byte array to be wrapped. */ public XDR(byte[] src) { this(ByteBuffer.wrap(src).asReadOnlyBuffer(), State.READING); }
From source file:com.sm.store.Utils.java
public static Value bytesToValue(byte[] bytes) { int len = bytes.length; ByteBuffer buf = ByteBuffer.wrap(bytes); long ver = buf.getLong(); short node = buf.getShort(); byte[] data = new byte[len - 10]; buf.get(data);//from w w w . j a v a2s .c om return CacheValue.createValue(data, ver, node); }
From source file:io.druid.segment.data.VSizeIndexedIntsWriterTest.java
private void checkSerializedSizeAndData() throws Exception { int maxValue = vals.length == 0 ? 0 : Ints.max(vals); VSizeIndexedIntsWriter writer = new VSizeIndexedIntsWriter(ioPeon, "test", maxValue); VSizeIndexedInts intsFromList = VSizeIndexedInts.fromList(Ints.asList(vals), maxValue); writer.open();/* w w w . j ava 2 s.c o m*/ for (int val : vals) { writer.add(val); } writer.close(); long writtenLength = writer.getSerializedSize(); final WritableByteChannel outputChannel = Channels.newChannel(ioPeon.makeOutputStream("output")); writer.writeToChannel(outputChannel); outputChannel.close(); assertEquals(writtenLength, intsFromList.getSerializedSize()); // read from ByteBuffer and check values VSizeIndexedInts intsFromByteBuffer = VSizeIndexedInts .readFromByteBuffer(ByteBuffer.wrap(IOUtils.toByteArray(ioPeon.makeInputStream("output")))); assertEquals(vals.length, intsFromByteBuffer.size()); for (int i = 0; i < vals.length; ++i) { assertEquals(vals[i], intsFromByteBuffer.get(i)); } }
From source file:gridool.communication.transport.tcp.GridNioClient.java
private static ByteBuffer toBuffer(final GridCommunicationMessage msg) { final byte[] b = GridUtils.toBytes(msg); final ByteBuffer buf = ByteBuffer.wrap(b); return buf;/*from www . j av a 2s. c o m*/ }
From source file:de.cosmocode.palava.store.CacheServiceStore.java
@Override public ByteBuffer view(String identifier) throws IOException { Preconditions.checkNotNull(identifier, "Identifier"); LOG.trace("Reading data from {}", identifier); final byte[] data = cache.read(identifier); Preconditions.checkState(data != null, "Unknown identifier %s", identifier); return ByteBuffer.wrap(data); }
From source file:com.caricah.iotracah.server.httpserver.transform.HttpIOTTransformerImpl.java
@Override public IOTMessage toIOTMessage(FullHttpMessage serverMessage) { if (serverMessage instanceof FullHttpRequest) { FullHttpRequest request = (FullHttpRequest) serverMessage; final String content = request.content().toString(CharsetUtil.UTF_8); final JSONObject json = new JSONObject(content); log.debug(" toIOTMessage : received content {} ", content); final String path = request.uri().toUpperCase(); switch (path) { case "/CONNECT": boolean isAnnonymousConnect = (!json.has("username") && !json.has("password")); int keepAliveTime = json.has("keepAliveTime") ? json.getInt("keepAliveTime") : 0; return ConnectMessage.from(false, 1, false, "MQTT", 4, false, isAnnonymousConnect, json.getString("clientId"), json.has("username") ? json.getString("username") : "", json.has("password") ? json.getString("password") : "", keepAliveTime, ""); case "/PUBLISH": ByteBuffer byteBuffer = ByteBuffer.wrap(json.getString("payload").getBytes()); PublishMessage publishMessage = PublishMessage.from(json.getInt("messageId"), json.has("dup") && json.getBoolean("dup"), 1, json.has("retain") && json.getBoolean("retain"), json.getString("topic"), byteBuffer, true); publishMessage.setSessionId(json.getString("sessionId")); publishMessage.setAuthKey(json.getString("authKey")); return publishMessage; case "/SUBSCRIBE": SubscribeMessage subscribeMessage = SubscribeMessage.from(1, false, 1, false); JSONArray jsonTopicQosList = json.getJSONArray("topicQosList"); for (int i = 0; i < jsonTopicQosList.length(); i++) { JSONObject topicQos = jsonTopicQosList.getJSONObject(i); String topic = topicQos.getString("topic"); int qos = topicQos.getInt("qos"); Map.Entry<String, Integer> entry = new AbstractMap.SimpleEntry<>(topic, qos); subscribeMessage.getTopicFilterList().add(entry); }/* w w w . j ava2s .com*/ subscribeMessage.setReceptionUrl(json.getString("recipientUrl")); subscribeMessage.setSessionId(json.getString("sessionId")); subscribeMessage.setAuthKey(json.getString("authKey")); return subscribeMessage; case "/UNSUBSCRIBE": List<String> topicList = new ArrayList<>(); JSONArray jsonTopicList = json.getJSONArray("topicList"); for (int i = 0; i < jsonTopicList.length(); i++) { String topic = jsonTopicList.getString(i); topicList.add(topic); } UnSubscribeMessage unSubscribeMessage = UnSubscribeMessage.from(1, false, 1, false, topicList); unSubscribeMessage.setSessionId(json.getString("sessionId")); unSubscribeMessage.setAuthKey(json.getString("authKey")); case "/DISCONNECT": DisconnectMessage disconMessage = DisconnectMessage.from(false); disconMessage.setSessionId(json.getString("sessionId")); disconMessage.setAuthKey(json.getString("authKey")); return disconMessage; default: return null; } } return null; }
From source file:com.cloudera.flume.handlers.avro.AvroEventAdaptor.java
public static AvroFlumeEvent convert(Event e) { AvroFlumeEvent tempAvroEvt = new AvroFlumeEvent(); tempAvroEvt.timestamp = e.getTimestamp(); tempAvroEvt.priority = convert(e.getPriority()); ByteBuffer bbuf = ByteBuffer.wrap(e.getBody()); tempAvroEvt.body = bbuf;//w w w. j a v a 2s .com tempAvroEvt.nanos = e.getNanos(); tempAvroEvt.host = e.getHost(); tempAvroEvt.fields = new HashMap<CharSequence, ByteBuffer>(); for (String s : e.getAttrs().keySet()) { // wrap a ByteBuffer around e.getAttrs().get(s) // also note that e.getAttrs().get(s) is immutable ByteBuffer temp = ByteBuffer.wrap(e.getAttrs().get(s)); tempAvroEvt.fields.put(s, temp); } return tempAvroEvt; }
From source file:de.cosmocode.palava.store.MemoryStore.java
@Override public ByteBuffer view(String identifier) throws IOException { Preconditions.checkNotNull(identifier, "Identifier"); LOG.trace("Reading data from {}", identifier); final byte[] data = map.get(identifier); Preconditions.checkState(data != null, "Unknown identifier %s", identifier); return ByteBuffer.wrap(data); }