Search in sources :

Example 61 with HttpResponse

use of org.jboss.netty.handler.codec.http.HttpResponse in project graylog2-server by Graylog2.

the class GELFHttpHandlerTest method testWithJavascriptContentType.

@Test
public void testWithJavascriptContentType() throws Exception {
    when(headers.get(HttpHeaders.Names.CONTENT_TYPE)).thenReturn("application/json");
    HttpTransport.Handler handler = new HttpTransport.Handler(true);
    handler.messageReceived(ctx, evt);
    ArgumentCaptor<HttpResponse> argument = ArgumentCaptor.forClass(HttpResponse.class);
    verify(channel).write(argument.capture());
    verify(ctx, atMost(1)).sendUpstream(any(ChannelEvent.class));
    HttpResponse response = argument.getValue();
    assertEquals(HttpResponseStatus.ACCEPTED, response.getStatus());
    assertEquals(response.headers().get(HttpHeaders.Names.CONNECTION), HttpHeaders.Values.CLOSE);
}
Also used : HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) ChannelEvent(org.jboss.netty.channel.ChannelEvent) Test(org.junit.Test)

Example 62 with HttpResponse

use of org.jboss.netty.handler.codec.http.HttpResponse in project graylog2-server by Graylog2.

the class HttpTransportHandlerTest method messageReceivedSuccessfullyProcessesPOSTRequest.

@Test
public void messageReceivedSuccessfullyProcessesPOSTRequest() throws Exception {
    final HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/gelf");
    httpRequest.headers().add("Host", "localhost");
    httpRequest.headers().add("Origin", "http://example.com");
    httpRequest.headers().add("Connection", "close");
    final String gelfMessage = "{\"version\":\"1.1\",\"short_message\":\"Foo\",\"host\":\"localhost\"}";
    httpRequest.setContent(ChannelBuffers.copiedBuffer(gelfMessage.toCharArray(), StandardCharsets.UTF_8));
    channel.offer(httpRequest);
    channel.finish();
    final HttpResponse httpResponse = channel.poll();
    assertThat(httpResponse.getStatus()).isEqualTo(HttpResponseStatus.ACCEPTED);
    final HttpHeaders headers = httpResponse.headers();
    assertThat(headers.get(HttpHeaders.Names.CONTENT_LENGTH)).isEqualTo("0");
    assertThat(headers.get(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("http://example.com");
    assertThat(headers.get(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isEqualTo("true");
    assertThat(headers.get(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_HEADERS)).isEqualTo("Authorization, Content-Type");
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) HttpHeaders(org.jboss.netty.handler.codec.http.HttpHeaders) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) Test(org.junit.Test)

Example 63 with HttpResponse

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

the class GetAllResponseSender method sendResponse.

/**
     * Sends nested multipart response. Outer multipart wraps all the keys
     * requested. Each key has a separate multipart for the versioned values.
     */
@Override
public void sendResponse(StoreStats performanceStats, boolean isFromLocalZone, long startTimeInMs) throws Exception {
    /*
         * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.
         * However when writing to the outputStream we only send the multiPart object and not the entire
         * mimeMessage. This is intentional.
         *
         * In the earlier version of this code we used to create a multiPart object and just send that multiPart
         * across the wire.
         *
         * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates
         * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated
         * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the
         * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()
         * on the body part. It's this updateHeaders call that transfers the content type from the
         * DataHandler to the part's MIME Content-Type header.
         *
         * To make sure that the Content-Type headers are being updated (without changing too much code), we decided
         * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.
         * This is to make sure multiPart's headers are updated accurately.
         */
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    // multiPartKeys is the outer multipart
    MimeMultipart multiPartKeys = new MimeMultipart();
    ByteArrayOutputStream keysOutputStream = new ByteArrayOutputStream();
    for (Entry<ByteArray, List<Versioned<byte[]>>> entry : versionedResponses.entrySet()) {
        ByteArray key = entry.getKey();
        String base64Key = RestUtils.encodeVoldemortKey(key.get());
        String contentLocationKey = "/" + this.storeName + "/" + base64Key;
        // Create the individual body part - for each key requested
        MimeBodyPart keyBody = new MimeBodyPart();
        try {
            // Add the right headers
            keyBody.addHeader(CONTENT_TYPE, "application/octet-stream");
            keyBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
            keyBody.addHeader(CONTENT_LOCATION, contentLocationKey);
        } catch (MessagingException me) {
            logger.error("Exception while constructing key body headers", me);
            keysOutputStream.close();
            throw me;
        }
        // multiPartValues is the inner multipart
        MimeMultipart multiPartValues = new MimeMultipart();
        for (Versioned<byte[]> versionedValue : entry.getValue()) {
            byte[] responseValue = versionedValue.getValue();
            VectorClock vectorClock = (VectorClock) versionedValue.getVersion();
            String eTag = RestUtils.getSerializedVectorClock(vectorClock);
            numVectorClockEntries += vectorClock.getVersionMap().size();
            // Create the individual body part - for each versioned value of
            // a key
            MimeBodyPart valueBody = new MimeBodyPart();
            try {
                // Add the right headers
                valueBody.addHeader(CONTENT_TYPE, "application/octet-stream");
                valueBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
                valueBody.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);
                valueBody.setContent(responseValue, "application/octet-stream");
                valueBody.addHeader(RestMessageHeaders.CONTENT_LENGTH, Integer.toString(responseValue.length));
                multiPartValues.addBodyPart(valueBody);
            } catch (MessagingException me) {
                logger.error("Exception while constructing value body part", me);
                keysOutputStream.close();
                throw me;
            }
        }
        try {
            // Add the inner multipart as the content of the outer body part
            keyBody.setContent(multiPartValues);
            multiPartKeys.addBodyPart(keyBody);
        } catch (MessagingException me) {
            logger.error("Exception while constructing key body part", me);
            keysOutputStream.close();
            throw me;
        }
    }
    message.setContent(multiPartKeys);
    message.saveChanges();
    try {
        multiPartKeys.writeTo(keysOutputStream);
    } catch (Exception e) {
        logger.error("Exception while writing mutipart to output stream", e);
        throw e;
    }
    ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();
    responseContent.writeBytes(keysOutputStream.toByteArray());
    // Create the Response object
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    // Set the right headers
    response.setHeader(CONTENT_TYPE, "multipart/binary");
    response.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
    // Copy the data into the payload
    response.setContent(responseContent);
    response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());
    // Write the response to the Netty Channel
    if (logger.isDebugEnabled()) {
        String keyStr = getKeysHexString(this.versionedResponses.keySet());
        debugLog("GET_ALL", this.storeName, keyStr, startTimeInMs, System.currentTimeMillis(), numVectorClockEntries);
    }
    this.messageEvent.getChannel().write(response);
    if (performanceStats != null && isFromLocalZone) {
        recordStats(performanceStats, startTimeInMs, Tracked.GET_ALL);
    }
    keysOutputStream.close();
}
Also used : MessagingException(javax.mail.MessagingException) VectorClock(voldemort.versioning.VectorClock) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) Properties(java.util.Properties) MessagingException(javax.mail.MessagingException) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) ByteArray(voldemort.utils.ByteArray) List(java.util.List) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 64 with HttpResponse

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

the class GetMetadataResponseSender method sendResponse.

/**
     * Sends a normal HTTP response containing the serialization information in
     * a XML format
     */
@Override
public void sendResponse(StoreStats performanceStats, boolean isFromLocalZone, long startTimeInMs) throws Exception {
    ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(this.responseValue.length);
    responseContent.writeBytes(responseValue);
    // 1. Create the Response object
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    // 2. Set the right headers
    response.setHeader(CONTENT_TYPE, "binary");
    response.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
    // 3. Copy the data into the payload
    response.setContent(responseContent);
    response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());
    if (logger.isDebugEnabled()) {
        logger.debug("Response = " + response);
    }
    // Write the response to the Netty Channel
    this.messageEvent.getChannel().write(response);
    if (performanceStats != null && isFromLocalZone) {
        recordStats(performanceStats, startTimeInMs, Tracked.GET);
    }
}
Also used : DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 65 with HttpResponse

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

the class RestErrorHandler method writeErrorResponse.

/**
     * Writes all error responses to the client.
     * 
     * TODO REST-Server 1. collect error stats
     * 
     * @param messageEvent - for retrieving the channel details
     * @param status - error code
     * @param message - error message
     */
public static void writeErrorResponse(MessageEvent messageEvent, HttpResponseStatus status, String message) {
    // Create the Response object
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
    response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.setContent(ChannelBuffers.copiedBuffer("Failure: " + status.toString() + ". " + message + "\r\n", CharsetUtil.UTF_8));
    response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());
    // Write the response to the Netty Channel
    messageEvent.getChannel().write(response);
}
Also used : DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse)

Aggregations

HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)143 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)111 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)61 HttpChunk (org.jboss.netty.handler.codec.http.HttpChunk)53 Test (org.testng.annotations.Test)51 DefaultHttpChunk (org.jboss.netty.handler.codec.http.DefaultHttpChunk)47 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)37 Channel (org.jboss.netty.channel.Channel)34 DefaultHttpChunkTrailer (org.jboss.netty.handler.codec.http.DefaultHttpChunkTrailer)30 HttpChunkTrailer (org.jboss.netty.handler.codec.http.HttpChunkTrailer)28 BootstrapDatabaseTooOldException (com.linkedin.databus2.core.container.request.BootstrapDatabaseTooOldException)25 InetSocketAddress (java.net.InetSocketAddress)25 ChannelFuture (org.jboss.netty.channel.ChannelFuture)25 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)25 Checkpoint (com.linkedin.databus.core.Checkpoint)24 SocketAddress (java.net.SocketAddress)23 ConditionCheck (com.linkedin.databus2.test.ConditionCheck)20 Test (org.junit.Test)20 Logger (org.apache.log4j.Logger)16 ChannelPipeline (org.jboss.netty.channel.ChannelPipeline)16