Example usage for java.nio ByteBuffer position

List of usage examples for java.nio ByteBuffer position

Introduction

In this page you can find the example usage for java.nio ByteBuffer position.

Prototype

public final int position() 

Source Link

Document

Returns the position of this buffer.

Usage

From source file:com.bennavetta.appsite.file.ResourceService.java

public Resource create(String path, MediaType mime, ReadableByteChannel src) throws IOException {
    String normalized = PathUtils.normalize(path);
    log.debug("Creating resource {}", normalized);

    AppEngineFile file = fs.createNewBlobFile(mime.toString(), normalized);
    FileWriteChannel channel = fs.openWriteChannel(file, true);

    MessageDigest digest = null;/*from  w  w w  .jav  a2 s.  com*/
    try {
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("MD5 not available", e);
    }
    ByteBuffer buf = ByteBuffer.allocateDirect(bufferSize.get());
    while (src.read(buf) != -1 || buf.position() != 0) {
        buf.flip();
        int read = channel.write(buf);
        if (read != 0) {
            int origPos = buf.position();
            int origLimit = buf.limit();
            buf.position(origPos - read);
            buf.limit(origPos);
            digest.update(buf);
            buf.limit(origLimit);
            buf.position(origPos);
        }

        buf.compact();
    }

    channel.closeFinally();
    Resource resource = new Resource(normalized, fs.getBlobKey(file).getKeyString(), digest.digest(), mime);
    resource.save();
    return resource;
}

From source file:jnative.io.AIO.java

public void submit() {
    NativeObject eventArray = new NativeObject(pendingOps.size() * SIZE_IOCB, true);
    long eventArrayAddress = eventArray.address();
    // TODO: more efficient way, pass the command list to native code through only one jni call
    for (int i = 0; i < pendingOps.size(); i++) {
        IOCommand command = pendingOps.get(i);

        final ByteBuffer bb = command.data;
        int pos = bb.position();
        int lim = bb.limit();
        assert (pos <= lim);
        int rem = (pos <= lim ? lim - pos : 0);

        prepare(eventArrayAddress + i * SIZE_IOCB, command.type, command.fd, command.offset,
                ((DirectBuffer) bb).address() + pos, rem, eventFd);
    }//from w w  w.  ja  v a2  s  .  c  o m
    submit0(context, pendingOps.size(), eventArrayAddress);
    eventArray.free();
    pendingOps.clear();
}

From source file:org.redisson.codec.JsonJacksonCodec.java

private Object decode(ByteBuffer bytes) {
    try {//from w  ww .ja v a2  s . c om
        return objectMapper.readValue(bytes.array(), bytes.arrayOffset() + bytes.position(), bytes.limit(),
                Object.class);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.redisson.codec.JsonJacksonCodec.java

@Override
public Object decodeMapValue(ByteBuffer bytes) {
    try {//w  w w. j  ava  2 s. co m
        return mapObjectMapper.readValue(bytes.array(), bytes.arrayOffset() + bytes.position(), bytes.limit(),
                Object.class);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:net.phoenix.thrift.hello.ThreadPoolTest.java

@Test
public void testBinary() throws Exception {
    LOG.info("Client starting....");
    String name = "Hello ";
    // TTransport transport = new TNonblockingSocket("localhost", 9804);
    TTransport transport = new TSocket("localhost", 9804);
    transport.open();//from  ww  w .  j a  v a 2s . c om
    // TTransport transport = new TTransport(socket);
    TProtocol protocol = new TBinaryProtocol(transport);
    HelloService.Client client = new HelloService.Client(protocol);
    try {

        ByteBuffer buffer = client.testBinary(ByteBuffer.wrap(name.getBytes("UTF-8")));

        assertEquals(new String(buffer.array(), buffer.position(), buffer.limit() - buffer.position(), "UTF-8"),
                "Hello " + name);
        // System.out.println(message);
    } finally {
        transport.close();
    }
}

From source file:com.reactive.hzdfs.utils.Digestor.java

private void updateBytes(ByteBuffer buff) {
    int i = buff.position();
    buff.flip();/*from  w w  w  .ja  v a 2s.  c  o m*/
    byte[] b = new byte[i];
    buff.get(b);
    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  .ja  va  2  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:net.phoenix.thrift.hello.ThreadedSelectorTest.java

@Test
public void testBinary() throws Exception {
    LOG.info("Client starting....");
    String name = "Hello";
    // TTransport transport = new TNonblockingSocket("localhost", 9804);
    TTransport transport = new TFramedTransport(new TSocket("localhost", 9804));
    transport.open();//from w w  w. ja  v a  2  s. c om
    // TTransport transport = new TTransport(socket);
    TProtocol protocol = new TBinaryProtocol(transport);
    HelloService.Client client = new HelloService.Client(protocol);
    try {

        ByteBuffer buffer = client.testBinary(ByteBuffer.wrap(name.getBytes("UTF-8")));
        assertEquals(new String(buffer.array(), buffer.position(), buffer.limit() - buffer.position(), "UTF-8"),
                "Hello " + name);
        // System.out.println(message);
    } finally {
        transport.close();
    }
}

From source file:de.csdev.ebus.command.EBusCommandUtils.java

/**
 * @param commandMethod/*from   ww w .j a va 2  s .co  m*/
 * @param values
 * @return
 * @throws EBusTypeException
 */
public static ByteBuffer composeMasterData(IEBusCommandMethod commandMethod, Map<String, Object> values)
        throws EBusTypeException {

    ByteBuffer buf = ByteBuffer.allocate(50);

    Map<Integer, IEBusComplexType<?>> complexTypes = new HashMap<Integer, IEBusComplexType<?>>();

    if (commandMethod.getMasterTypes() != null) {
        for (IEBusValue entry : commandMethod.getMasterTypes()) {

            IEBusType<?> type = entry.getType();
            byte[] b = null;

            // use the value from the values map if set
            if (values != null && values.containsKey(entry.getName())) {
                b = type.encode(values.get(entry.getName()));

            } else {
                if (type instanceof IEBusComplexType) {

                    // add the complex to the list for post processing
                    complexTypes.put(buf.position(), (IEBusComplexType<?>) type);

                    // add placeholder
                    b = new byte[entry.getType().getTypeLength()];

                } else {
                    b = type.encode(entry.getDefaultValue());

                }

            }

            if (b == null) {
                throw new RuntimeException("Encoded value is null! " + type.toString());
            }
            // buf.p
            buf.put(b);
            // len += type.getTypeLength();
        }
    }

    // replace the placeholders with the complex values
    if (!complexTypes.isEmpty()) {
        int orgPos = buf.position();
        for (Entry<Integer, IEBusComplexType<?>> entry : complexTypes.entrySet()) {
            // jump to position
            buf.position(entry.getKey());
            // put new value
            buf.put(entry.getValue().encodeComplex(buf));

        }
        buf.position(orgPos);

    }

    // reset pos to zero and set the new limit
    buf.limit(buf.position());
    buf.position(0);

    return buf;
}

From source file:rx.apache.http.consumers.ResponseConsumerEventStream.java

@Override
protected void onByteReceived(ByteBuffer buf, IOControl ioctrl) throws IOException {
    if (parentSubscription.isUnsubscribed()) {
        ioctrl.shutdown();/*from   ww w  .  ja  va2  s . c o  m*/
    }
    while (buf.position() < buf.limit()) {
        byte b = buf.get();
        if (b == 10 || b == 13) {
            if (dataBuffer.hasContent()) {
                contentSubject.onNext(dataBuffer.getBytes());
            }
            dataBuffer.reset();
        } else {
            dataBuffer.addByte(b);
        }
    }
}