Example usage for io.netty.handler.codec.http HttpResponseStatus ACCEPTED

List of usage examples for io.netty.handler.codec.http HttpResponseStatus ACCEPTED

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpResponseStatus ACCEPTED.

Prototype

HttpResponseStatus ACCEPTED

To view the source code for io.netty.handler.codec.http HttpResponseStatus ACCEPTED.

Click Source Link

Document

202 Accepted

Usage

From source file:com.bloom.zerofs.rest.NettyResponseChannel.java

License:Open Source License

/**
 * Converts a {@link ResponseStatus} into a {@link HttpResponseStatus}.
 * @param responseStatus {@link ResponseStatus} that needs to be mapped to a {@link HttpResponseStatus}.
 * @return the {@link HttpResponseStatus} that maps to the {@link ResponseStatus}.
 *//*from   w  w w . j ava  2s  . c om*/
private HttpResponseStatus getHttpResponseStatus(ResponseStatus responseStatus) {
    HttpResponseStatus status;
    switch (responseStatus) {
    case Ok:
        status = HttpResponseStatus.OK;
        break;
    case Created:
        status = HttpResponseStatus.CREATED;
        break;
    case Accepted:
        status = HttpResponseStatus.ACCEPTED;
        break;
    case NotModified:
        status = HttpResponseStatus.NOT_MODIFIED;
        break;
    case BadRequest:
        nettyMetrics.badRequestCount.inc();
        status = HttpResponseStatus.BAD_REQUEST;
        break;
    case Unauthorized:
        nettyMetrics.unauthorizedCount.inc();
        status = HttpResponseStatus.UNAUTHORIZED;
        break;
    case NotFound:
        nettyMetrics.notFoundCount.inc();
        status = HttpResponseStatus.NOT_FOUND;
        break;
    case Gone:
        nettyMetrics.goneCount.inc();
        status = HttpResponseStatus.GONE;
        break;
    case Forbidden:
        nettyMetrics.forbiddenCount.inc();
        status = HttpResponseStatus.FORBIDDEN;
        break;
    case ProxyAuthenticationRequired:
        nettyMetrics.proxyAuthRequiredCount.inc();
        status = HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED;
        break;
    case InternalServerError:
        nettyMetrics.internalServerErrorCount.inc();
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        break;
    default:
        nettyMetrics.unknownResponseStatusCount.inc();
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        break;
    }
    return status;
}

From source file:com.difference.historybook.proxy.littleproxy.LittleProxyResponseTest.java

License:Apache License

@Test
public void testGetStatus() {
    FullHttpResponse response = mock(FullHttpResponse.class);
    when(response.getStatus()).thenReturn(HttpResponseStatus.ACCEPTED);

    LittleProxyResponse lpr = new LittleProxyResponse(response);
    assertEquals(HttpResponseStatus.ACCEPTED.code(), lpr.getStatus());
}

From source file:com.github.ambry.admin.AdminIntegrationTest.java

License:Open Source License

/**
 * Deletes the blob with blob ID {@code blobId} and verifies the response returned.
 * @param blobId the blob ID of the blob to DELETE.
 * @throws ExecutionException/*from ww  w.java 2 s  .c  om*/
 * @throws InterruptedException
 */
private void deleteBlobAndVerify(String blobId) throws ExecutionException, InterruptedException {
    FullHttpRequest httpRequest = buildRequest(HttpMethod.DELETE, blobId, null, null);
    verifyDeleted(httpRequest, HttpResponseStatus.ACCEPTED);
}

From source file:com.github.ambry.admin.AdminIntegrationTest.java

License:Open Source License

/**
 * Verifies that the right response code is returned for GET, HEAD and DELETE once a blob is deleted.
 * @param blobId the ID of the blob that was deleted.
 * @throws ExecutionException/*from   www . ja  v  a 2s . c  om*/
 * @throws InterruptedException
 */
private void verifyOperationsAfterDelete(String blobId) throws ExecutionException, InterruptedException {
    FullHttpRequest httpRequest = buildRequest(HttpMethod.GET, blobId, null, null);
    verifyDeleted(httpRequest, HttpResponseStatus.GONE);

    httpRequest = buildRequest(HttpMethod.HEAD, blobId, null, null);
    verifyDeleted(httpRequest, HttpResponseStatus.GONE);

    httpRequest = buildRequest(HttpMethod.DELETE, blobId, null, null);
    verifyDeleted(httpRequest, HttpResponseStatus.ACCEPTED);
}

From source file:com.github.ambry.rest.NettyResponseChannelTest.java

License:Open Source License

/**
 * Sends null input to {@link NettyResponseChannel#setHeader(String, Object)} (through
 * {@link MockNettyMessageProcessor}) and tests for reaction.
 *///from ww w .j a va  2  s.c  o  m
@Test
public void nullHeadersSetTest() {
    HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.SetNullHeader.toString());
    HttpHeaders.setKeepAlive(request, false);
    EmbeddedChannel channel = createEmbeddedChannel();
    channel.writeInbound(request);

    HttpResponse response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.ACCEPTED, response.getStatus());
    assertFalse("Channel not closed on the server", channel.isActive());
}

From source file:com.github.ambry.rest.NettyResponseChannelTest.java

License:Open Source License

/**
 * Tries different exception scenarios for {@link NettyResponseChannel#setRequest(NettyRequest)}.
 *//*from  w  ww.  j  ava2 s . c om*/
@Test
public void setRequestTest() {
    HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.SetRequest.toString());
    HttpHeaders.setKeepAlive(request, false);
    EmbeddedChannel channel = createEmbeddedChannel();
    channel.writeInbound(request);

    HttpResponse response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.ACCEPTED, response.getStatus());
    assertFalse("Channel not closed on the server", channel.isActive());
}

From source file:com.github.ambry.rest.NettyResponseChannelTest.java

License:Open Source License

/**
 * Checks the headers in the response match those in the request.
 * @param request the {@link HttpRequest} with the original value of the headers.
 * @param response the {@link HttpResponse} that should have the same value for some headers in {@code request}.
 * @throws ParseException/*from   www . j  a  va 2  s  .  c om*/
 */
private void checkHeaders(HttpRequest request, HttpResponse response) throws ParseException {
    assertEquals("Unexpected response status", HttpResponseStatus.ACCEPTED, response.getStatus());
    assertEquals(HttpHeaders.Names.CONTENT_TYPE + " does not match",
            HttpHeaders.getHeader(request, HttpHeaders.Names.CONTENT_TYPE),
            HttpHeaders.getHeader(response, HttpHeaders.Names.CONTENT_TYPE));
    assertEquals(HttpHeaders.Names.CONTENT_LENGTH + " does not match",
            HttpHeaders.getHeader(request, HttpHeaders.Names.CONTENT_LENGTH),
            HttpHeaders.getHeader(response, HttpHeaders.Names.CONTENT_LENGTH));
    assertEquals(HttpHeaders.Names.LOCATION + " does not match",
            HttpHeaders.getHeader(request, HttpHeaders.Names.LOCATION),
            HttpHeaders.getHeader(response, HttpHeaders.Names.LOCATION));
    assertEquals(HttpHeaders.Names.LAST_MODIFIED + " does not match",
            HttpHeaders.getDateHeader(request, HttpHeaders.Names.LAST_MODIFIED),
            HttpHeaders.getDateHeader(response, HttpHeaders.Names.LAST_MODIFIED));
    assertEquals(HttpHeaders.Names.EXPIRES + " does not match",
            HttpHeaders.getDateHeader(request, HttpHeaders.Names.EXPIRES),
            HttpHeaders.getDateHeader(response, HttpHeaders.Names.EXPIRES));
    assertEquals(HttpHeaders.Names.CACHE_CONTROL + " does not match",
            HttpHeaders.getHeader(request, HttpHeaders.Names.CACHE_CONTROL),
            HttpHeaders.getHeader(response, HttpHeaders.Names.CACHE_CONTROL));
    assertEquals(HttpHeaders.Names.PRAGMA + " does not match",
            HttpHeaders.getHeader(request, HttpHeaders.Names.PRAGMA),
            HttpHeaders.getHeader(response, HttpHeaders.Names.PRAGMA));
    assertEquals(HttpHeaders.Names.DATE + " does not match",
            HttpHeaders.getDateHeader(request, HttpHeaders.Names.DATE),
            HttpHeaders.getDateHeader(response, HttpHeaders.Names.DATE));
    assertEquals(MockNettyMessageProcessor.CUSTOM_HEADER_NAME + " does not match",
            HttpHeaders.getHeader(request, MockNettyMessageProcessor.CUSTOM_HEADER_NAME),
            HttpHeaders.getHeader(response, MockNettyMessageProcessor.CUSTOM_HEADER_NAME));
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpUploadHandler.java

License:Open Source License

@SuppressWarnings("FutureReturnValueIgnored")
@Override/*ww  w  .  ja  v a  2  s . c om*/
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse response) {
    if (!response.decoderResult().isSuccess()) {
        failAndClose(new IOException("Failed to parse the HTTP response."), ctx);
        return;
    }
    try {
        checkState(userPromise != null, "response before request");
        if (!response.status().equals(HttpResponseStatus.OK)
                && !response.status().equals(HttpResponseStatus.ACCEPTED)
                && !response.status().equals(HttpResponseStatus.CREATED)
                && !response.status().equals(HttpResponseStatus.NO_CONTENT)) {
            // Supporting more than OK status to be compatible with nginx webdav.
            String errorMsg = response.status().toString();
            if (response.content().readableBytes() > 0) {
                byte[] data = new byte[response.content().readableBytes()];
                response.content().readBytes(data);
                errorMsg += "\n" + new String(data, HttpUtil.getCharset(response));
            }
            failAndResetUserPromise(new HttpException(response, errorMsg, null));
        } else {
            succeedAndResetUserPromise();
        }
    } finally {
        if (!HttpUtil.isKeepAlive(response)) {
            ctx.close();
        }
    }
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpUploadHandlerTest.java

License:Open Source License

/**
 * Test that uploading blobs works to both the Action Cache and the CAS. Also test that the
 * handler is reusable./*from   w  w  w.  java 2s  .  co m*/
 */
@Test
public void uploadsShouldWork() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new HttpUploadHandler(null));
    HttpResponseStatus[] statuses = new HttpResponseStatus[] { HttpResponseStatus.OK,
            HttpResponseStatus.CREATED, HttpResponseStatus.ACCEPTED, HttpResponseStatus.NO_CONTENT };

    for (HttpResponseStatus status : statuses) {
        uploadsShouldWork(true, ch, status);
        uploadsShouldWork(false, ch, status);
    }
}

From source file:com.mesosphere.mesos.rx.java.test.simulation.MesosServerSimulation.java

License:Apache License

/**
 * Create a {@code MesosServerSimulation} that will use {@code events} as the event stream to return to a
 * a client when {@code isSubscribePredicate} evaluates to {@code true}
 * <p>//from  www .  j  a  va2 s  . c  om
 * The simulation server must be started using {@link #start()} before requests can be serviced by the server.
 *
 * @param events               The event stream to be returned by the server upon {@code isSubscribePredicate}
 *                             evaluating to {@code true} For each {@link Event} sent to {@code events}, the event
 *                             will be sent by the server.
 * @param sendCodec            The {@link MessageCodec} to use to encode {@link Event}s sent by the server
 * @param receiveCodec         The {@link MessageCodec} to use to decode {@link Call}s received by the server
 * @param isSubscribePredicate The predicate used to determine if a {@link Call} is a "Subscribe" call
 */
public MesosServerSimulation(@NotNull final Observable<Event> events,
        @NotNull final MessageCodec<Event> sendCodec, @NotNull final MessageCodec<Call> receiveCodec,
        @NotNull final Predicate<Call> isSubscribePredicate) {
    this.callsReceived = Collections.synchronizedList(new ArrayList<>());
    this.started = new AtomicBoolean(false);
    this.eventsCompletedLatch = new CountDownLatch(1);
    this.subscribedLatch = new CountDownLatch(1);
    this.sem = new Semaphore(0);
    this.server = RxNetty.createHttpServer(0, (request, response) -> {
        response.getHeaders().setHeader("Accept", receiveCodec.mediaType());

        if (!"/api/v1/scheduler".equals(request.getUri())) {
            response.setStatus(HttpResponseStatus.NOT_FOUND);
            response.getHeaders().setHeader("Content-Length", "0");
            return response.close();
        }
        if (!HttpMethod.POST.equals(request.getHttpMethod())
                || !receiveCodec.mediaType().equals(request.getHeaders().getHeader("Content-Type"))
                || request.getHeaders().getContentLength() <= 0) {
            response.setStatus(HttpResponseStatus.BAD_REQUEST);
            response.getHeaders().setHeader("Content-Length", "0");
            return response.close();
        }

        return request.getContent().flatMap(buf -> {
            final ByteBufInputStream in = new ByteBufInputStream(buf);
            final Call call = receiveCodec.decode(in);
            if (callsReceived.add(call)) {
                sem.release();
            }
            LOGGER.debug(RECEIVE_MARKER, "Call: {}", receiveCodec.show(call));
            if (isSubscribePredicate.test(call)) {
                if (subscribedLatch.getCount() == 0) {
                    final String message = "Only one event stream can be open per server";
                    response.setStatus(HttpResponseStatus.CONFLICT);
                    response.getHeaders().set("Content-Type", "test/plain;charset=utf-8");
                    response.writeString(message);
                    return response.close();
                }
                LOGGER.debug("Responding with event stream from source: {}", events);
                response.getHeaders().setTransferEncodingChunked();
                response.getHeaders().set("Content-Type", sendCodec.mediaType());
                response.getHeaders().add("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
                response.getHeaders().add("Pragma", "no-cache");

                final Subject<Void, Void> subject = PublishSubject.create();
                final MultipleAssignmentSubscription subscription = new MultipleAssignmentSubscription();
                final Subscription actionSubscription = events
                        .doOnSubscribe(() -> LOGGER.debug("Event stream subscription active"))
                        .doOnNext(e -> LOGGER.debug(SEND_MARKER, "Event: {}", sendCodec.show(e)))
                        .doOnError((t) -> LOGGER.error("Error while creating response", t))
                        .doOnCompleted(() -> {
                            eventsCompletedLatch.countDown();
                            LOGGER.debug("Sending events complete");
                            if (!response.isCloseIssued()) {
                                response.close(true);
                            }
                        }).map(sendCodec::encode).map(RecordIOUtils::createChunk).subscribe(bytes -> {
                            if (!response.getChannel().isOpen()) {
                                subscription.unsubscribe();
                                return;
                            }
                            try {
                                LOGGER.trace(SEND_MARKER, "bytes: {}", Arrays.toString(bytes));
                                response.writeBytesAndFlush(bytes);
                            } catch (Exception e) {
                                subject.onError(e);
                            }
                        });
                subscription.set(actionSubscription);
                subscribedLatch.countDown();
                return subject;
            } else {
                response.setStatus(HttpResponseStatus.ACCEPTED);
                return response.close();
            }
        });
    });
}