Search in sources :

Example 6 with HttpResponse

use of org.jboss.netty.handler.codec.http.HttpResponse in project NabAlive by jcheype.

the class TtsController method init.

@PostConstruct
void init() {
    restHandler.get(new Route("/tts/:apikey/:voice") {

        @Override
        public void handle(Request request, final Response response, Map<String, String> map) throws Exception {
            String text = StringEscapeUtils.escapeXml(checkNotNull(request.getParam("text")));
            String voice = checkNotNull(map.get("voice"));
            if (!text.startsWith("<s>")) {
                text = "<s>" + text + "</s>";
            }
            final String key = text + "|" + voice;
            byte[] bytes = ttsCache.asMap().get(key);
            if (bytes != null) {
                response.write(ChannelBuffers.copiedBuffer(bytes));
                return;
            }
            asyncHttpClient.preparePost(frenchTtsUrl).setBody(text).execute(new AsyncCompletionHandler<com.ning.http.client.Response>() {

                @Override
                public com.ning.http.client.Response onCompleted(com.ning.http.client.Response asyncResponse) throws Exception {
                    InputStream inputStream = asyncResponse.getResponseBodyAsStream();
                    byte[] bytes = ByteStreams.toByteArray(inputStream);
                    ttsCache.asMap().put(key, bytes);
                    response.write(bytes);
                    return asyncResponse;
                }

                @Override
                public void onThrowable(Throwable t) {
                    logger.error("TTS error", t);
                    HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                    response.write(httpResponse);
                }
            });
        }
    }).get(new Route("/tts/:voice") {

        @Override
        public void handle(Request request, final Response response, Map<String, String> map) throws Exception {
            String text = StringEscapeUtils.escapeXml(checkNotNull(request.getParam("text")));
            String voice = checkNotNull(map.get("voice"));
            if (!text.startsWith("<s>")) {
                text = "<s>" + text + "</s>";
            }
            final String key = text + "|" + voice;
            byte[] bytes = ttsCache.asMap().get(key);
            if (bytes != null) {
                response.write(ChannelBuffers.copiedBuffer(bytes));
                return;
            }
            asyncHttpClient.preparePost(frenchTtsUrl).setBody(text).execute(new AsyncCompletionHandler<com.ning.http.client.Response>() {

                @Override
                public com.ning.http.client.Response onCompleted(com.ning.http.client.Response asyncResponse) throws Exception {
                    InputStream inputStream = asyncResponse.getResponseBodyAsStream();
                    byte[] bytes = ByteStreams.toByteArray(inputStream);
                    ttsCache.asMap().put(key, bytes);
                    response.write(bytes);
                    return asyncResponse;
                }

                @Override
                public void onThrowable(Throwable t) {
                    logger.error("TTS error", t);
                    HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                    response.write(httpResponse);
                }
            });
        }
    });
}
Also used : InputStream(java.io.InputStream) Request(com.nabalive.framework.web.Request) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) Response(com.nabalive.framework.web.Response) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) AsyncCompletionHandler(com.ning.http.client.AsyncCompletionHandler) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) Map(java.util.Map) Route(com.nabalive.framework.web.Route) PostConstruct(javax.annotation.PostConstruct)

Example 7 with HttpResponse

use of org.jboss.netty.handler.codec.http.HttpResponse in project socket.io-netty by ibdknox.

the class PollingIOClient method _write.

private void _write(String message) {
    if (!this.open)
        return;
    HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
    res.addHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
    res.addHeader("Access-Control-Allow-Origin", "*");
    res.addHeader("Access-Control-Allow-Credentials", "true");
    res.addHeader("Connection", "keep-alive");
    res.setContent(ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));
    setContentLength(res, res.getContent().readableBytes());
    // Send the response and close the connection if necessary.
    Channel chan = ctx.getChannel();
    if (chan.isOpen()) {
        ChannelFuture f = chan.write(res);
        if (!isKeepAlive(req) || res.getStatus().getCode() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }
    this.connected = false;
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) Channel(org.jboss.netty.channel.Channel) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse)

Example 8 with HttpResponse

use of org.jboss.netty.handler.codec.http.HttpResponse in project databus by linkedin.

the class DummyHttpRequestHandler method testSetResponseCode.

@Test
public void testSetResponseCode() {
    LOG.info("Start: Testing response code with headers with empty body");
    setupClient();
    ArrayList<byte[]> chunks = new ArrayList<byte[]>();
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("header1", "value1");
    headers.put("header2", "value2");
    HashMap<String, String> footers = new HashMap<String, String>();
    setupServer(HttpResponseStatus.BAD_GATEWAY, chunks, headers, footers);
    ChannelFuture connectFuture = _clientBootstrap.connect(_serverAddress);
    connectFuture.awaitUninterruptibly(1, TimeUnit.SECONDS);
    assertTrue("connect succeeded", connectFuture.isSuccess());
    HttpRequest request = new DefaultHttpRequest(HTTP_1_1, HttpMethod.GET, "/test");
    Channel requestChannel = connectFuture.getChannel();
    ChannelFuture writeFuture = requestChannel.write(request);
    writeFuture.awaitUninterruptibly(1, TimeUnit.SECONDS);
    assertTrue("connect succeeded", writeFuture.isSuccess());
    HttpResponse response = _responseHandler.getResponse();
    assertEquals("response code", HttpResponseStatus.BAD_GATEWAY, response.getStatus());
    assertEquals("Checking header1 value", "value1", response.getHeader("header1"));
    assertEquals("Checking header2 value", "value2", response.getHeader("header2"));
    assertEquals("Checking header3 value", null, response.getHeader("header3"));
    byte[] responseBody = _responseHandler.getReceivedBytes();
    assertTrue("empty response", null == responseBody || responseBody.length == 0);
    LOG.info("Done: Testing response code with headers with empty body");
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) HashMap(java.util.HashMap) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) ChunkedBodyWritableByteChannel(com.linkedin.databus2.core.container.netty.ChunkedBodyWritableByteChannel) Channel(org.jboss.netty.channel.Channel) ArrayList(java.util.ArrayList) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) Test(org.testng.annotations.Test)

Example 9 with HttpResponse

use of org.jboss.netty.handler.codec.http.HttpResponse in project databus by linkedin.

the class DummyHttpRequestHandler method messageReceived.

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    //HttpRequest request = (HttpRequest) e.getMessage();
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
    ChunkedBodyWritableByteChannel writeChannel = new ChunkedBodyWritableByteChannel(e.getChannel(), response);
    for (String key : _headers.keySet()) {
        writeChannel.setMetadata(key, _headers.get(key));
    }
    for (byte[] chunk : _responseChunks) {
        writeChannel.write(ByteBuffer.wrap(chunk));
    }
    writeChannel.setResponseCode(_responseCode);
    for (String key : _footers.keySet()) {
        writeChannel.setMetadata(key, _footers.get(key));
    }
    writeChannel.close();
}
Also used : DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) ChunkedBodyWritableByteChannel(com.linkedin.databus2.core.container.netty.ChunkedBodyWritableByteChannel) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse)

Example 10 with HttpResponse

use of org.jboss.netty.handler.codec.http.HttpResponse in project databus by linkedin.

the class DummyHttpRequestHandler method testWriteOneChunk.

@Test
public void testWriteOneChunk() {
    LOG.info("Start: Testing headers with one chunk");
    setupClient();
    String chunk1 = "hello";
    ArrayList<byte[]> chunks = new ArrayList<byte[]>();
    chunks.add(chunk1.getBytes(Charset.defaultCharset()));
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("header1", "value1");
    headers.put("header2", "value2");
    HashMap<String, String> footers = new HashMap<String, String>();
    setupServer(HttpResponseStatus.OK, chunks, headers, footers);
    ChannelFuture connectFuture = _clientBootstrap.connect(_serverAddress);
    connectFuture.awaitUninterruptibly(1, TimeUnit.SECONDS);
    assertTrue("connect succeeded", connectFuture.isSuccess());
    HttpRequest request = new DefaultHttpRequest(HTTP_1_1, HttpMethod.GET, "/test");
    Channel requestChannel = connectFuture.getChannel();
    ChannelFuture writeFuture = requestChannel.write(request);
    writeFuture.awaitUninterruptibly(1, TimeUnit.SECONDS);
    assertTrue("connect succeeded", writeFuture.isSuccess());
    HttpResponse response = _responseHandler.getResponse();
    assertEquals("response code", Integer.toString(HttpResponseStatus.OK.getCode()), response.getHeader(ChunkedBodyWritableByteChannel.RESPONSE_CODE_FOOTER_NAME));
    assertEquals("Checking header1 value", "value1", response.getHeader("header1"));
    assertEquals("Checking header2 value", "value2", response.getHeader("header2"));
    byte[] responseBody = _responseHandler.getReceivedBytes();
    assertEquals("response length", chunk1.getBytes(Charset.defaultCharset()).length, responseBody.length);
    assertTrue("response content", Arrays.equals(chunk1.getBytes(Charset.defaultCharset()), responseBody));
    LOG.info("Done: Testing headers with one chunk");
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) HashMap(java.util.HashMap) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) ChunkedBodyWritableByteChannel(com.linkedin.databus2.core.container.netty.ChunkedBodyWritableByteChannel) Channel(org.jboss.netty.channel.Channel) ArrayList(java.util.ArrayList) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) Test(org.testng.annotations.Test)

Aggregations

HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)124 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)95 Test (org.testng.annotations.Test)51 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)49 HttpChunk (org.jboss.netty.handler.codec.http.HttpChunk)49 DefaultHttpChunk (org.jboss.netty.handler.codec.http.DefaultHttpChunk)45 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)36 Channel (org.jboss.netty.channel.Channel)33 DefaultHttpChunkTrailer (org.jboss.netty.handler.codec.http.DefaultHttpChunkTrailer)30 HttpChunkTrailer (org.jboss.netty.handler.codec.http.HttpChunkTrailer)27 BootstrapDatabaseTooOldException (com.linkedin.databus2.core.container.request.BootstrapDatabaseTooOldException)25 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)25 Checkpoint (com.linkedin.databus.core.Checkpoint)24 InetSocketAddress (java.net.InetSocketAddress)24 SocketAddress (java.net.SocketAddress)23 ConditionCheck (com.linkedin.databus2.test.ConditionCheck)20 Test (org.junit.Test)20 Logger (org.apache.log4j.Logger)16 Map (java.util.Map)15 ChannelPipeline (org.jboss.netty.channel.ChannelPipeline)15