Example usage for java.nio ByteBuffer flip

List of usage examples for java.nio ByteBuffer flip

Introduction

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

Prototype

public final Buffer flip() 

Source Link

Document

Flips this buffer.

Usage

From source file:com.meidusa.venus.benchmark.FileLineRandomData.java

private final String readLine(ByteBuffer buffer) {
    if (closed)//from w ww  .j a v  a 2  s  .co  m
        throw new IllegalStateException("file closed..");
    ByteBuffer tempbuffer = localTempBuffer.get();
    tempbuffer.position(0);
    tempbuffer.limit(tempbuffer.capacity());
    byte c = -1;
    boolean eol = false;
    while (!eol) {
        switch (c = buffer.get()) {
        case -1:
        case '\n':
            eol = true;
            break;
        case '\r':
            eol = true;
            int cur = buffer.position();
            if ((buffer.get()) != '\n') {
                buffer.position(cur);
            }
            break;
        default:
            tempbuffer.put(c);
            break;
        }
    }

    if ((c == -1) && (tempbuffer.position() == 0)) {
        return null;
    }
    tempbuffer.flip();

    try {
        return new String(tempbuffer.array(), encoding);
    } catch (UnsupportedEncodingException e) {
        return new String(tempbuffer.array());
    }

}

From source file:org.alfresco.provision.ActiveMQService.java

private DestinationStats getStats(String destinationType, String destinationName) throws IOException {
    StringBuilder sb = new StringBuilder("http://");
    sb.append(activeMQHost);/*ww w  .j av  a2  s  . com*/
    sb.append(":");
    sb.append(activeMQPort);
    sb.append("/api/jolokia");
    String url = sb.toString();

    CloseableHttpResponse httpResponse = null;

    HttpPost httpPost = new HttpPost(url);
    Request[] post = new Request[] {
            new Request("read",
                    "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType
                            + ",destinationName=" + destinationName,
                    "AverageEnqueueTime"),
            new Request("read",
                    "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType
                            + ",destinationName=" + destinationName,
                    "EnqueueCount"),
            new Request("read",
                    "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType
                            + ",destinationName=" + destinationName,
                    "DequeueCount"),
            new Request("read",
                    "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType
                            + ",destinationName=" + destinationName,
                    "DispatchCount"),
            new Request("read",
                    "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType
                            + ",destinationName=" + destinationName,
                    "MemoryPercentUsage"),
            new Request("read",
                    "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType
                            + ",destinationName=" + destinationName,
                    "AverageBlockedTime"),
            new Request("read",
                    "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType
                            + ",destinationName=" + destinationName,
                    "QueueSize"),
            new Request("read",
                    "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType
                            + ",destinationName=" + destinationName,
                    "BlockedSends"),
            new Request("read", "org.apache.activemq:type=Broker,brokerName=localhost,destinationType="
                    + destinationType + ",destinationName=" + destinationName, "MaxEnqueueTime") };
    String str = mapper.writeValueAsString(post);
    HttpEntity postEntity = new StringEntity(str);
    httpPost.setEntity(postEntity);
    httpResponse = client.execute(httpPost);

    DestinationStats stats = new DestinationStats(destinationType, destinationName);

    StatusLine status = httpResponse.getStatusLine();
    // Expecting "OK" status
    if (status.getStatusCode() == HttpStatus.SC_OK) {
        HttpEntity entity = httpResponse.getEntity();
        InputStream in = entity.getContent();
        try {
            ByteBuffer bb = ByteBuffer.allocate(1024 * 10);
            ReadableByteChannel inChannel = Channels.newChannel(in);
            int read = -1;
            do {
                read = inChannel.read(bb);
            } while (read != -1);
            bb.flip();
            Response[] response = mapper.readValue(bb.array(), Response[].class);
            for (Response r : response) {
                if (r.getRequest().getAttribute().equals("AverageEnqueueTime")) {
                    stats.setAverageEnqueueTime(r.getValue() != null ? r.getValue() : 0.0);
                } else if (r.getRequest().getAttribute().equals("EnqueueCount")) {
                    stats.setEnqueueCount(r.getValue() != null ? r.getValue() : 0.0);
                } else if (r.getRequest().getAttribute().equals("DequeueCount")) {
                    stats.setDequeueCount(r.getValue() != null ? r.getValue() : 0.0);
                } else if (r.getRequest().getAttribute().equals("DispatchCount")) {
                    stats.setDispatchCount(r.getValue() != null ? r.getValue() : 0.0);
                } else if (r.getRequest().getAttribute().equals("MemoryPercentUsage")) {
                    stats.setMemoryPercentUsage(r.getValue() != null ? r.getValue() : 0.0);
                } else if (r.getRequest().getAttribute().equals("AverageBlockedTime")) {
                    stats.setAverageBlockedTime(r.getValue() != null ? r.getValue() : 0.0);
                } else if (r.getRequest().getAttribute().equals("QueueSize")) {
                    stats.setQueueSize(r.getValue() != null ? r.getValue() : 0.0);
                } else if (r.getRequest().getAttribute().equals("MaxEnqueueTime")) {
                    stats.setMaxEnqueueTime(r.getValue() != null ? r.getValue() : 0.0);
                } else if (r.getRequest().getAttribute().equals("BlockedSends")) {
                    stats.setBlockedSends(r.getValue() != null ? r.getValue() : 0.0);
                } else if (r.getRequest().getAttribute().equals("DispatchCount")) {
                    stats.setDispatchCount(r.getValue() != null ? r.getValue() : 0.0);
                }
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
    } else {
        // TODO
    }

    return stats;
}

From source file:com.projecttango.examples.java.pointtopoint.PointToPointActivity.java

/**
 * Set up the callback listeners for the Tango Service and obtain other parameters required
 * after Tango connection.//from www.  java2 s. co m
 * Listen to updates from the RGB camera and point cloud.
 */
private void startupTango() {
    // No need to add any coordinate frame pairs since we are not
    // using pose data. So just initialize.
    ArrayList<TangoCoordinateFramePair> framePairs = new ArrayList<TangoCoordinateFramePair>();
    mTango.connectListener(framePairs, new OnTangoUpdateListener() {
        @Override
        public void onPoseAvailable(TangoPoseData pose) {
            // We are not using OnPoseAvailable for this app.
        }

        @Override
        public void onFrameAvailable(int cameraId) {
            // Check if the frame available is for the camera we want and update its frame
            // on the view.
            if (cameraId == TangoCameraIntrinsics.TANGO_CAMERA_COLOR) {
                // Mark a camera frame as available for rendering in the OpenGL thread.
                mIsFrameAvailableTangoThread.set(true);
                mSurfaceView.requestRender();
            }
        }

        @Override
        public void onXyzIjAvailable(TangoXyzIjData xyzIj) {
            // We are not using onXyzIjAvailable for this app.
        }

        @Override
        public void onPointCloudAvailable(TangoPointCloudData pointCloud) {
            // Save the cloud and point data for later use.
            mPointCloudManager.updatePointCloud(pointCloud);
        }

        @Override
        public void onTangoEvent(TangoEvent event) {
            // We are not using OnPoseAvailable for this app.
        }
    });
    mTango.experimentalConnectOnFrameListener(TangoCameraIntrinsics.TANGO_CAMERA_COLOR,
            new Tango.OnFrameAvailableListener() {
                @Override
                public void onFrameAvailable(TangoImageBuffer tangoImageBuffer, int i) {
                    mCurrentImageBuffer = copyImageBuffer(tangoImageBuffer);
                }

                TangoImageBuffer copyImageBuffer(TangoImageBuffer imageBuffer) {
                    ByteBuffer clone = ByteBuffer.allocateDirect(imageBuffer.data.capacity());
                    imageBuffer.data.rewind();
                    clone.put(imageBuffer.data);
                    imageBuffer.data.rewind();
                    clone.flip();
                    return new TangoImageBuffer(imageBuffer.width, imageBuffer.height, imageBuffer.stride,
                            imageBuffer.frameNumber, imageBuffer.timestamp, imageBuffer.format, clone);
                }
            });
}

From source file:org.bytesoft.bytetcc.work.CleanupWork.java

private int invokeCompress() throws RuntimeException {
    ByteBuffer current = ByteBuffer.allocate(CONSTANTS_RECORD_SIZE + 1);
    ByteBuffer previou = ByteBuffer.allocate(CONSTANTS_RECORD_SIZE + 1);
    int position = CONSTANTS_START_INDEX;
    for (int index = CONSTANTS_START_INDEX; index < this.endIndex; index += CONSTANTS_RECORD_SIZE + 1) {
        try {//from   w ww.  j av a  2  s  .  c om
            this.lock.lock();

            this.channel.position(index);
            this.channel.read(current);
            current.flip();
            boolean enabled = 0x1 == current.get();
            if (enabled) {
                if (index != position) {
                    if (previou.equals(current) == false) {
                        previou.put((byte) 0x1);
                        previou.put(current);

                        previou.flip();
                        current.flip();

                        this.channel.position(position);
                        this.channel.write(current);

                        previou.flip();
                        current.clear();
                    }

                    this.channel.position(index);
                    ByteBuffer buffer = ByteBuffer.allocate(1);
                    buffer.put((byte) 0x0);
                    this.channel.write(buffer);
                }
                position = index + CONSTANTS_RECORD_SIZE + 1;
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } finally {
            this.lock.unlock();

            previou.flip();
            current.clear();
        }
    }

    return position;
}

From source file:me.schiz.jmeter.ring.udp.sampler.UDPRingSampler.java

@Override
public SampleResult sample(Entry entry) {
    boolean idling = false;
    SampleResult newSampleResult = new SampleResult();
    newSampleResult.setSampleLabel(getName());

    ConcurrentLinkedQueue<SampleResult> queue = tlQueue.get();
    if (queue == null) {
        queue = new ConcurrentLinkedQueue<SampleResult>();
        tlQueue.set(queue);//from   w  ww .  j  a v a  2s  . co m
    }

    Ring ring = UDPRingSourceElement.get(getSource());
    Token t;
    int tid = -1;
    byte[] request_in_bytes = new byte[0];

    ByteBuffer request = tlRequest.get();
    if (request == null) {
        request = tlBuffer.get();
        if (request == null) {
            request = ByteBuffer.allocateDirect(8 * 1024 * 1024);
            tlBuffer.set(request);
        }
        request.clear();

        if (isHex()) {
            try {
                request_in_bytes = Hex.decodeHex(getRequest().toCharArray());
            } catch (DecoderException e) {
                log.error("can't decode request", e);
                idling = true;
            }
        } else {
            request_in_bytes = getRequest().getBytes();
        }
        request.put(request_in_bytes);
    }
    if (!idling) {
        try {
            request.flip();
            while (tid == -1) {
                tid = ring.acquire();
            }
            t = ring.get(tid);
            t.lock.lock();
            if (isHex())
                t.ishex = true;
            newSampleResult.sampleStart();
            try {
                //t.socketChannel.write(request);
                t.sampleResult = newSampleResult;
                t.queue = queue;
                ring.write(tid, request);
                request.clear();
                newSampleResult.setSuccessful(true);
            } catch (IOException e) {
                newSampleResult.setSuccessful(false);
                ring.reset(tid);
                log.warn("IOException", e);
            } finally {
                t.lock.unlock();
            }

        } catch (Exception e) {
            log.error("Exception", e);
            newSampleResult.setSuccessful(false);
            newSampleResult.setResponseCode(e.getClass().getName());
            while (!queue.offer(newSampleResult)) {
            }
            if (tid != -1)
                ring.reset(tid);
        } finally {
            newSampleResult.setRequestHeaders(getRequest());
        }
    }
    SampleResult sampleResult = queue.poll();
    return sampleResult;
}

From source file:org.apache.hc.client5.http.impl.auth.CredSspScheme.java

private String wrap(final ByteBuffer src) throws AuthenticationException {
    final SSLEngine sslEngine = getSSLEngine();
    final SSLSession sslSession = sslEngine.getSession();
    final ByteBuffer dst = ByteBuffer.allocate(sslSession.getPacketBufferSize());
    wrap(src, dst);/*w ww  .  j  ava 2  s .  c om*/
    dst.flip();
    return encodeBase64(dst);
}

From source file:org.apache.hc.client5.http.impl.auth.CredSspScheme.java

private ByteBuffer unwrap(final String inputString) throws MalformedChallengeException {
    final SSLEngine sslEngine = getSSLEngine();
    final SSLSession sslSession = sslEngine.getSession();
    final ByteBuffer src = decodeBase64(inputString);
    final ByteBuffer dst = ByteBuffer.allocate(sslSession.getApplicationBufferSize());
    unwrap(src, dst);//  ww  w .  j a  va2 s  . c  o m
    dst.flip();
    return dst;
}

From source file:org.bytesoft.openjtcc.supports.logger.DbTransactionLoggerImpl.java

private byte[] streamToByteArray(InputStream input) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ReadableByteChannel in = null;
    WritableByteChannel out = null;
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    try {//w ww . ja  v  a  2  s.  c o m
        in = Channels.newChannel(input);
        out = Channels.newChannel(baos);
        while (in.read(buffer) != -1) {
            buffer.flip();
            out.write(buffer);
            buffer.clear();
        }
    } catch (IOException ex) {
        // ignore
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // ignore
            }
        }
        if (baos != null) {
            try {
                baos.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return baos.toByteArray();
}

From source file:edu.hawaii.soest.kilonalu.ctd.SBE37Source.java

/**
 * A method that queries the instrument to obtain its ID
 *///from w  w w  .j av a  2s . c om
public boolean queryInstrument(String command) {

    // the result of the query
    boolean result = false;

    // only send the command if the socket is connected
    if (this.socketChannel.isConnected()) {
        ByteBuffer commandBuffer = ByteBuffer.allocate(command.length() * 10);
        commandBuffer.put(command.getBytes());
        commandBuffer.flip();

        try {
            this.socketChannel.write(commandBuffer);
            logger.debug("Wrote " + command + " to the socket channel.");
            result = true;

        } catch (IOException ioe) {
            ioe.printStackTrace();
            result = false;
        }
    }
    return result;
}

From source file:byps.BTransport.java

protected BProtocol negotiateProtocolServer(BTargetId targetId, ByteBuffer buf,
        BAsyncResult<ByteBuffer> asyncResult) {
    BProtocol ret = null;/*from w  w  w.  j a v  a  2s.c  o  m*/
    try {
        BNegotiate nego = new BNegotiate();
        nego.read(buf);

        synchronized (this) {
            this.protocol = ret = createNegotiatedProtocol(nego);
            setSessionId(targetId.toSessionId());
            setTargetId(targetId);
        }

        ByteBuffer bout = ByteBuffer.allocate(BNegotiate.NEGOTIATE_MAX_SIZE);
        try {
            nego.targetId = targetId;
            nego.sessionId = targetId.toSessionId();
            nego.write(bout);
            bout.flip();
            asyncResult.setAsyncResult(bout, null);
        } finally {
        }

    } catch (Throwable e) {
        asyncResult.setAsyncResult(null, e);
    }
    return ret;
}