List of usage examples for java.nio ByteBuffer flip
public final Buffer flip()
From source file:org.apache.hama.monitor.fd.UDPSensor.java
/** * The heartbeat function, signifying its existence. *//* w ww .ja v a 2 s .c o m*/ @Override public void heartbeat() throws IOException { ByteBuffer heartbeat = ByteBuffer.allocate(8); heartbeat.clear(); heartbeat.putLong(sequence.incrementAndGet()); heartbeat.flip(); channel.send(heartbeat, new InetSocketAddress(this.host, this.port)); if (LOG.isDebugEnabled()) { LOG.debug("Heartbeat sequence " + sequence.get() + " is sent to " + this.host + ":" + this.port); } }
From source file:com.unister.semweb.drums.api.SearchForTest.java
/** * Converts the given <code>value</code> into an byte array. The final byte array will have * <code>overallBytes</code>. */// ww w .j a v a 2 s. c o m private byte[] convert(int value, int overallBytes) { ByteBuffer buffer = ByteBuffer.allocate(overallBytes); buffer.putInt(overallBytes - 4, value); buffer.flip(); return buffer.array(); }
From source file:SelfClassLoader.java
private byte[] loadClassBytes(String className) throws ClassNotFoundException { try {// w w w. jav a 2 s . c om String classFile = getClassFile(className); FileInputStream fis = new FileInputStream(classFile); FileChannel fileC = fis.getChannel(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel outC = Channels.newChannel(baos); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int i = fileC.read(buffer); if (i == 0 || i == -1) { break; } buffer.flip(); outC.write(buffer); buffer.clear(); } fis.close(); return baos.toByteArray(); } catch (IOException fnfe) { throw new ClassNotFoundException(className); } }
From source file:com.facebook.infrastructure.net.UdpConnection.java
public boolean write(Message message, EndPoint to) throws IOException { boolean bVal = true; ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); Message.serializer().serialize(message, dos); byte[] data = bos.toByteArray(); if (data.length > 0) { logger_.trace("Size of Gossip packet " + data.length); byte[] protocol = BasicUtilities.intToByteArray(protocol_); ByteBuffer buffer = ByteBuffer.allocate(data.length + protocol.length); buffer.put(protocol);// w w w.j a v a 2 s .c o m buffer.put(data); buffer.flip(); int n = socketChannel_.send(buffer, to.getInetAddress()); if (n == 0) { bVal = false; } } return bVal; }
From source file:com.reactive.hzdfs.utils.Digestor.java
private void updateBytes(ByteBuffer buff) { int i = buff.position(); buff.flip(); byte[] b = new byte[i]; buff.get(b);/*from w w w.j av a 2s .co m*/ if (byteArray == null) byteArray = b; else { i = byteArray.length; byteArray = Arrays.copyOf(byteArray, i + b.length); System.arraycopy(b, 0, byteArray, i, b.length); } }
From source file:com.esri.ges.solutions.adapter.geomessage.DefenseOutboundAdapter.java
@SuppressWarnings("incomplete-switch") @Override//from ww w. j a va2 s .c o m public void receive(GeoEvent geoEvent) { String wkid = null; stringBuffer.setLength(0); stringBuffer.append("<geomessages>"); stringBuffer.append("<geomessage>"); GeoEventDefinition definition = geoEvent.getGeoEventDefinition(); for (FieldDefinition fieldDefinition : definition.getFieldDefinitions()) { String attributeName = fieldDefinition.getName(); Object value = geoEvent.getField(attributeName); stringBuffer.append("<" + attributeName + ">"); FieldType t = fieldDefinition.getType(); switch (t) { case String: stringBuffer.append((String) value); break; case Date: Date date = (Date) value; stringBuffer.append(formatter.format(date)); break; case Double: Double doubleValue = (Double) value; stringBuffer.append(doubleValue); break; case Float: Float floatValue = (Float) value; stringBuffer.append(floatValue); break; case Geometry: if (definition.getIndexOf(attributeName) == definition.getGeometryId()) { Geometry geom = geoEvent.getGeometry(); if (geom.getType() == GeometryType.Point) { Point p = (Point) geom; stringBuffer.append(p.getX()); stringBuffer.append(","); stringBuffer.append(p.getY()); wkid = String.valueOf(p.getSpatialReference().getWkid()); } } else { LOG.error( "unable to parse the value for the secondary geometry field \"" + attributeName + "\""); } break; case Integer: Integer intValue = (Integer) value; stringBuffer.append(intValue); break; case Long: Long longValue = (Long) value; stringBuffer.append(longValue); break; case Short: Short shortValue = (Short) value; stringBuffer.append(shortValue); break; case Boolean: Boolean booleanValue = (Boolean) value; stringBuffer.append(booleanValue); break; } stringBuffer.append("</" + attributeName + ">"); if (wkid != null) { String wkidValue = wkid; wkid = null; stringBuffer.append("<_wkid>"); stringBuffer.append(wkidValue); stringBuffer.append("</_wkid>"); } } stringBuffer.append("</geomessage>"); stringBuffer.append("</geomessages>"); stringBuffer.append("\r\n"); ByteBuffer buf = charset.encode(stringBuffer.toString()); if (buf.position() > 0) buf.flip(); try { byteBuffer.put(buf); } catch (BufferOverflowException ex) { LOG.error( "Csv Outbound Adapter does not have enough room in the buffer to hold the outgoing data. Either the receiving transport object is too slow to process the data, or the data message is too big."); } byteBuffer.flip(); byteListener.receive(byteBuffer, geoEvent.getTrackId()); byteBuffer.clear(); }
From source file:com.gistlabs.mechanize.util.apache.URLEncodedUtils.java
/** * Decode/unescape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true. * /* w ww . jav a 2 s .c o m*/ * @param content the portion to decode * @param charset the charset to use * @param plusAsBlank if {@code true}, then convert '+' to space (e.g. for www-url-form-encoded content), otherwise leave as is. * @return */ private static String urldecode(final String content, final Charset charset, final boolean plusAsBlank) { if (content == null) return null; ByteBuffer bb = ByteBuffer.allocate(content.length()); CharBuffer cb = CharBuffer.wrap(content); while (cb.hasRemaining()) { char c = cb.get(); if (c == '%' && cb.remaining() >= 2) { char uc = cb.get(); char lc = cb.get(); int u = Character.digit(uc, 16); int l = Character.digit(lc, 16); if (u != -1 && l != -1) bb.put((byte) ((u << 4) + l)); else { bb.put((byte) '%'); bb.put((byte) uc); bb.put((byte) lc); } } else if (plusAsBlank && c == '+') bb.put((byte) ' '); else bb.put((byte) c); } bb.flip(); return charset.decode(bb).toString(); }
From source file:com.taobao.common.tfs.comm.TfsClient.java
public void invokeAsync(final BasePacket packet, final long timeout, ResponseListener listener) { if (isDebugEnabled) { log.debug("send request [" + packet.getChid() + "] async,time is:" + System.currentTimeMillis()); }/*from w ww.j a va 2 s.c o m*/ if (minTimeout > timeout) { minTimeout = timeout; } final ResponseCallbackTask callbackTask = new ResponseCallbackTask(packet.getSeqId(), listener, timeout); callbackTasks.put(packet.getChid(), callbackTask); ByteBuffer bb = packet.getByteBuffer(); bb.flip(); byte[] data = new byte[bb.remaining()]; bb.get(data); WriteFuture writeFuture = session.write(data); writeFuture.addListener(new IoFutureListener() { public void operationComplete(IoFuture future) { WriteFuture wfuture = (WriteFuture) future; if (wfuture.isWritten()) { return; } String error = "send message to tfs server error [" + packet.getChid() + "], tfs server: " + session.getRemoteAddress() + ", maybe because this connection closed: " + !session.isConnected(); callbackTask.setResponse(new TfsException(error)); // close this session if (session.isConnected()) { session.close(); } else { TfsClientFactory.getInstance().removeClient(key); } } }); }
From source file:tachyon.master.RawTables.java
/** * Get the metadata of the specified raw table. It will return a duplication. * * @param tableId The id of the raw table * @return null if it has no metadata, or a duplication of the metadata *///from w w w . j a va 2 s . c o m public synchronized ByteBuffer getMetadata(int tableId) { Pair<Integer, ByteBuffer> data = mData.get(tableId); if (null == data) { return null; } ByteBuffer ret = ByteBuffer.allocate(data.getSecond().capacity()); ret.put(data.getSecond().array()); ret.flip(); return ret; }
From source file:com.alibaba.zonda.logger.server.writer.OutputStreamManager.java
public void writeWithLength(byte[] data, String tag) throws IOException { lock.readLock().lock();/*w w w.j ava2 s. com*/ try { LogOutputStream os = getOutputStream(tag); ByteBuffer bf = ByteBuffer.allocate(4 + data.length); bf.put(BytesUtil.intToBytes(data.length)); bf.put(data); bf.flip(); IOUtils.write(bf.array(), os.getStream()); os.addBytesWritten(4 + data.length); os.getStream().flush(); } finally { lock.readLock().unlock(); } }