Example usage for java.nio ByteBuffer limit

List of usage examples for java.nio ByteBuffer limit

Introduction

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

Prototype

public final int limit() 

Source Link

Document

Returns the limit of this buffer.

Usage

From source file:org.apache.hadoop.hbase.KeyValue.java

/**
 * @param bb//from  ww w.  j  a v  a2 s  .c om
 * @return A KeyValue made of a byte buffer that holds the key-only part.
 * Needed to convert hfile index members to KeyValues.
 */
public static KeyValue createKeyValueFromKey(final ByteBuffer bb) {
    return createKeyValueFromKey(bb.array(), bb.arrayOffset(), bb.limit());
}

From source file:com.netscape.cmsutil.crypto.CryptoUtil.java

public static byte[] charsToBytes(char[] chars) {
    if (chars == null)
        return null;

    Charset charset = Charset.forName("UTF-8");
    ByteBuffer byteBuffer = charset.encode(CharBuffer.wrap(chars));
    byte[] result = Arrays.copyOf(byteBuffer.array(), byteBuffer.limit());

    if (byteBuffer.hasArray()) {
        byte[] contentsToBeErased = byteBuffer.array();
        CryptoUtil.obscureBytes(contentsToBeErased, "random");
    }/*from  w ww.j a  v  a  2s.co m*/
    return result;
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void tesFormParamWithURLEncoded() throws IOException {
    HttpURLConnection connection = request("/test/v1/formParam", HttpMethod.POST);
    String rawData = "name=wso2&age=10";
    ByteBuffer encodedData = Charset.defaultCharset().encode(rawData);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
    try (OutputStream os = connection.getOutputStream()) {
        os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
    }/*www.  j av a2s .  co  m*/

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "wso2:10");
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testGetAllFormItemsWithURLEncoded() throws IOException, URISyntaxException {
    HttpURLConnection connection = request("/test/v1/getAllFormItemsURLEncoded", HttpMethod.POST);
    String rawData = "names=WSO2&names=IBM&age=10&type=Software";
    ByteBuffer encodedData = Charset.defaultCharset().encode(rawData);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
    try (OutputStream os = connection.getOutputStream()) {
        os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
    }/*from w w w. ja va  2 s  .  c  om*/

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals("No of Companies-2 type-Software", response);
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testFormDataParamWithSimpleRequest() throws IOException, URISyntaxException {
    // Send x-form-url-encoded request
    HttpURLConnection connection = request("/test/v1/formDataParam", HttpMethod.POST);
    String rawData = "name=wso2&age=10";
    ByteBuffer encodedData = Charset.defaultCharset().encode(rawData);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
    try (OutputStream os = connection.getOutputStream()) {
        os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
    }//from   www  .j  a  v a  2  s . co m

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "wso2:10");

    // Send multipart/form-data request
    connection = request("/test/v1/formDataParam", HttpMethod.POST);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart("name", new StringBody("wso2", ContentType.TEXT_PLAIN));
    builder.addPart("age", new StringBody("10", ContentType.TEXT_PLAIN));
    HttpEntity build = builder.build();
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    inputStream = connection.getInputStream();
    response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "wso2:10");
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void tesFormParamWithCollection() throws IOException {
    // Send x-form-url-encoded request
    HttpURLConnection connection = request("/test/v1/formParamWithList", HttpMethod.POST);
    String rawData = "names=WSO2&names=IBM";
    ByteBuffer encodedData = Charset.defaultCharset().encode(rawData);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
    try (OutputStream os = connection.getOutputStream()) {
        os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
    }/*from   w w  w  .  j a  v  a2  s.co m*/

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "2");

    // Send multipart/form-data request
    connection = request("/test/v1/formParamWithList", HttpMethod.POST);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart("names", new StringBody("WSO2", ContentType.TEXT_PLAIN));
    builder.addPart("names", new StringBody("IBM", ContentType.TEXT_PLAIN));
    builder.addPart("names", new StringBody("Oracle", ContentType.TEXT_PLAIN));
    HttpEntity build = builder.build();
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    inputStream = connection.getInputStream();
    response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "3");

    // Send x-form-url-encoded request
    connection = request("/test/v1/formParamWithSet", HttpMethod.POST);
    rawData = "names=WSO2&names=IBM&names=IBM";
    encodedData = Charset.defaultCharset().encode(rawData);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
    try (OutputStream os = connection.getOutputStream()) {
        os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
    }

    inputStream = connection.getInputStream();
    response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "2");

    // Send multipart/form-data request
    connection = request("/test/v1/formParamWithSet", HttpMethod.POST);
    builder = MultipartEntityBuilder.create();
    builder.addPart("names", new StringBody("WSO2", ContentType.TEXT_PLAIN));
    builder.addPart("names", new StringBody("IBM", ContentType.TEXT_PLAIN));
    builder.addPart("names", new StringBody("IBM", ContentType.TEXT_PLAIN));
    builder.addPart("names", new StringBody("Oracle", ContentType.TEXT_PLAIN));
    build = builder.build();
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    inputStream = connection.getInputStream();
    response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "3");
}

From source file:org.apache.qpid.server.store.derby.DerbyMessageStore.java

private void addContent(Connection conn, long messageId, ByteBuffer src) {
    if (_logger.isDebugEnabled()) {
        _logger.debug("Adding content for message " + messageId);
    }/*from   ww  w .  ja va2  s  . c o m*/
    PreparedStatement stmt = null;

    try {
        src = src.slice();

        byte[] chunkData = new byte[src.limit()];
        src.duplicate().get(chunkData);

        stmt = conn.prepareStatement(INSERT_INTO_MESSAGE_CONTENT);
        stmt.setLong(1, messageId);

        ByteArrayInputStream bis = new ByteArrayInputStream(chunkData);
        stmt.setBinaryStream(2, bis, chunkData.length);
        stmt.executeUpdate();
    } catch (SQLException e) {
        closeConnection(conn);
        throw new RuntimeException("Error adding content for message " + messageId + ": " + e.getMessage(), e);
    } finally {
        closePreparedStatement(stmt);
    }

}

From source file:byps.http.HWireClient.java

protected RequestToCancel createRequestForMessage(BMessage msg, BAsyncResult<BMessage> asyncResult,
        int timeoutSecondsRequest) {
    if (log.isDebugEnabled())
        log.debug("createRequestForMessage(" + msg);
    ByteBuffer requestDataBuffer = msg.buf;

    if (log.isDebugEnabled()) {
        requestDataBuffer.mark();//from w w w . j  ava 2s .  co m
        BBufferJson bbuf = new BBufferJson(requestDataBuffer);
        log.debug(bbuf.toDetailString());
        requestDataBuffer.reset();
    }

    final RequestToCancel requestToCancel = new RequestToCancel(msg.header.messageId, 0L, 0L, asyncResult);

    final boolean isNegotiate = BNegotiate.isNegotiateMessage(requestDataBuffer);
    final boolean isJson = isNegotiate
            || BMessageHeader.detectProtocol(requestDataBuffer) == BMessageHeader.MAGIC_JSON;
    if (log.isDebugEnabled())
        log.debug("isJson=" + isJson);

    try {
        StringBuilder destUrl = null;

        // Negotiate?
        if (isNegotiate) {

            // Send a GET request and pass the negotiate string as parameter

            String negoStr = new String(requestDataBuffer.array(), requestDataBuffer.position(),
                    requestDataBuffer.limit(), "UTF-8");
            negoStr = URLEncoder.encode(negoStr, "UTF-8");

            String negoServlet = getServletPathForNegotiationAndAuthentication();
            destUrl = getUrlStringBuilder(negoServlet);
            destUrl.append("&negotiate=").append(negoStr);

            // Clear session Cookie
            httpClient.clearHttpSession();
        }

        // Reverse request (long-poll) ?
        else if ((msg.header.flags & BMessageHeader.FLAG_RESPONSE) != 0) {

            String longpollServlet = getServletPathForReverseRequest();
            destUrl = getUrlStringBuilder(longpollServlet);

            timeoutSecondsRequest = 0; // timeout controlled by server, 10min by
                                       // default.
        }

        // Ordinary request
        else {
            destUrl = getUrlStringBuilder("");
        }

        if (log.isDebugEnabled())
            log.debug("open connection, url=" + destUrl);
        final HHttpRequest httpRequest = isNegotiate ? httpClient.get(destUrl.toString(), requestToCancel)
                : httpClient.post(destUrl.toString(), requestDataBuffer, requestToCancel);

        httpRequest.setTimeouts(timeoutSecondsClient, timeoutSecondsRequest);

        requestToCancel.setHttpRequest(httpRequest);

        addRequest(requestToCancel);
    } catch (Throwable e) {
        if (log.isDebugEnabled())
            log.debug("received Throwable: " + e);
        BException bex = new BException(BExceptionC.IOERROR, "IO error", e);
        asyncResult.setAsyncResult(null, bex);
    }

    if (log.isDebugEnabled())
        log.debug(")createRequestForMessage=" + requestToCancel);
    return requestToCancel;
}

From source file:com.robonobo.eon.SEONConnection.java

private void gotIncomingData(SEONPacket pkt) {
    ByteBuffer buf = pkt.getPayload();
    buf.position(0);//from  ww w  .ja v  a 2s  .c om
    // if (DEBUG_LOG_BUFS) {
    // StringBuffer sb = new StringBuffer(this.toString()).append(" receiving data: ");
    // ByteUtil.printBuf(buf, sb);
    // log.debug(sb);
    // }
    receiveLock.lock();
    try {
        incomingDataBufs.add(buf);
        inFlowRate.notifyData(buf.limit());
        if (dataReceiver == null) {
            // Synchronous receives
            haveData.signalAll();
        } else {
            // Async receives
            if (dataReceiverRunning) {
                // The receiver will pick up this pkt when it's finished
                return;
            } else
                fireAsyncReceiver();
        }
    } finally {
        receiveLock.unlock();
    }
}