Example usage for java.nio ByteBuffer get

List of usage examples for java.nio ByteBuffer get

Introduction

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

Prototype

public abstract byte get(int index);

Source Link

Document

Returns the byte at the specified index and does not change the position.

Usage

From source file:info.dolezel.fatrat.plugins.DownloadPlugin.java

/**
 * If the captcha image URL depends on the IP address, cookies or other circumstances
 * that won't exist if that URL is loaded in a different environment or location,
 * use this method instead of {@link #solveCaptcha}.
 * @param url URL of the image/*  w  ww .ja v a2  s  . co  m*/
 * @param cb Callback with the result
 */
protected void solveCaptchaLoadLocally(String url, final CaptchaListener cb) {
    fetchPage(url, new PageFetchListener() {

        @Override
        public void onCompleted(ByteBuffer buf, Map<String, String> headers) {
            String type;
            if (headers.containsKey("content-type"))
                type = headers.get("content-type");
            else
                type = "";

            byte[] b = new byte[buf.remaining()];
            buf.get(b);

            String encodedImage = "data:" + type + ";base64," + Base64.encodeBase64String(b);
            solveCaptcha(encodedImage, cb);
        }

        @Override
        public void onFailed(String error) {
            cb.onFailed();
        }
    });
}

From source file:com.l2jfree.loginserver.network.L2ClientSelectorThread.java

public void printDebug(ByteBuffer buf, L2Client client, int opcode) {
    report(ErrorMode.INVALID_OPCODE, client, null, null);

    //if (!Config.PACKET_HANDLER_DEBUG)
    //   return;// w  ww  .ja  v  a 2  s  .  c  o  m

    StringBuilder sb = new StringBuilder("Unknown Packet: ");
    sb.append("0x").append(Integer.toHexString(opcode));
    sb.append(", Client: ").append(client);
    _log.info(sb);

    byte[] array = new byte[buf.remaining()];
    buf.get(array);
    for (String line : StringUtils.split(HexUtil.printData(array), "\n"))
        _log.info(line);
}

From source file:gridool.memcached.gateway.MemcachedProxyHandler.java

@Override
public byte[] handleGet(byte[] key) {
    final ByteBuffer reqPacket = ByteBuffer.allocate(HEADER_LENGTH + key.length);
    // request header
    Header header = new Header(MAGIC_BYTE_REQUEST, OPCODE_GET);
    header.setBodyLength(GET_EXTRA_LENGTH, key.length, 0);
    header.encode(reqPacket);//from www  .  j  a  v a 2  s.  c  o  m
    // request body (key)
    reqPacket.put(key);
    reqPacket.flip();

    final byte[] value;
    final SocketAddress sockAddr = getSocket(key);
    final ByteChannel channel = sockPool.borrowObject(sockAddr);
    try {
        // handle request
        NIOUtils.writeFully(channel, reqPacket);

        // handle response header
        ByteBuffer responseHeaderPacket = ByteBuffer.allocate(HEADER_LENGTH);
        NIOUtils.readFully(channel, responseHeaderPacket);
        responseHeaderPacket.flip();
        // handle response body 
        int totalBody = responseHeaderPacket.getInt(8);
        int keyLen = responseHeaderPacket.getShort(2);
        int extraLen = responseHeaderPacket.get(4);
        int bodyPos = extraLen + keyLen;
        int bodyLen = totalBody - bodyPos;
        if (bodyLen <= 0) {
            return null;
        }
        ByteBuffer responseBodyPacket = ByteBuffer.allocate(totalBody);
        NIOUtils.readFully(channel, responseBodyPacket);
        responseBodyPacket.flip();
        value = new byte[bodyLen];
        responseBodyPacket.get(value, 0, bodyLen);
    } catch (IOException e) {
        LOG.error(e);
        return null;
    } finally {
        sockPool.returnObject(sockAddr, channel);
    }
    return value;
}

From source file:com.facebook.hive.orc.ReaderImpl.java

public ReaderImpl(FileSystem fs, Path path, Configuration conf) throws IOException {
    try {//from   w w w .  j  av  a 2 s .co m
        this.fileSystem = fs;
        this.path = path;
        this.conf = conf;
        FSDataInputStream file = fs.open(path);
        long size = fs.getFileStatus(path).getLen();
        int readSize = (int) Math.min(size, DIRECTORY_SIZE_GUESS);
        ByteBuffer buffer = ByteBuffer.allocate(readSize);
        InStream.read(file, size - readSize, buffer.array(), buffer.arrayOffset() + buffer.position(),
                buffer.remaining());
        int psLen = buffer.get(readSize - 1);
        int psOffset = readSize - 1 - psLen;
        CodedInputStream in = CodedInputStream.newInstance(buffer.array(), buffer.arrayOffset() + psOffset,
                psLen);
        OrcProto.PostScript ps = OrcProto.PostScript.parseFrom(in);
        int footerSize = (int) ps.getFooterLength();
        bufferSize = (int) ps.getCompressionBlockSize();
        switch (ps.getCompression()) {
        case NONE:
            compressionKind = CompressionKind.NONE;
            break;
        case ZLIB:
            compressionKind = CompressionKind.ZLIB;
            break;
        case SNAPPY:
            compressionKind = CompressionKind.SNAPPY;
            break;
        case LZO:
            compressionKind = CompressionKind.LZO;
            break;
        default:
            throw new IllegalArgumentException("Unknown compression");
        }
        codec = WriterImpl.createCodec(compressionKind);

        InputStream instream = InStream.create("footer", file, size - 1 - psLen - footerSize, footerSize, codec,
                bufferSize);
        footer = OrcProto.Footer.parseFrom(instream);
        inspector = new OrcLazyRowObjectInspector(0, footer.getTypesList());
        file.close();
    } catch (IndexOutOfBoundsException e) {
        /**
         * When a non ORC file is read by ORC reader, we get IndexOutOfBoundsException exception while
         * creating a reader. Caught that exception and checked the file header to see if the input
         * file was ORC or not. If its not ORC, throw a NotAnORCFileException with the file
         * attempted to be reading (thus helping to figure out which table-partition was being read).
         */
        checkIfORC(fs, path);
        throw new IOException("Failed to create record reader for file " + path, e);
    } catch (IOException e) {
        throw new IOException("Failed to create record reader for file " + path, e);
    }
}

From source file:android.pim.vcard.VCardEntryConstructor.java

private String encodeString(String originalString, String charsetForDecodedBytes) {
    if (mInputCharset.equalsIgnoreCase(charsetForDecodedBytes)) {
        return originalString;
    }/*from   www  . j  a v a  2  s .  c om*/
    Charset charset = Charset.forName(mInputCharset);
    ByteBuffer byteBuffer = charset.encode(originalString);
    // byteBuffer.array() "may" return byte array which is larger than
    // byteBuffer.remaining(). Here, we keep on the safe side.
    byte[] bytes = new byte[byteBuffer.remaining()];
    byteBuffer.get(bytes);
    try {
        return new String(bytes, charsetForDecodedBytes);
    } catch (UnsupportedEncodingException e) {
        Log.e(LOG_TAG, "Failed to encode: charset=" + charsetForDecodedBytes);
        return null;
    }
}

From source file:com.msopentech.thali.relay.RelayWebServer.java

@Override
public Response serve(IHTTPSession session) {
    Method method = session.getMethod();
    String queryString = session.getQueryParameterString();
    String path = session.getUri();
    Map<String, String> headers = session.getHeaders();

    LOG.info("URI + Query: " + path + (queryString == null ? "" : "?" + queryString));
    LOG.info("METHOD: " + method.toString());
    LOG.info("ORIGIN: " + headers.get("origin"));

    // Handle an OPTIONS request without relaying anything for now
    // TODO: Relay OPTIONS properly, but manage the CORS aspects so
    // we don't introduce dependencies on couch CORS configuration
    if (method.name().equalsIgnoreCase("OPTIONS")) {
        Response optionsResponse = new Response("OK");
        AppendCorsHeaders(optionsResponse, headers);
        optionsResponse.setStatus(Response.Status.OK);
        return optionsResponse;
    }//from w  w  w .  j  a v a2  s .  c  o m

    // Handle request for local HTTP Key URL
    // TODO: Temporary fake values, need to build hook to handle magic URLs and generate proper HTTPKey
    if (path.equalsIgnoreCase("/_relayutility/localhttpkeys")) {
        ObjectMapper mapper = new ObjectMapper();
        String responseBody = null;
        try {
            responseBody = mapper.writeValueAsString(httpKeyTypes);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Could not generate localhttpkeys output", e);
        }
        Response httpKeyResponse = new Response(responseBody);
        AppendCorsHeaders(httpKeyResponse, headers);
        httpKeyResponse.setMimeType("application/json");
        httpKeyResponse.setStatus(Response.Status.OK);
        return httpKeyResponse;
    }

    // Get the body of the request if appropriate
    byte[] requestBody = new byte[0];
    if (method.equals(Method.PUT) || method.equals(Method.POST)) {
        try {
            ByteBuffer bodyBuffer = ((HTTPSession) session).getBody();
            if (bodyBuffer != null) {
                requestBody = new byte[bodyBuffer.remaining()];
                bodyBuffer.get(requestBody);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return GenerateErrorResponse(e.getMessage());
        }
    }

    // Make a new request which we will prepare for relaying to TDH
    BasicHttpEntityEnclosingRequest basicHttpRequest = null;
    try {
        basicHttpRequest = buildRelayRequest(method, path, queryString, headers, requestBody);
    } catch (UnsupportedEncodingException e) {
        String message = "Unable to translate body to new request.\n" + ExceptionUtils.getStackTrace(e);
        return GenerateErrorResponse(message);
    } catch (URISyntaxException e) {
        return GenerateErrorResponse(
                "Unable to generate the URL for the local TDH.\n" + ExceptionUtils.getStackTrace(e));
    }

    // Actually make the relayed call
    HttpResponse tdhResponse = null;
    InputStream tdhResponseContent = null;
    Response clientResponse = null;
    try {
        LOG.info("Relaying call to TDH: " + httpHost.toURI());
        tdhResponse = httpClient.execute(httpHost, basicHttpRequest);
        tdhResponseContent = tdhResponse.getEntity().getContent();

        // Create response and set status and body
        // default the MIME_TYPE for now and we'll set it later when we enumerate the headers
        if (tdhResponse != null) {

            // This is horrible awful evil code to deal with CouchBase note properly sending CouchDB responses
            // for some errors. We must fix this in CouchBase - https://github.com/thaliproject/thali/issues/30
            String responseBodyString = null;
            if (tdhResponse.containsHeader("content-type") && tdhResponse.getFirstHeader("content-type")
                    .getValue().equalsIgnoreCase("application/json")) {
                if (tdhResponse.getStatusLine().getStatusCode() == 404) {
                    responseBodyString = "{\"error\":\"not_found\"}";
                }
                if (tdhResponse.getStatusLine().getStatusCode() == 412) {
                    responseBodyString = "{\"error\":\"missing_id\"}";
                }
            }

            clientResponse = new Response(new RelayStatus(tdhResponse.getStatusLine()),
                    NanoHTTPD.MIME_PLAINTEXT,
                    responseBodyString != null ? IOUtils.toInputStream(responseBodyString)
                            : IOUtils.toBufferedInputStream(tdhResponseContent));
            // If there is a response body we want to send it chunked to enable streaming
            clientResponse.setChunkedTransfer(true);
        }
    } catch (IOException e) {
        String message = "Reading response failed!\n" + ExceptionUtils.getStackTrace(e);
        return GenerateErrorResponse(message);
    } finally {
        // Make sure the read stream is closed so we don't exhaust our pool
        if (tdhResponseContent != null)
            try {
                tdhResponseContent.close();
            } catch (IOException e) {
                LOG.error(e.getMessage());
            }
    }

    // Prep all headers for our final response
    AppendCorsHeaders(clientResponse, headers);
    copyHeadersToResponse(clientResponse, tdhResponse.getAllHeaders());

    return clientResponse;
}

From source file:com.jonbanjo.cups.operations.HttpPoster.java

static OperationResult sendRequest(URL url, ByteBuffer ippBuf, InputStream documentStream, final AuthInfo auth)
        throws IOException {

    final OperationResult opResult = new OperationResult();

    if (ippBuf == null) {
        return null;
    }/*w ww .j a va 2 s .co  m*/

    if (url == null) {
        return null;
    }

    DefaultHttpClient client = new DefaultHttpClient();

    // will not work with older versions of CUPS!
    client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    client.getParams().setParameter("http.socket.timeout", SOCKET_TIMEOUT);
    client.getParams().setParameter("http.connection.timeout", CONNECTION_TIMEOUT);
    client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    client.getParams().setParameter("http.method.response.buffer.warnlimit", new Integer(8092));
    // probabaly not working with older CUPS versions
    client.getParams().setParameter("http.protocol.expect-continue", Boolean.valueOf(true));

    HttpPost httpPost;

    try {
        httpPost = new HttpPost(url.toURI());
    } catch (Exception e) {
        System.out.println(e.toString());
        return null;
    }

    httpPost.getParams().setParameter("http.socket.timeout", SOCKET_TIMEOUT);

    byte[] bytes = new byte[ippBuf.limit()];
    ippBuf.get(bytes);

    ByteArrayInputStream headerStream = new ByteArrayInputStream(bytes);
    // If we need to send a document, concatenate InputStreams
    InputStream inputStream = headerStream;
    if (documentStream != null) {
        inputStream = new SequenceInputStream(headerStream, documentStream);
    }

    // set length to -1 to advice the entity to read until EOF
    InputStreamEntity requestEntity = new InputStreamEntity(inputStream, -1);

    requestEntity.setContentType(IPP_MIME_TYPE);
    httpPost.setEntity(requestEntity);

    if (auth.reason == AuthInfo.AUTH_REQUESTED) {
        AuthHeader.makeAuthHeader(httpPost, auth);
        if (auth.reason == AuthInfo.AUTH_OK) {
            httpPost.addHeader(auth.getAuthHeader());
            //httpPost.addHeader("Authorization", "Basic am9uOmpvbmJveQ==");
        }
    }

    ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
        @Override
        public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            if (response.getStatusLine().getStatusCode() == 401) {
                auth.setHttpHeader(response.getFirstHeader("WWW-Authenticate"));
            } else {
                auth.reason = AuthInfo.AUTH_OK;
            }
            HttpEntity entity = response.getEntity();
            opResult.setHttResult(response.getStatusLine().toString());
            if (entity != null) {
                return EntityUtils.toByteArray(entity);
            } else {
                return null;
            }
        }
    };

    if (url.getProtocol().equals("https")) {

        Scheme scheme = JfSSLScheme.getScheme();
        if (scheme == null)
            return null;
        client.getConnectionManager().getSchemeRegistry().register(scheme);
    }

    byte[] result = client.execute(httpPost, handler);
    //String test = new String(result);
    IppResponse ippResponse = new IppResponse();

    opResult.setIppResult(ippResponse.getResponse(ByteBuffer.wrap(result)));
    opResult.setAuthInfo(auth);
    client.getConnectionManager().shutdown();
    return opResult;
}

From source file:android.pim.vcard.VCardDataBuilder.java

private String encodeString(String originalString, String targetCharset) {
    if (mSourceCharset.equalsIgnoreCase(targetCharset)) {
        return originalString;
    }//  www  . j a  v  a  2 s . co  m
    Charset charset = Charset.forName(mSourceCharset);
    ByteBuffer byteBuffer = charset.encode(originalString);
    // byteBuffer.array() "may" return byte array which is larger than
    // byteBuffer.remaining(). Here, we keep on the safe side.
    byte[] bytes = new byte[byteBuffer.remaining()];
    byteBuffer.get(bytes);
    try {
        return new String(bytes, targetCharset);
    } catch (UnsupportedEncodingException e) {
        Log.e(LOG_TAG, "Failed to encode: charset=" + targetCharset);
        return null;
    }
}

From source file:co.cask.cdap.client.rest.RestStreamWriter.java

@Override
public ListenableFuture<Void> write(ByteBuffer buffer, Map<String, String> headers)
        throws IllegalArgumentException {
    Preconditions.checkArgument(buffer != null, "ByteBuffer parameter is null.");
    HttpEntity content;//from w w w .j  a v  a 2  s.  c  om
    if (buffer.hasArray()) {
        content = new ByteArrayEntity(buffer.array(), buffer.arrayOffset() + buffer.position(),
                buffer.remaining());
    } else {
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        content = new ByteArrayEntity(bytes);
    }
    return write(content, headers);
}

From source file:com.weibo.api.motan.protocol.v2motan.MotanV2Codec.java

/**
 * decode data//  w  w  w . ja  va2s.c o m
 *
 * @return
 * @throws IOException
 */
@Override
public Object decode(Channel channel, String remoteIp, byte[] data) throws IOException {
    MotanV2Header header = MotanV2Header.buildHeader(data);
    Map<String, String> metaMap = new HashMap<String, String>();
    ByteBuffer buf = ByteBuffer.wrap(data);
    int metaSize = buf.getInt(HEADER_SIZE);
    int index = HEADER_SIZE + 4;
    if (metaSize > 0) {
        byte[] meta = new byte[metaSize];
        buf.position(index);
        buf.get(meta);
        metaMap = decodeMeta(meta);
        index += metaSize;
    }
    int bodySize = buf.getInt(index);
    index += 4;
    Object obj = null;
    if (bodySize > 0) {
        byte[] body = new byte[bodySize];
        buf.position(index);
        buf.get(body);
        if (header.isGzip()) {
            body = ByteUtil.unGzip(body);
        }
        //?
        Serialization serialization = getSerializaiontByNum(header.getSerialize());
        obj = new DeserializableObject(serialization, body);
    }
    if (header.isRequest()) {
        if (header.isHeartbeat()) {
            return DefaultRpcHeartbeatFactory.getDefaultHeartbeatRequest(header.getRequestId());
        } else {
            DefaultRequest request = new DefaultRequest();
            request.setRequestId(header.getRequestId());
            request.setInterfaceName(metaMap.remove(M2_PATH));
            request.setMethodName(metaMap.remove(M2_METHOD));
            request.setParamtersDesc(metaMap.remove(M2_METHOD_DESC));
            request.setAttachments(metaMap);
            if (obj != null) {
                request.setArguments(new Object[] { obj });
            }
            if (metaMap.get(M2_GROUP) != null) {
                request.setAttachment(URLParamType.group.getName(), metaMap.get(M2_GROUP));
            }

            if (StringUtils.isNotBlank(metaMap.get(M2_VERSION))) {
                request.setAttachment(URLParamType.version.getName(), metaMap.get(M2_VERSION));
            }

            return request;
        }

    } else {
        if (header.isHeartbeat()) {
            return DefaultRpcHeartbeatFactory.getDefaultHeartbeatResponse(header.getRequestId());
        }
        DefaultResponse response = new DefaultResponse();
        response.setRequestId(header.getRequestId());
        response.setProcessTime(MathUtil.parseLong(metaMap.remove(M2_PROCESS_TIME), 0));
        response.setAttachments(metaMap);
        if (header.getStatus() == MotanV2Header.MessageStatus.NORMAL.getStatus()) {//???
            response.setValue(obj);
        } else {
            String errmsg = metaMap.remove(M2_ERROR);
            Exception e = ExceptionUtil.fromMessage(errmsg);
            if (e == null) {
                e = (Exception) new MotanServiceException("default remote exception. remote errmsg:" + errmsg);
            }
            response.setException(e);
        }
        return response;
    }

}