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

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

Introduction

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

Prototype

HttpResponseStatus CREATED

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

Click Source Link

Document

201 Created

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}.
 *//*  w ww.j  a va  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.github.ambry.admin.AdminIntegrationTest.java

License:Open Source License

/**
 * Posts a blob with the given {@code headers} and {@code content}.
 * @param headers the headers required./*  www .  ja v a2  s  .c o  m*/
 * @param content the content of the blob.
 * @return the blob ID of the blob.
 * @throws ExecutionException
 * @throws InterruptedException
 */
private String postBlobAndVerify(HttpHeaders headers, ByteBuffer content)
        throws ExecutionException, InterruptedException {
    FullHttpRequest httpRequest = buildRequest(HttpMethod.POST, "/", headers, content);
    Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get();
    HttpResponse response = (HttpResponse) responseParts.poll();
    discardContent(responseParts, 1);
    assertEquals("Unexpected response status", HttpResponseStatus.CREATED, response.getStatus());
    assertTrue("No Date header", HttpHeaders.getDateHeader(response, HttpHeaders.Names.DATE, null) != null);
    assertTrue("No " + RestUtils.Headers.CREATION_TIME,
            HttpHeaders.getHeader(response, RestUtils.Headers.CREATION_TIME, null) != null);
    assertEquals("Content-Length is not 0", 0, HttpHeaders.getContentLength(response));
    String blobId = HttpHeaders.getHeader(response, HttpHeaders.Names.LOCATION, null);

    if (blobId == null) {
        fail("postBlobAndVerify did not return a blob ID");
    }
    return blobId;
}

From source file:com.github.ambry.frontend.FrontendIntegrationTest.java

License:Open Source License

/**
 * Posts a blob with the given {@code headers} and {@code content}.
 * @param headers the headers required./*from w w  w  . j a v a2 s .c  om*/
 * @param content the content of the blob.
 * @return the blob ID of the blob.
 * @throws ExecutionException
 * @throws InterruptedException
 */
private String postBlobAndVerify(HttpHeaders headers, ByteBuffer content)
        throws ExecutionException, InterruptedException {
    FullHttpRequest httpRequest = buildRequest(HttpMethod.POST, "/", headers, content);
    Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get();
    HttpResponse response = (HttpResponse) responseParts.poll();
    assertEquals("Unexpected response status", HttpResponseStatus.CREATED, response.getStatus());
    assertTrue("No Date header", HttpHeaders.getDateHeader(response, HttpHeaders.Names.DATE, null) != null);
    assertTrue("No " + RestUtils.Headers.CREATION_TIME,
            HttpHeaders.getHeader(response, RestUtils.Headers.CREATION_TIME, null) != null);
    assertEquals("Content-Length is not 0", 0, HttpHeaders.getContentLength(response));
    String blobId = HttpHeaders.getHeader(response, HttpHeaders.Names.LOCATION, null);

    if (blobId == null) {
        fail("postBlobAndVerify did not return a blob ID");
    }
    discardContent(responseParts, 1);
    assertTrue("Channel should be active", HttpHeaders.isKeepAlive(response));
    return blobId;
}

From source file:com.github.ambry.frontend.FrontendIntegrationTest.java

License:Open Source License

/**
 * Posts a blob with the given {@code headers} and {@code content}.
 * @param headers the headers required./*from w  ww.j  av  a2s  .c  o m*/
 * @param content the content of the blob.
 * @param usermetadata the {@link ByteBuffer} that represents user metadata
 * @return the blob ID of the blob.
 * @throws Exception
 */
private String multipartPostBlobAndVerify(HttpHeaders headers, ByteBuffer content, ByteBuffer usermetadata)
        throws Exception {
    HttpRequest httpRequest = RestTestUtils.createRequest(HttpMethod.POST, "/", headers);
    HttpPostRequestEncoder encoder = createEncoder(httpRequest, content, usermetadata);
    Queue<HttpObject> responseParts = nettyClient.sendRequest(encoder.finalizeRequest(), encoder, null).get();
    HttpResponse response = (HttpResponse) responseParts.poll();
    assertEquals("Unexpected response status", HttpResponseStatus.CREATED, response.getStatus());
    assertTrue("No Date header", HttpHeaders.getDateHeader(response, HttpHeaders.Names.DATE, null) != null);
    assertTrue("No " + RestUtils.Headers.CREATION_TIME,
            HttpHeaders.getHeader(response, RestUtils.Headers.CREATION_TIME, null) != null);
    assertEquals("Content-Length is not 0", 0, HttpHeaders.getContentLength(response));
    String blobId = HttpHeaders.getHeader(response, HttpHeaders.Names.LOCATION, null);

    if (blobId == null) {
        fail("postBlobAndVerify did not return a blob ID");
    }
    discardContent(responseParts, 1);
    assertTrue("Channel should be active", HttpHeaders.isKeepAlive(response));
    return blobId;
}

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

License:Open Source License

@SuppressWarnings("FutureReturnValueIgnored")
@Override//from  w  w  w  .j  ava  2  s.  co  m
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.  ja  va2 s .  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.netflix.ribbon.examples.rx.RxMovieServer.java

License:Apache License

private Observable<Void> handleRegisterMovie(HttpServerRequest<ByteBuf> request,
        final HttpServerResponse<ByteBuf> response) {
    System.out.println("Http request -> register movie: " + request.getPath());
    return request.getContent().flatMap(new Func1<ByteBuf, Observable<Void>>() {
        @Override/*  w w  w  .  j a  v a  2  s . co  m*/
        public Observable<Void> call(ByteBuf byteBuf) {
            String formatted = byteBuf.toString(Charset.defaultCharset());
            System.out.println("    movie: " + formatted);
            try {
                Movie movie = Movie.from(formatted);
                movies.put(movie.getId(), movie);
                response.setStatus(HttpResponseStatus.CREATED);
            } catch (Exception e) {
                System.err.println("Invalid movie content");
                e.printStackTrace();
                response.setStatus(HttpResponseStatus.BAD_REQUEST);
            }
            return response.close();
        }
    });
}

From source file:com.netflix.ribbon.examples.rx.RxMovieServerTest.java

License:Apache License

@Test
public void testMovieRegistration() {
    String movieFormatted = ORANGE_IS_THE_NEW_BLACK.toString();

    HttpResponseStatus statusCode = RxNetty
            .createHttpPost(baseURL + "/movies", Observable.just(movieFormatted), new StringTransformer())
            .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<HttpResponseStatus>>() {
                @Override//from w  ww .  ja  v a  2  s .  c om
                public Observable<HttpResponseStatus> call(HttpClientResponse<ByteBuf> httpClientResponse) {
                    return Observable.just(httpClientResponse.getStatus());
                }
            }).toBlocking().first();

    assertEquals(HttpResponseStatus.CREATED, statusCode);
    assertEquals(ORANGE_IS_THE_NEW_BLACK, movieServer.movies.get(ORANGE_IS_THE_NEW_BLACK.getId()));
}

From source file:com.nike.cerberus.endpoints.category.CreateCategoryTest.java

License:Apache License

@Test
public void doExecute_returns_201_with_location() {
    final RequestInfo<Category> requestInfo = mock(RequestInfo.class);
    when(requestInfo.getContent()).thenReturn(category);
    final Principal principal = mock(Principal.class);
    when(principal.getName()).thenReturn(user);
    final SecurityContext securityContext = mock(SecurityContext.class);
    when(securityContext.getUserPrincipal()).thenReturn(principal);
    when(categoryService.createCategory(category, user)).thenReturn(categoryId);

    final CompletableFuture<ResponseInfo<Void>> completableFuture = subject.doExecute(requestInfo, executor,
            null, securityContext);//from  ww  w.  j a va2  s.com
    final ResponseInfo<Void> responseInfo = completableFuture.join();
    assertThat(responseInfo.getHttpStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code());
    assertThat(responseInfo.getHeaders().get(HttpHeaders.Names.LOCATION))
            .isEqualTo(CATEGORY_PATH + "/" + categoryId);
}

From source file:com.nike.cerberus.endpoints.sdb.CreateSafeDepositBox.java

License:Apache License

private ResponseInfo<Map<String, String>> createSafeDepositBox(final RequestInfo<SafeDepositBox> request,
        final String basePath) {
    final Optional<SecurityContext> securityContext = CmsRequestSecurityValidator
            .getSecurityContextForRequest(request);

    if (securityContext.isPresent()) {
        final VaultAuthPrincipal vaultAuthPrincipal = (VaultAuthPrincipal) securityContext.get()
                .getUserPrincipal();//  w  w w  .j  av a 2s  . c o m
        final String id = safeDepositBoxService.createSafeDepositBox(request.getContent(),
                vaultAuthPrincipal.getName());

        final String location = basePath + "/" + id;
        final Map<String, String> map = Maps.newHashMap();
        map.put("id", id);
        return ResponseInfo
                .newBuilder(map).withHeaders(new DefaultHttpHeaders().set(LOCATION, location)
                        .set(HEADER_X_REFRESH_TOKEN, Boolean.TRUE.toString()))
                .withHttpStatusCode(HttpResponseStatus.CREATED.code()).build();
    }

    throw ApiException.newBuilder().withApiErrors(DefaultApiError.AUTH_BAD_CREDENTIALS).build();
}