Example usage for java.nio CharBuffer wrap

List of usage examples for java.nio CharBuffer wrap

Introduction

In this page you can find the example usage for java.nio CharBuffer wrap.

Prototype

public static CharBuffer wrap(CharSequence chseq) 

Source Link

Document

Creates a new char buffer by wrapping the given char sequence.

Usage

From source file:com.addthis.hydra.query.web.HttpQueryHandler.java

private void fastHandle(ChannelHandlerContext ctx, FullHttpRequest request, String target, KVPairs kv)
        throws Exception {
    StringBuilderWriter writer = new StringBuilderWriter(50);
    HttpResponse response = HttpUtils.startResponse(writer);
    response.headers().add("Access-Control-Allow-Origin", "*");

    switch (target) {
    case "/metrics": {
        fakeMetricsServlet.writeMetrics(writer, kv);
        break;//w w  w . j  a  v  a2  s  .co m
    }
    case "/running":
    case "/query/list":
    case "/query/running":
    case "/v2/queries/running.list": {
        Jackson.defaultMapper().writerWithDefaultPrettyPrinter().writeValue(writer, tracker.getRunning());
        break;
    }
    case "/done":
    case "/complete":
    case "/query/done":
    case "/query/complete":
    case "/completed/list":
    case "/v2/queries/finished.list": {
        Jackson.defaultMapper().writerWithDefaultPrettyPrinter().writeValue(writer, tracker.getCompleted());
        break;
    }
    case "/query/all":
    case "/v2/queries/list": {
        Collection<QueryEntryInfo> aggregatingSnapshot = tracker.getRunning();
        aggregatingSnapshot.addAll(tracker.getCompleted());
        Jackson.defaultMapper().writerWithDefaultPrettyPrinter().writeValue(writer, aggregatingSnapshot);
        break;
    }
    case "/cancel":
    case "/query/cancel": {
        if (tracker.cancelRunning(kv.getValue("uuid"))) {
            writer.write("canceled " + kv.getValue("uuid"));
        } else {
            writer.write("canceled failed for " + kv.getValue("uuid"));
            response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }
        break;
    }
    case "/workers":
    case "/query/workers":
    case "/v2/queries/workers": {
        Map<String, Integer> workerSnapshot = meshQueryMaster.worky().values().stream()
                .collect(toMap(WorkerData::hostName, WorkerData::queryLeases));
        Jackson.defaultMapper().writerWithDefaultPrettyPrinter().writeValue(writer, workerSnapshot);
        break;
    }
    case "/host":
    case "/host/list":
    case "/v2/host/list":
        String queryStatusUuid = kv.getValue("uuid");
        QueryEntry queryEntry = tracker.getQueryEntry(queryStatusUuid);
        if (queryEntry != null) {
            DetailedStatusHandler hostDetailsHandler = new DetailedStatusHandler(writer, response, ctx, request,
                    queryEntry);
            hostDetailsHandler.handle();
            return;
        } else {
            QueryEntryInfo queryEntryInfo = tracker.getCompletedQueryInfo(queryStatusUuid);
            if (queryEntryInfo != null) {
                Jackson.defaultMapper().writerWithDefaultPrettyPrinter().writeValue(writer, queryEntryInfo);
            } else {
                log.trace("could not find query for status");
                if (ctx.channel().isActive()) {
                    sendError(ctx, new HttpResponseStatus(NOT_FOUND.code(), "could not find query"));
                }
                return;
            }
            break;
        }
    case "/git":
    case "/v2/settings/git.properties": {
        try {
            Jackson.defaultMapper().writeValue(writer,
                    ConfigFactory.parseResourcesAnySyntax("/hydra-git.properties").getConfig("git"));
        } catch (Exception ex) {
            String noGitWarning = "Error loading git.properties, possibly jar was not compiled with maven.";
            log.warn(noGitWarning);
            writer.write(noGitWarning);
        }
        break;
    }
    case "/query/encode": {
        Query q = new Query(null, new String[] { kv.getValue("query", kv.getValue("path", "")) }, null);
        JSONArray path = CodecJSON.encodeJSON(q).getJSONArray("path");
        writer.write(path.toString());
        break;
    }
    case "/query/decode": {
        String qo = "{path:" + kv.getValue("query", kv.getValue("path", "")) + "}";
        Query q = CodecJSON.decodeString(Query.class, qo);
        writer.write(q.getPaths()[0]);
        break;
    }
    default:
        // forward to static file server
        ctx.pipeline().addLast(staticFileHandler);
        request.retain();
        ctx.fireChannelRead(request);
        return; // don't do text response clean up
    }
    log.trace("response being sent {}", writer);
    ByteBuf textResponse = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(writer.getBuilder()), UTF_8);
    HttpContent content = new DefaultHttpContent(textResponse);
    response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, textResponse.readableBytes());
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    ctx.write(response);
    ctx.write(content);
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    log.trace("response pending");
    if (!HttpHeaders.isKeepAlive(request)) {
        log.trace("Setting close listener");
        ((Future<Void>) lastContentFuture).addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:org.apache.arrow.vector.util.Text.java

/**
 * Converts the provided String to bytes using the UTF-8 encoding. If <code>replace</code> is true, then malformed
 * input is replaced with the substitution character, which is U+FFFD. Otherwise the method throws a
 * MalformedInputException./*w  w w  .  j  av a2 s .com*/
 *
 * @return ByteBuffer: bytes stores at ByteBuffer.array() and length is ByteBuffer.limit()
 */
public static ByteBuffer encode(String string, boolean replace) throws CharacterCodingException {
    CharsetEncoder encoder = ENCODER_FACTORY.get();
    if (replace) {
        encoder.onMalformedInput(CodingErrorAction.REPLACE);
        encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
    }
    ByteBuffer bytes = encoder.encode(CharBuffer.wrap(string.toCharArray()));
    if (replace) {
        encoder.onMalformedInput(CodingErrorAction.REPORT);
        encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
    }
    return bytes;
}

From source file:org.cloudata.core.common.io.CText.java

/**
 * Converts the provided String to bytes using the
 * UTF-8 encoding. If <code>replace</code> is true, then
 * malformed input is replaced with the//w w  w.ja  va2  s  .  c o m
 * substitution character, which is U+FFFD. Otherwise the
 * method throws a MalformedInputException.
 * @return ByteBuffer: bytes stores at ByteBuffer.array() 
 *                     and length is ByteBuffer.limit()
 */
public static ByteBuffer encode(String string, boolean replace) throws CharacterCodingException {
    synchronized (ENCODER) {
        if (replace) {
            ENCODER.onMalformedInput(CodingErrorAction.REPLACE);
            ENCODER.onUnmappableCharacter(CodingErrorAction.REPLACE);
        }
        ByteBuffer bytes = ENCODER.encode(CharBuffer.wrap(string.toCharArray()));
        if (replace) {
            ENCODER.onMalformedInput(CodingErrorAction.REPORT);
            ENCODER.onUnmappableCharacter(CodingErrorAction.REPORT);
        }
        return bytes;
    }
}

From source file:org.opencms.i18n.CmsEncoder.java

/**
 * Encodes all characters that are contained in the String which can not displayed 
 * in the given encodings charset with HTML entity references
 * like <code>&amp;#8364;</code>.<p>
 * //from w w  w . j  a  v  a2s.com
 * This is required since a Java String is 
 * internally always stored as Unicode, meaning it can contain almost every character, but 
 * the HTML charset used might not support all such characters.<p>
 * 
 * @param input the input to encode for HTML
 * @param encoding the charset to encode the result with
 * 
 * @return the input with the encoded HTML entities
 * 
 * @see #decodeHtmlEntities(String, String)
 */
public static String encodeHtmlEntities(String input, String encoding) {

    StringBuffer result = new StringBuffer(input.length() * 2);
    CharBuffer buffer = CharBuffer.wrap(input.toCharArray());
    Charset charset = Charset.forName(encoding);
    CharsetEncoder encoder = charset.newEncoder();
    for (int i = 0; i < buffer.length(); i++) {
        int c = buffer.get(i);
        if (c < 128) {
            // first 128 chars are contained in almost every charset
            result.append((char) c);
            // this is intended as performance improvement since 
            // the canEncode() operation appears quite CPU heavy
        } else if (encoder.canEncode((char) c)) {
            // encoder can encode this char
            result.append((char) c);
        } else {
            // append HTML entity reference
            result.append(ENTITY_PREFIX);
            result.append(c);
            result.append(";");
        }
    }
    return result.toString();
}

From source file:com.alexandreroman.nrelay.NmeaRelayService.java

private void sendNmeaOnLocalNetwork(String nmea) throws IOException {
    if (!prefs.getBoolean(SP_NETWORK_READY, false)) {
        Log.d(TAG, "Network is not ready: cannot relay NMEA");
        updateState(State.NETWORK_UNAVAILABLE);
        return;/*  w  ww . ja  v  a 2s  .co  m*/
    }

    if (sock == null) {
        Log.d(TAG, "Initializing client socket");
        final String hostAddress = prefs.getString(SP_HOST_ADDRESS, "192.168.1.93");
        if (hostAddress == null) {
            throw new IOException("No host address set");
        }
        final int port = Integer.parseInt(prefs.getString(SP_PORT, "0"));
        final InetSocketAddress serverAddr = new InetSocketAddress(hostAddress, port);
        sock = SocketChannel.open();
        sock.configureBlocking(true);
        sock.socket().setSoTimeout(4000);

        Log.d(TAG, "Connecting to server: " + hostAddress + ":" + port);
        try {
            sock.connect(serverAddr);
        } catch (ConnectException e) {
            Log.w(TAG, "Failed to connect to server");
            updateState(State.SERVER_UNREACHABLE);
            sock = null;
            return;
        }
    }

    buffer.clear();
    encoder.encode(CharBuffer.wrap(nmea), buffer, true);
    buffer.flip();

    if (BuildConfig.DEBUG) {
        Log.v(TAG, "Sending NMEA on local network: " + nmea + " (" + buffer.remaining() + " bytes)");
    }
    while (buffer.hasRemaining()) {
        try {
            sock.write(buffer);
        } catch (IOException e) {
            try {
                sock.close();
            } catch (IOException ignore) {
            }
            updateState(State.SERVER_UNREACHABLE);
            sock = null;
            throw e;
        }
    }
    updateState(State.RELAYING_NMEA);
}

From source file:org.sonews.daemon.sync.SynchronousNNTPConnection.java

public void print(final String line) throws IOException {
    writeToChannel(CharBuffer.wrap(line), charset, line);
}

From source file:eap.util.EDcodeUtil.java

public static byte[] utf8Encode(CharSequence string) {
    try {// w  w  w  . j a  v a  2  s .c  o  m
        ByteBuffer bytes = CHARSET.newEncoder().encode(CharBuffer.wrap(string));
        byte[] bytesCopy = new byte[bytes.limit()];
        System.arraycopy(bytes.array(), 0, bytesCopy, 0, bytes.limit());

        return bytesCopy;
    } catch (CharacterCodingException e) {
        throw new IllegalArgumentException("Encoding failed", e);
    }
}

From source file:org.geppetto.frontend.messaging.DefaultMessageSender.java

private void sendTextMessage(String message, OutboundMessages messageType) {

    try {/* w  w  w  .java 2s . c om*/

        long startTime = System.currentTimeMillis();
        CharBuffer buffer = CharBuffer.wrap(message);
        wsOutbound.writeTextMessage(buffer);
        if (messageType.equals("experiment_status")) {
            logger.info(String.format("Sent text message - %s, length: %d bytes, took: %d ms", messageType,
                    message.length(), System.currentTimeMillis() - startTime));
        }

    } catch (IOException e) {
        logger.warn("Failed to send message", e);
        notifyListeners(MessageSenderEvent.Type.MESSAGE_SEND_FAILED);
    }
}

From source file:com.gistlabs.mechanize.util.apache.URLEncodedUtils.java

/**
 * Decode/unescape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true.
 * //from  w  w w  . java2 s  .  c  o  m
 * @param content the portion to decode
 * @param charset the charset to use
 * @param plusAsBlank if {@code true}, then convert '+' to space (e.g. for www-url-form-encoded content), otherwise leave as is.
 * @return
 */
private static String urldecode(final String content, final Charset charset, final boolean plusAsBlank) {
    if (content == null)
        return null;
    ByteBuffer bb = ByteBuffer.allocate(content.length());
    CharBuffer cb = CharBuffer.wrap(content);
    while (cb.hasRemaining()) {
        char c = cb.get();
        if (c == '%' && cb.remaining() >= 2) {
            char uc = cb.get();
            char lc = cb.get();
            int u = Character.digit(uc, 16);
            int l = Character.digit(lc, 16);
            if (u != -1 && l != -1)
                bb.put((byte) ((u << 4) + l));
            else {
                bb.put((byte) '%');
                bb.put((byte) uc);
                bb.put((byte) lc);
            }
        } else if (plusAsBlank && c == '+')
            bb.put((byte) ' ');
        else
            bb.put((byte) c);
    }
    bb.flip();
    return charset.decode(bb).toString();
}

From source file:org.opencms.i18n.CmsEncoder.java

/**
 * Encodes all characters that are contained in the String which can not displayed 
 * in the given encodings charset with Java escaping like <code>\u20ac</code>.<p>
 * /*from   w w  w.  j  a v  a 2  s.co  m*/
 * This can be used to escape values used in Java property files.<p>
 * 
 * @param input the input to encode for Java
 * @param encoding the charset to encode the result with
 * 
 * @return the input with the encoded Java entities
 */
public static String encodeJavaEntities(String input, String encoding) {

    StringBuffer result = new StringBuffer(input.length() * 2);
    CharBuffer buffer = CharBuffer.wrap(input.toCharArray());
    Charset charset = Charset.forName(encoding);
    CharsetEncoder encoder = charset.newEncoder();
    for (int i = 0; i < buffer.length(); i++) {
        int c = buffer.get(i);
        if (c < 128) {
            // first 128 chars are contained in almost every charset
            result.append((char) c);
            // this is intended as performance improvement since 
            // the canEncode() operation appears quite CPU heavy
        } else if (encoder.canEncode((char) c)) {
            // encoder can encode this char
            result.append((char) c);
        } else {
            // append Java entity reference
            result.append("\\u");
            String hex = Integer.toHexString(c);
            int pad = 4 - hex.length();
            for (int p = 0; p < pad; p++) {
                result.append('0');
            }
            result.append(hex);
        }
    }
    return result.toString();
}