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:Main.java

public static void writeData(SeekableByteChannel seekableChannel, Charset cs) throws IOException {
    String separator = System.getProperty("line.separator");
    StringBuilder sb = new StringBuilder();
    sb.append("test");
    sb.append(separator);/*from  w w w  .  j ava  2s  . c om*/
    sb.append("test2");
    sb.append(separator);

    CharBuffer charBuffer = CharBuffer.wrap(sb);
    ByteBuffer byteBuffer = cs.encode(charBuffer);
    seekableChannel.write(byteBuffer);
}

From source file:Main.java

/**
 * Returns an MD-5 digest of the database encryption password.
 * <blockquote>This algorithm performs an MD-5 hash on a UTF-8 representation of the password.</blockquote>
 *
 * @param pass The plain encryption password
 *
 * @return The database encryption password digest
 *
 * @throws NoSuchAlgorithmException If the platform doesn't support MD-5
 *///from   w  w w  .  j  ava2  s.  c o m
public static byte[] passToDigest(char[] pass) throws NoSuchAlgorithmException {
    // FIXME: Enhance security for this method
    Charset cs = Charset.forName("UTF-8");
    MessageDigest md = MessageDigest.getInstance("MD5");
    ByteBuffer bbuf = cs.encode(CharBuffer.wrap(pass));
    byte[] bpass = Arrays.copyOf(bbuf.array(), bbuf.remaining());

    return md.digest(bpass);
}

From source file:it.geosolutions.geostore.core.security.password.SecurityUtils.java

/**
 * Converts a char array to a byte array.
 *///from   w ww  .  j ava 2  s  .  co m
public static byte[] toBytes(char[] ch, Charset charset) {
    ByteBuffer buff = charset.encode(CharBuffer.wrap(ch));
    byte[] tmp = new byte[buff.limit()];
    buff.get(tmp);
    return tmp;
}

From source file:android.wulongdao.thirdparty.mime.HttpMultipart.java

private static ByteArrayBuffer encode(final Charset charset, final String string) {
    ByteBuffer encoded = charset.encode(CharBuffer.wrap(string));
    ByteArrayBuffer bab = new ByteArrayBuffer(encoded.remaining());
    bab.append(encoded.array(), encoded.position(), encoded.remaining());
    return bab;//ww  w .  ja va2  s.  com
}

From source file:de.jackwhite20.japs.shared.pipeline.handler.JSONObjectEncoder.java

@Override
protected void encode(ChannelHandlerContext ctx, JSONObject jsonObject, List<Object> out) throws Exception {

    out.add(ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(jsonObject.toString()), CharsetUtil.UTF_8));
}

From source file:com.amazonaws.services.dynamodbv2.online.index.AttributeValueConverter.java

public static AttributeValue parseFromWithAttributeTypeString(String value) throws IllegalArgumentException {
    try {/*from  ww w  .j a  v  a 2s  . c o  m*/
        Map<String, String> valueMap = mapper.readValue(value, new TypeReference<Map<String, String>>() {
        });
        AttributeValue attributeValue = new AttributeValue();
        if (null != valueMap.get("N")) {
            attributeValue.withN(valueMap.get("N"));
        } else if (null != valueMap.get("S")) {
            attributeValue.withS(valueMap.get("S"));
        } else if (null != valueMap.get("B")) {
            attributeValue.withB(encoder.encode(CharBuffer.wrap(valueMap.get("B"))));
        } else if (null != valueMap.get("NS")) {
            List<String> numberSet = mapper.readValue(valueMap.get("NS"), new TypeReference<List<String>>() {
            });
            attributeValue.withNS(numberSet);
        } else if (null != valueMap.get("SS")) {
            List<String> stringSet = mapper.readValue(valueMap.get("SS"), new TypeReference<List<String>>() {
            });
            attributeValue.withSS(stringSet);
        } else if (null != valueMap.get("BS")) {
            List<String> binaryStringSet = mapper.readValue(valueMap.get("BS"),
                    new TypeReference<List<String>>() {
                    });
            List<ByteBuffer> bianrySet = new ArrayList<ByteBuffer>();
            for (String bss : binaryStringSet) {
                bianrySet.add(encoder.encode(CharBuffer.wrap(bss)));
            }
            attributeValue.withBS(bianrySet);
        } else {
            throw new IllegalArgumentException("Error: Invalid Attribute Value Type. ");
        }
        return attributeValue;
    } catch (CharacterCodingException cce) {
        throw new IllegalArgumentException("Error: Failed to encode binary into string.");
    } catch (IOException e) {
        throw new IllegalArgumentException("Error: Failed to parse set from string.");
    }
}

From source file:topoos.APIAccess.mime.HttpMultipart.java

/**
 * Encode.//w w w  .  j av  a  2s  .com
 *
 * @param charset the charset
 * @param string the string
 * @return the byte array buffer
 */
private static ByteArrayBuffer encode(final Charset charset, final String string) {
    ByteBuffer encoded = charset.encode(CharBuffer.wrap(string));
    ByteArrayBuffer bab = new ByteArrayBuffer(encoded.remaining());
    bab.append(encoded.array(), encoded.position(), encoded.remaining());
    return bab;
}

From source file:Main.java

/**
 * Returns a new byte array containing the characters of the specified
 * string encoded using the given charset.
 * //from   w w  w. jav a  2 s. com
 * It is equivalent to <code>input.getBytes(charset)</code> except it has
 * workaround for the bug ID 61917.
 * 
 * @see https://code.google.com/p/android/issues/detail?id=61917
 */
//@formatter:off
/*
 * The original code is available from
 *     https://android.googlesource.com/platform/libcore/+/android-4.4_r1.2/libdvm/src/main/java/java/lang/String.java
 */
//@formatter:on
public static byte[] getBytes(String input, Charset charset) {
    CharBuffer chars = CharBuffer.wrap(input.toCharArray());
    // @formatter:off
    CharsetEncoder encoder = charset.newEncoder().onMalformedInput(CodingErrorAction.REPLACE)
            .onUnmappableCharacter(CodingErrorAction.REPLACE);
    // @formatter:on
    ByteBuffer buffer;
    buffer = encode(chars.asReadOnlyBuffer(), encoder);
    byte[] bytes = new byte[buffer.limit()];
    buffer.get(bytes);
    return bytes;

}

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

public static Query handleQuery(Query query, KVPairs kv, HttpRequest request, ChannelHandlerContext ctx)
        throws IOException, QueryException {

    String async = kv.getValue("async");
    if (async == null) {
        return query;
    } else if (async.equals("new")) {
        StringBuilderWriter writer = new StringBuilderWriter(50);
        HttpResponse response = HttpUtils.startResponse(writer);
        String asyncUuid = genAsyncUuid();
        asyncCache.put(asyncUuid, query);
        Query.traceLog.info("async create {} from {}", asyncUuid, query);
        writer.write("{\"id\":\"" + asyncUuid + "\"}");
        ByteBuf textResponse = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(writer.getBuilder()),
                CharsetUtil.UTF_8);/*from ww  w  .  j  av a 2s.c  om*/
        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);
        if (!HttpHeaders.isKeepAlive(request)) {
            lastContentFuture.addListener(ChannelFutureListener.CLOSE);
        }
        return null;
    } else {
        Query asyncQuery = asyncCache.getIfPresent(async);
        asyncCache.invalidate(async);
        Query.traceLog.info("async restore {} as {}", async, asyncQuery);
        if (asyncQuery != null) {
            return asyncQuery;
        } else {
            throw new QueryException("Missing Async Id");
        }
    }
}

From source file:com.srotya.tau.api.Utils.java

public static boolean isCharsetMisInterpreted(String input, String encoding) {
    CharsetDecoder decoder = Charset.forName("ascii").newDecoder();
    CharsetEncoder encoder = Charset.forName(encoding).newEncoder();
    ByteBuffer tmp;//from  w w w.j  av  a 2  s.  co m
    try {
        tmp = encoder.encode(CharBuffer.wrap(input));
    } catch (CharacterCodingException e) {
        return false;
    }

    try {
        decoder.decode(tmp);
        return true;
    } catch (CharacterCodingException e) {
        return false;
    }
}