Example usage for io.netty.util CharsetUtil UTF_8

List of usage examples for io.netty.util CharsetUtil UTF_8

Introduction

In this page you can find the example usage for io.netty.util CharsetUtil UTF_8.

Prototype

Charset UTF_8

To view the source code for io.netty.util CharsetUtil UTF_8.

Click Source Link

Document

8-bit UTF (UCS Transformation Format)

Usage

From source file:com.mastfrog.acteur.twitter.TwitterSign.java

public AuthorizationResponse getTwitterAccessTokenFromAuthorizationCode(String pin, String oauth_token,
        String oauth_nonce) throws IOException, InterruptedException, GeneralSecurityException {

    // this particular request uses POST
    String get_or_post = "POST";

    // I think this is the signature method used for all Twitter API calls
    String oauth_signature_method = "HMAC-SHA1";

    // get the timestamp
    Calendar tempcal = Calendar.getInstance();
    long ts = tempcal.getTimeInMillis();// get current time in milliseconds
    String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

    // the parameter string must be in alphabetical order
    String parameter_string = "oauth_consumer_key=" + twitter_consumer_key + "&oauth_nonce=" + oauth_nonce
            + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp
            + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";

    String twitter_endpoint = "https://api.twitter.com/oauth/access_token";
    String twitter_endpoint_host = "api.twitter.com";
    String twitter_endpoint_path = "/oauth/access_token";
    String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
            + encode(parameter_string);//from   w  w  w.  ja  va 2  s. c o  m

    String oauth_signature = computeSignature(signature_base_string, twitter_consumer_secret + "&"); // note the & at the end. Normally the user access_token would go here, but we don't know it yet

    String authorization_header_string = "OAuth oauth_consumer_key=\"" + twitter_consumer_key
            + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
            + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
            + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";
    // System.out.println("authorization_header_string=" + authorization_header_string);

    String access_token = "";
    String access_token_secret = "";
    String user_id = "";
    String screen_name = "";

    RH rh = new RH();
    ResponseLatch latch = new ResponseLatch();

    URL url = URL.builder(Protocols.HTTPS).setHost(Host.parse(twitter_endpoint_host))
            .setPath(twitter_endpoint_path).create();

    client.post().setURL(url).addHeader(Headers.stringHeader("Authorization"), authorization_header_string)
            .setBody("oauth_verifier=" + encode(pin),
                    MediaType.parse("application/x-www-form-urlencoded").withCharset(CharsetUtil.UTF_8))
            .on(StateType.Closed, latch).on(StateType.Timeout, latch).execute(rh);
    latch.latch.await(1, TimeUnit.MINUTES);

    String responseBody = rh.getResponse();

    StringTokenizer st = new StringTokenizer(responseBody, "&");
    String currenttoken = "";
    while (st.hasMoreTokens()) {
        currenttoken = st.nextToken();
        if (currenttoken.startsWith("oauth_token=")) {
            access_token = currenttoken.substring(currenttoken.indexOf("=") + 1);
        } else if (currenttoken.startsWith("oauth_token_secret=")) {
            access_token_secret = currenttoken.substring(currenttoken.indexOf("=") + 1);
        } else if (currenttoken.startsWith("user_id=")) {
            user_id = currenttoken.substring(currenttoken.indexOf("=") + 1);
        } else if (currenttoken.startsWith("screen_name=")) {
            screen_name = currenttoken.substring(currenttoken.indexOf("=") + 1);
        } else {
            System.out.println("Warning... twitter returned a key we weren't looking for: " + currenttoken);
            // something else. The 4 values above are the only ones twitter should return, so this case would be weird.
            // skip
        }
    }
    if ("".equals(access_token) || "".equals(access_token_secret)) {
        throw new IOException("Missing information in " + responseBody);
    }
    return new AuthorizationResponse(access_token, access_token_secret);
}

From source file:com.mastfrog.netty.http.client.RequestBuilder.java

License:Open Source License

@Override
public HttpRequestBuilder setBody(Object o, MediaType contentType) throws IOException {
    if (o instanceof CharSequence) {
        CharSequence seq = (CharSequence) o;
        setBody(seq.toString().getBytes(CharsetUtil.UTF_8), contentType);
    } else if (o instanceof byte[]) {
        byte[] b = (byte[]) o;
        ByteBuf buffer = alloc.buffer(b.length).writeBytes(b);
        setBody(buffer, contentType);//  w  w  w .j  a  va2s. com
    } else if (o instanceof ByteBuf) {
        body = (ByteBuf) o;
        if (send100Continue) {
            addHeader(Headers.stringHeader(HttpHeaders.Names.EXPECT), HttpHeaders.Values.CONTINUE);
        }
        addHeader(Headers.CONTENT_LENGTH, (long) body.readableBytes());
        addHeader(Headers.CONTENT_TYPE, contentType);
    } else if (o instanceof InputStream) {
        ByteBuf buf = newByteBuf();
        try (ByteBufOutputStream out = new ByteBufOutputStream(buf)) {
            try (InputStream in = (InputStream) o) {
                Streams.copy(in, out, 1024);
            }
        }
        setBody(buf, contentType);
    } else if (o instanceof RenderedImage) {
        ByteBuf buf = newByteBuf();
        try (ByteBufOutputStream out = new ByteBufOutputStream(buf)) {
            String type = contentType.subtype();
            if ("jpeg".equals(type)) {
                type = "jpg";
            }
            ImageIO.write((RenderedImage) o, type, out);
        }
        setBody(buf, contentType);
    } else {
        try {
            setBody(new ObjectMapper().writeValueAsBytes(o), contentType);
        } catch (Exception ex) {
            throw new IllegalArgumentException(ex);
        }
    }
    return this;
}

From source file:com.mastfrog.netty.http.client.ResponseHandler.java

License:Open Source License

protected void internalReceive(HttpResponseStatus status, HttpHeaders headers, ByteBuf content) {
    try {/*from   w  w w. j a  va2 s  .  c om*/
        if (status.code() > 399) {
            byte[] b = new byte[content.readableBytes()];
            content.readBytes(b);
            onErrorResponse(status, headers, new String(b, CharsetUtil.UTF_8));
            return;
        }
        if (type == ByteBuf.class) {
            _doReceive(status, headers, type.cast(content));
        } else if (type == String.class || type == CharSequence.class) {
            byte[] b = new byte[content.readableBytes()];
            content.readBytes(b);
            _doReceive(status, headers, type.cast(new String(b, CharsetUtil.UTF_8)));
        } else if (type == byte[].class) {
            byte[] b = new byte[content.readableBytes()];
            content.readBytes(b);
            _doReceive(status, headers, type.cast(b));
        } else {
            byte[] b = new byte[content.readableBytes()];
            content.readBytes(b);
            try {
                Object o = mapper.readValue(b, type);
                _doReceive(status, headers, type.cast(o));
            } catch (JsonParseException ex) {
                content.resetReaderIndex();
                try {
                    String s = Streams.readString(new ByteBufInputStream(content), "UTF-8");
                    onErrorResponse(HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE, headers, s);
                } catch (IOException ex1) {
                    Exceptions.chuck(ex1);
                }
            } catch (Exception ex) {
                Exceptions.chuck(ex);
            }
        }
    } finally {
        latch.countDown();
    }
}

From source file:com.mastfrog.scamper.password.crypto.Encrypter.java

License:Open Source License

private byte[] createKey(String password) {
    byte[] key = password.getBytes(CharsetUtil.UTF_8);
    int bits = (key.length * 8);
    if (bits > 448) {
        int amt = 448 / 8;
        byte[] nue = new byte[amt];
        System.arraycopy(key, 0, nue, 0, amt);
        int pos = amt;
        while (pos < key.length) {
            for (int i = 0; i < nue.length && pos < key.length; i++) {
                nue[i] ^= key[pos++];/*from  www.  j  a v a2  s .  c o m*/
            }
        }
        key = nue;
    }
    return key;
}

From source file:com.mastfrog.scamper.password.crypto.Encrypter.java

License:Open Source License

public String encrypt(String cleartext) {
    try {/*  w w  w .j ava  2s .c o m*/
        byte[] encrypted = cleartext.getBytes(CharsetUtil.UTF_8);
        Cipher encipher = encipher();
        for (int i = 0; i < ROUNDS; i++) {
            encrypted = encipher.doFinal(encrypted);
        }
        return Base64.getEncoder().encodeToString(encrypted);
    } catch (IllegalBlockSizeException | BadPaddingException ex) {
        return Exceptions.chuck(ex);
    }
}

From source file:com.mastfrog.scamper.password.crypto.Encrypter.java

License:Open Source License

public String decrypt(String encrypted) {
    try {//from  w  ww  . j  ava  2s .com
        byte[] decrypted = Base64.getDecoder().decode(encrypted);
        Cipher decipher = decipher();
        for (int i = 0; i < ROUNDS; i++) {
            decrypted = decipher.doFinal(decrypted);
        }
        return new String(decrypted, CharsetUtil.UTF_8);
    } catch (IllegalBlockSizeException | BadPaddingException ex) {
        return Exceptions.chuck(ex);
    }
}

From source file:com.myftpserver.channelinitializer.CommandChannelInitializer.java

License:Apache License

@Override
protected void initChannel(Channel ch) throws Exception {
    String remoteIp = (((InetSocketAddress) ch.remoteAddress()).getAddress().getHostAddress());
    if (myFtpServer.isOverConnectionLimit()) {
        String msg = myFtpServer.getServerConfig().getFtpMessage("330_Connection_Full");
        Utility.disconnectFromClient(ch, logger, remoteIp, msg);
    } else {/*  ww w  . j  a  v  a2  s.co  m*/
        FtpServerConfig serverConfig = myFtpServer.getServerConfig();
        ch.closeFuture().addListener(new CommandChannelClosureListener(myFtpServer, remoteIp));
        ch.pipeline().addLast("idleStateHandler",
                new IdleStateHandler(serverConfig.getCommandChannelConnectionTimeOut(), 30, 0));
        ch.pipeline().addLast("CommandChannelTimeoutHandler",
                new CommandChannelTimeoutHandler(logger, remoteIp));
        ch.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
        ch.pipeline().addLast("frameDecoder", new LineBasedFrameDecoder(1024));
        ch.pipeline().addLast("MyHandler", new FtpSessionHandler(myFtpServer, remoteIp));
    }
}

From source file:com.myftpserver.handler.SendFileNameListHandler.java

License:Apache License

@Override
public void startToSend(ChannelHandlerContext ctx) throws Exception {
    if (fileNameList[index].equals("")) //The directory is empty
    {/*  w  w w  .  ja va2 s .  co  m*/
        closeChannel(ctx);
    } else {
        ctx.writeAndFlush(Unpooled.copiedBuffer(fileNameList[index] + "\r\n", CharsetUtil.UTF_8));
    }
}

From source file:com.myftpserver.handler.SendFileNameListHandler.java

License:Apache License

@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
    if (ctx.channel().isWritable()) {
        try {//from   ww w.j  a va2  s.c  o  m
            ctx.writeAndFlush(Unpooled.copiedBuffer(fileNameList[++index] + "\r\n", CharsetUtil.UTF_8));
        } catch (Exception err) {
            closeChannel(ctx);
        }
    }
}

From source file:com.mylearn.netty.sample.websocket.client.WebSocketClientHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();// w w  w . jav a2s.c  o  m
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        System.out.println("WebSocket Client connected!");
        handshakeFuture.setSuccess();
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content="
                + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        System.out.println("WebSocket Client received message: " + textFrame.text());
    } else if (frame instanceof PongWebSocketFrame) {
        System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
        System.out.println("WebSocket Client received closing");
        ch.close();
    }
}