List of usage examples for java.nio ByteBuffer get
public abstract byte get(int index);
From source file:com.offbynull.portmapper.natpmp.NatPmpReceiver.java
/** * Start listening for NAT-PMP events. This method blocks until {@link #stop() } is called. * @param listener listener to notify of events * @throws IOException if socket error occurs * @throws NullPointerException if any argument is {@code null} *//*from w ww .j a v a 2 s . c o m*/ public void start(NatPmpEventListener listener) throws IOException { Validate.notNull(listener); MulticastSocket socket = null; try { final InetAddress group = InetAddress.getByName("224.0.0.1"); // NOPMD final int port = 5350; final InetSocketAddress groupAddress = new InetSocketAddress(group, port); socket = new MulticastSocket(port); if (!currentSocket.compareAndSet(null, socket)) { IOUtils.closeQuietly(socket); return; } socket.setReuseAddress(true); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); Enumeration<InetAddress> addrs = networkInterface.getInetAddresses(); while (addrs.hasMoreElements()) { // make sure atleast 1 ipv4 addr bound to interface InetAddress addr = addrs.nextElement(); try { if (addr instanceof Inet4Address) { socket.joinGroup(groupAddress, networkInterface); } } catch (IOException ioe) { // NOPMD // occurs with certain interfaces // do nothing } } } ByteBuffer buffer = ByteBuffer.allocate(12); DatagramPacket data = new DatagramPacket(buffer.array(), buffer.capacity()); while (true) { buffer.clear(); socket.receive(data); buffer.position(data.getLength()); buffer.flip(); if (!data.getAddress().equals(gatewayAddress)) { // data isn't from our gateway, ignore continue; } if (buffer.remaining() != 12) { // data isn't the expected size, ignore continue; } int version = buffer.get(0); if (version != 0) { // data doesn't have the correct version, ignore continue; } int opcode = buffer.get(1) & 0xFF; if (opcode != 128) { // data doesn't have the correct op, ignore continue; } int resultCode = buffer.getShort(2) & 0xFFFF; switch (resultCode) { case 0: break; default: continue; // data doesn't have a successful result, ignore } listener.publicAddressUpdated(new ExternalAddressNatPmpResponse(buffer)); } } catch (IOException ioe) { if (currentSocket.get() == null) { return; // ioexception caused by interruption/stop, so just return without propogating error up } throw ioe; } finally { IOUtils.closeQuietly(socket); currentSocket.set(null); } }
From source file:dap4.dap4.Dap4Print.java
protected String valueString(Object value, DapType basetype) throws DataException { if (value == null) return "null"; AtomicType atype = basetype.getAtomicType(); boolean unsigned = atype.isUnsigned(); switch (atype) { case Int8:// w ww.j a v a2 s . c o m case UInt8: long lvalue = ((Byte) value).longValue(); if (unsigned) lvalue &= 0xFFL; return String.format("%d", lvalue); case Int16: case UInt16: lvalue = ((Short) value).longValue(); if (unsigned) lvalue &= 0xFFFFL; return String.format("%d", lvalue); case Int32: case UInt32: lvalue = ((Integer) value).longValue(); if (unsigned) lvalue &= 0xFFFFFFFFL; return String.format("%d", lvalue); case Int64: case UInt64: lvalue = ((Long) value).longValue(); if (unsigned) { BigInteger b = BigInteger.valueOf(lvalue); b = b.and(DapUtil.BIG_UMASK64); return b.toString(); } else return String.format("%d", lvalue); case Float32: return String.format("%f", ((Float) value).floatValue()); case Float64: return String.format("%f", ((Double) value).doubleValue()); case Char: return "'" + ((Character) value).toString() + "'"; case String: case URL: return "\"" + ((String) value) + "\""; case Opaque: ByteBuffer opaque = (ByteBuffer) value; String s = "0x"; for (int i = 0; i < opaque.limit(); i++) { byte b = opaque.get(i); char c = hexchar((b >> 4) & 0xF); s += c; c = hexchar((b) & 0xF); s += c; } return s; case Enum: return valueString(value, ((DapEnum) basetype).getBaseType()); default: break; } throw new DataException("Unknown type: " + basetype); }
From source file:net.jradius.freeradius.FreeRadiusListener.java
public JRadiusEvent parseRequest(ListenerRequest listenerRequest, ByteBuffer notUsed, InputStream in) throws Exception { FreeRadiusRequest request = (FreeRadiusRequest) requestObjectPool.borrowObject(); request.setBorrowedFromPool(requestObjectPool); int totalLength = (int) (RadiusFormat.readUnsignedInt(in) - 4); int readOffset = 0; ByteBuffer buffer = request.buffer_in; if (totalLength < 0 || totalLength > buffer.capacity()) { return null; }/*from w w w .j av a 2 s. c o m*/ buffer.clear(); byte[] payload = buffer.array(); while (readOffset < totalLength) { int result = in.read(payload, readOffset, totalLength - readOffset); if (result < 0) return null; readOffset += result; } buffer.limit(totalLength); long nameLength = RadiusFormat.getUnsignedInt(buffer); if (nameLength < 0 || nameLength > 1024) { throw new RadiusException("KeepAlive rlm_jradius connection has been closed"); } byte[] nameBytes = new byte[(int) nameLength]; buffer.get(nameBytes); int messageType = RadiusFormat.getUnsignedByte(buffer); int packetCount = RadiusFormat.getUnsignedByte(buffer); RadiusPacket rp[] = PacketFactory.parse(buffer, packetCount); long length = RadiusFormat.getUnsignedInt(buffer); if (length > buffer.remaining()) { throw new RadiusException("bad length"); } AttributeList configItems = new AttributeList(); format.unpackAttributes(configItems, buffer, (int) length, true); request.setConfigItems(configItems); request.setSender(new String(nameBytes)); request.setType(messageType); request.setPackets(rp); return request; }
From source file:edu.umass.cs.nio.MessageExtractor.java
private void demultiplexMessage(NIOHeader header, ByteBuffer incoming) throws IOException { boolean extracted = false; byte[] msg = null; // synchronized (this.packetDemuxes) {//from w ww . j a va 2 s . c o m for (final AbstractPacketDemultiplexer<?> pd : this.packetDemuxes) { if (pd instanceof PacketDemultiplexerDefault // if congested, don't process || pd.isCongested(header)) continue; if (!extracted) { // extract at most once msg = new byte[incoming.remaining()]; incoming.get(msg); extracted = true; NIOInstrumenter.incrBytesRcvd(msg.length + 8); } // String message = (new String(msg, // MessageNIOTransport.NIO_CHARSET_ENCODING)); if (this.callDemultiplexerHandler(header, msg, pd)) return; } } }
From source file:com.linkedin.databus.core.DbusEventV2.java
@Override public DbusEventInternalReadable reset(ByteBuffer buf, int position) { if (buf.get(position) != DbusEventFactory.DBUS_EVENT_V2) { verifyByteOrderConsistency(buf, "DbusEventV2.reset()"); return DbusEventV1Factory.createReadOnlyDbusEventFromBufferUnchecked(buf, position); }// w w w. j av a 2 s .c om resetInternal(buf, position); return this; }
From source file:dk.statsbiblioteket.util.LineReaderTest.java
private void checkContent(String message, byte[] expected, ByteBuffer buffer) throws IOException { byte[] actual = new byte[expected.length]; buffer.get(actual); for (int i = 0; i < expected.length; i++) { assertEquals(message + ": The byte at position " + i + " should be as expected", expected[i], actual[i]);//w w w . j ava2s .c o m } }
From source file:com.github.ambry.utils.UtilsTest.java
@Test public void testSerializeNullableString() { String randomString = getRandomString(10); ByteBuffer outputBuffer = ByteBuffer.allocate(4 + randomString.getBytes().length); Utils.serializeNullableString(outputBuffer, randomString); outputBuffer.flip();//from w w w. ja va2 s. c o m int length = outputBuffer.getInt(); assertEquals("Input and output string lengths don't match ", randomString.getBytes().length, length); byte[] output = new byte[length]; outputBuffer.get(output); assertFalse("Output buffer shouldn't have any remaining, but has " + outputBuffer.remaining() + " bytes", outputBuffer.hasRemaining()); String outputString = new String(output); assertEquals("Input and output strings don't match", randomString, outputString); randomString = null; outputBuffer = ByteBuffer.allocate(4); Utils.serializeNullableString(outputBuffer, randomString); outputBuffer.flip(); length = outputBuffer.getInt(); assertEquals("Input and output string lengths don't match", 0, length); output = new byte[length]; outputBuffer.get(output); assertFalse("Output buffer shouldn't have any remaining, but has " + outputBuffer.remaining() + " bytes", outputBuffer.hasRemaining()); outputString = new String(output); assertEquals("Output string \"" + outputString + "\" expected to be empty", outputString, ""); }
From source file:com.flyingcrop.ScreenCaptureFragment.java
void savePlanes() { Image.Plane[] planes = image.getPlanes(); Buffer imageBuffer = planes[0].getBuffer().rewind(); //Log.i(TAG, "Time 2 " + (System.currentTimeMillis() - time_now)); // create bitmap bitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888); bitmap.copyPixelsFromBuffer(imageBuffer); int offset = 0; int pixelStride = planes[0].getPixelStride(); int rowStride = planes[0].getRowStride(); int rowPadding = rowStride - pixelStride * mWidth; ByteBuffer buffer = planes[0].getBuffer(); //Log.e(TAG, "Time 3 " + (System.currentTimeMillis() - time_now)); for (int i = 0; i < mHeight; ++i) { for (int j = 0; j < mWidth; ++j) { int pixel = 0; pixel |= (buffer.get(offset) & 0xff) << 16; // R pixel |= (buffer.get(offset + 1) & 0xff) << 8; // G pixel |= (buffer.get(offset + 2) & 0xff); // B pixel |= (buffer.get(offset + 3) & 0xff) << 24; // A bitmap.setPixel(j, i, pixel); offset += pixelStride;// w w w .jav a2 s. com } offset += rowPadding; } //Log.i(TAG, "Time 4 " + (System.currentTimeMillis() - time_now)); Log.i(TAG, "x_inicial " + x_inicial); Log.i(TAG, "x_final " + x_final); Log.i(TAG, "y_inicial " + y_inicial); Log.i(TAG, "y_final " + y_final); bitmap = Bitmap.createBitmap(bitmap, (int) x_inicial, (int) status_bar_height + (int) y_inicial, Math.abs((int) x_final - (int) x_inicial), Math.abs((int) y_final - (int) y_inicial)); //bitmap = Bitmap.createBitmap(bitmap, 0 ,0,mWidth, mHeight); // write bitmap to a file SharedPreferences settings = getActivity().getSharedPreferences("data", 0); if (!settings.getBoolean("watermark", false)) { Canvas mCanvas = new Canvas(bitmap); Bitmap watermark = resize( BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.watermark)); mCanvas.drawBitmap(watermark, 0, 0, null); } String date = getDate(); String dir = STORE_DIRECTORY + "/FlyingCrop/" + date + ".png"; try { fos = new FileOutputStream(dir); } catch (Exception e) { } bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); //Log.e(TAG, "Time 5 " + (System.currentTimeMillis() - time_now)); File file = new File(dir); // MediaStore.Images.Media.insertImage(getActivity().getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName()); if (settings.getBoolean("toast", true)) { Toast.makeText(getActivity(), getResources().getString(R.string.fragment_img_saved) + " " + dir, Toast.LENGTH_SHORT).show(); } Intent mIntent = new Intent(getActivity(), Brush.class); getActivity().stopService(mIntent); notifySS(bitmap, date, dir); MediaScannerConnection.scanFile(getActivity(), new String[] { dir }, null, null); mImageReader = null; getActivity().finish(); }
From source file:de.rwhq.btree.LeafNode.java
@Override public List<V> get(final K key) { final List<V> result = new ArrayList<V>(); final byte[] keyBuf = keySerializer.serialize(key); final byte[] tmpKeyBuf = new byte[keySerializer.getSerializedLength()]; final byte[] tmpValBuf = new byte[valueSerializer.getSerializedLength()]; final int pos = offsetOfKey(key); if (pos == NOT_FOUND) return result; final ByteBuffer buffer = rawPage().bufferForReading(pos); while (buffer.position() < offsetBehindLastEntry()) { buffer.get(tmpKeyBuf); if (Arrays.equals(tmpKeyBuf, keyBuf)) { buffer.get(tmpValBuf);/* w w w . j av a2 s .co m*/ result.add(valueSerializer.deserialize(tmpValBuf)); } } return result; }
From source file:de.rwhq.btree.LeafNode.java
/** * @param key//from ww w . j a v a2 s . c o m * @param takeNext * boolean, whether if the key was not found the next higher key should be taken * @return position to set the buffer to, where the key starts, -1 if key not found */ private int offsetOfKey(final K key, final boolean takeNext) { final byte[] pointerBuf = new byte[valueSerializer.getSerializedLength()]; final byte[] keyBuf = new byte[keySerializer.getSerializedLength()]; final ByteBuffer buffer = rawPage().bufferForReading(Header.size()); for (int i = 0; i < getNumberOfEntries(); i++) { buffer.get(keyBuf); final int compResult = comparator.compare(keySerializer.deserialize(keyBuf), key); if (compResult == 0) { return buffer.position() - keySerializer.getSerializedLength(); } else if (compResult > 0) { if (takeNext) return buffer.position() - keySerializer.getSerializedLength(); else return NOT_FOUND; } // if compresult < 0: // get the data pointer but do nothing with it buffer.get(pointerBuf); } return NOT_FOUND; }