Example usage for io.netty.handler.codec.http HttpHeaders setHeader

List of usage examples for io.netty.handler.codec.http HttpHeaders setHeader

Introduction

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

Prototype

@Deprecated
public static void setHeader(HttpMessage message, CharSequence name, Iterable<?> values) 

Source Link

Usage

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

License:Open Source License

/**
 * Tests different scenarios with {@link NettyMultipartRequest#prepare()}.
 * Currently tests://from   w w w . j  a  v a2 s .  c  o  m
 * 1. Idempotency of {@link NettyMultipartRequest#prepare()}.
 * 2. Exception scenarios of {@link NettyMultipartRequest#prepare()}.
 * @throws Exception
 */
@Test
public void prepareTest() throws Exception {
    // prepare half baked data
    HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
    HttpPostRequestEncoder encoder = createEncoder(httpRequest, null);
    NettyMultipartRequest request = new NettyMultipartRequest(encoder.finalizeRequest(), nettyMetrics);
    assertTrue("Request channel is not open", request.isOpen());
    // insert random data
    HttpContent httpContent = new DefaultHttpContent(Unpooled.wrappedBuffer(RestTestUtils.getRandomBytes(10)));
    request.addContent(httpContent);
    // prepare should fail
    try {
        request.prepare();
        fail("Preparing request should have failed");
    } catch (HttpPostRequestDecoder.NotEnoughDataDecoderException e) {
        assertEquals("Reference count is not as expected", 1, httpContent.refCnt());
    } finally {
        closeRequestAndValidate(request);
    }

    // more than one blob part
    HttpHeaders httpHeaders = new DefaultHttpHeaders();
    httpHeaders.set(RestUtils.Headers.BLOB_SIZE, 256);
    InMemoryFile[] files = new InMemoryFile[2];
    files[0] = new InMemoryFile(RestUtils.MultipartPost.BLOB_PART,
            ByteBuffer.wrap(RestTestUtils.getRandomBytes(256)));
    files[1] = new InMemoryFile(RestUtils.MultipartPost.BLOB_PART,
            ByteBuffer.wrap(RestTestUtils.getRandomBytes(256)));
    request = createRequest(httpHeaders, files);
    assertEquals("Request size does not match", 256, request.getSize());
    try {
        request.prepare();
        fail("Prepare should have failed because there was more than one " + RestUtils.MultipartPost.BLOB_PART);
    } catch (RestServiceException e) {
        assertEquals("Unexpected RestServiceErrorCode", RestServiceErrorCode.MalformedRequest,
                e.getErrorCode());
    } finally {
        closeRequestAndValidate(request);
    }

    // more than one part named "part-1"
    files = new InMemoryFile[2];
    files[0] = new InMemoryFile("Part-1", ByteBuffer.wrap(RestTestUtils.getRandomBytes(256)));
    files[1] = new InMemoryFile("Part-1", ByteBuffer.wrap(RestTestUtils.getRandomBytes(256)));
    request = createRequest(null, files);
    try {
        request.prepare();
        fail("Prepare should have failed because there was more than one part named Part-1");
    } catch (RestServiceException e) {
        assertEquals("Unexpected RestServiceErrorCode", RestServiceErrorCode.MalformedRequest,
                e.getErrorCode());
    } finally {
        closeRequestAndValidate(request);
    }

    // size of blob does not match the advertized size
    httpHeaders = new DefaultHttpHeaders();
    httpHeaders.set(RestUtils.Headers.BLOB_SIZE, 256);
    files = new InMemoryFile[1];
    files[0] = new InMemoryFile(RestUtils.MultipartPost.BLOB_PART,
            ByteBuffer.wrap(RestTestUtils.getRandomBytes(128)));
    request = createRequest(httpHeaders, files);
    try {
        request.prepare();
        fail("Prepare should have failed because there was more than one " + RestUtils.MultipartPost.BLOB_PART);
    } catch (RestServiceException e) {
        assertEquals("Unexpected RestServiceErrorCode", RestServiceErrorCode.BadRequest, e.getErrorCode());
    } finally {
        closeRequestAndValidate(request);
    }

    // non fileupload (file attribute present)
    httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
    HttpHeaders.setHeader(httpRequest, RestUtils.Headers.BLOB_SIZE, 256);
    files = new InMemoryFile[1];
    files[0] = new InMemoryFile(RestUtils.MultipartPost.BLOB_PART,
            ByteBuffer.wrap(RestTestUtils.getRandomBytes(256)));
    encoder = createEncoder(httpRequest, files);
    encoder.addBodyAttribute("dummyKey", "dummyValue");
    request = new NettyMultipartRequest(encoder.finalizeRequest(), nettyMetrics);
    assertTrue("Request channel is not open", request.isOpen());
    while (!encoder.isEndOfInput()) {
        // Sending null for ctx because the encoder is OK with that.
        request.addContent(encoder.readChunk(null));
    }
    try {
        request.prepare();
        fail("Prepare should have failed because there was non fileupload");
    } catch (RestServiceException e) {
        assertEquals("Unexpected RestServiceErrorCode", RestServiceErrorCode.BadRequest, e.getErrorCode());
    } finally {
        closeRequestAndValidate(request);
    }
}

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

License:Open Source License

/**
 * Sets the value of response headers after making sure that the response metadata is not already sent.
 * @param headerName The name of the header.
 * @param headerValue The intended value of the header.
 * @throws IllegalArgumentException if any of {@code headerName} or {@code headerValue} is null.
 * @throws IllegalStateException if response metadata has already been written to the channel.
 *///from ww  w  .  j  av a 2 s.c  o m
private void setResponseHeader(String headerName, Object headerValue) {
    if (headerName != null && headerValue != null) {
        long startTime = System.currentTimeMillis();
        if (headerValue instanceof Date) {
            HttpHeaders.setDateHeader(responseMetadata, headerName, (Date) headerValue);
        } else {
            HttpHeaders.setHeader(responseMetadata, headerName, headerValue);
        }
        if (responseMetadataWritten.get()) {
            nettyMetrics.deadResponseAccessError.inc();
            throw new IllegalStateException(
                    "Response metadata changed after it has already been written to the channel");
        } else {
            logger.trace("Header {} set to {} for channel {}", headerName,
                    responseMetadata.headers().get(headerName), ctx.channel());
            nettyMetrics.headerSetTimeInMs.update(System.currentTimeMillis() - startTime);
        }
    } else {
        throw new IllegalArgumentException(
                "Header name [" + headerName + "] or header value [" + headerValue + "] null");
    }
}

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

License:Open Source License

/**
 * Provided a cause, returns an error response with the right status and error message.
 * @param cause the cause of the error./*from  www.  ja  v  a  2s  .co m*/
 * @return a {@link FullHttpResponse} with the error message that can be sent to the client.
 */
private FullHttpResponse getErrorResponse(Throwable cause) {
    HttpResponseStatus status;
    StringBuilder errReason = new StringBuilder();
    if (cause instanceof RestServiceException) {
        RestServiceErrorCode restServiceErrorCode = ((RestServiceException) cause).getErrorCode();
        status = getHttpResponseStatus(ResponseStatus.getResponseStatus(restServiceErrorCode));
        if (status == HttpResponseStatus.BAD_REQUEST) {
            errReason.append(" [").append(Utils.getRootCause(cause).getMessage()).append("]");
        }
    } else {
        nettyMetrics.internalServerErrorCount.inc();
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    }
    String fullMsg = "Failure: " + status + errReason;
    logger.trace("Constructed error response for the client - [{}]", fullMsg);
    FullHttpResponse response;
    if (request != null && !request.getRestMethod().equals(RestMethod.HEAD)) {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
                Unpooled.wrappedBuffer(fullMsg.getBytes()));
    } else {
        // for HEAD, we cannot send the actual body but we need to return what the length would have been if this was GET.
        // https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html (Section 9.4)
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
    }
    HttpHeaders.setDate(response, new GregorianCalendar().getTime());
    HttpHeaders.setContentLength(response, fullMsg.length());
    HttpHeaders.setHeader(response, HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
    boolean keepAlive = request != null && !request.getRestMethod().equals(RestMethod.POST)
            && !CLOSE_CONNECTION_ERROR_STATUSES.contains(status);
    HttpHeaders.setKeepAlive(response, keepAlive);
    return response;
}

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

License:Open Source License

/**
 * Tests setting of different available {@link ResponseStatus} codes and sees that they are recognized and converted
 * in {@link NettyResponseChannel}.//ww  w. j  a  v  a2s.  c  o  m
 * <p/>
 * If this test fails, a case for conversion probably needs to be added in {@link NettyResponseChannel}.
 */
@Test
public void setStatusTest() {
    // ask for every status to be set
    for (ResponseStatus expectedResponseStatus : ResponseStatus.values()) {
        HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.SetStatus.toString());
        HttpHeaders.setHeader(request, MockNettyMessageProcessor.STATUS_HEADER_NAME, expectedResponseStatus);
        HttpHeaders.setKeepAlive(request, false);
        EmbeddedChannel channel = createEmbeddedChannel();
        channel.writeInbound(request);

        // pull but discard response
        channel.readOutbound();
        assertFalse("Channel not closed on the server", channel.isActive());
    }
    // check if all the ResponseStatus codes were recognized.
    String metricName = MetricRegistry.name(NettyResponseChannel.class, "UnknownResponseStatusCount");
    long metricCount = MockNettyMessageProcessor.METRIC_REGISTRY.getCounters().get(metricName).getCount();
    assertEquals("Some of the ResponseStatus codes were not recognized", 0, metricCount);
}

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

License:Open Source License

/**
 * Creates a {@link HttpRequest} with some headers set that will be checked on response.
 * @param httpMethod the {@link HttpMethod} desired.
 * @param uri the URI to hit.//from   w  ww .  ja  v a  2s. c  om
 * @return a link {@link HttpRequest} with some headers set.
 */
private HttpRequest createRequestWithHeaders(HttpMethod httpMethod, String uri) {
    long currentTime = System.currentTimeMillis();
    HttpRequest request = RestTestUtils.createRequest(httpMethod, uri, null);
    HttpHeaders.setHeader(request, HttpHeaders.Names.CONTENT_TYPE, "dummy/content-type");
    HttpHeaders.setHeader(request, HttpHeaders.Names.CONTENT_LENGTH, 100);
    HttpHeaders.setHeader(request, HttpHeaders.Names.LOCATION, "dummyLocation");
    HttpHeaders.setDateHeader(request, HttpHeaders.Names.LAST_MODIFIED, new Date(currentTime));
    HttpHeaders.setDateHeader(request, HttpHeaders.Names.EXPIRES, new Date(currentTime + 1));
    HttpHeaders.setHeader(request, HttpHeaders.Names.CACHE_CONTROL, "dummyCacheControl");
    HttpHeaders.setHeader(request, HttpHeaders.Names.PRAGMA, "dummyPragma");
    HttpHeaders.setDateHeader(request, HttpHeaders.Names.DATE, new Date(currentTime + 2));
    HttpHeaders.setHeader(request, MockNettyMessageProcessor.CUSTOM_HEADER_NAME, "customHeaderValue");
    return request;
}

From source file:com.soho.framework.server.servlet.impl.HttpServletResponseImpl.java

License:Apache License

@Override
public void setDateHeader(String name, long date) {
    HttpHeaders.setHeader(this.originalResponse, name, date);
}

From source file:com.soho.framework.server.servlet.impl.HttpServletResponseImpl.java

License:Apache License

@Override
public void setHeader(String name, String value) {
    HttpHeaders.setHeader(this.originalResponse, name, value);
}

From source file:com.soho.framework.server.servlet.impl.HttpServletResponseImpl.java

License:Apache License

@Override
public void setCharacterEncoding(String charset) {
    HttpHeaders.setHeader(this.originalResponse, Names.CONTENT_ENCODING, charset);
}

From source file:com.xx_dev.apn.proxy.ApnProxyPreHandler.java

License:Apache License

private boolean preCheck(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        String originalHost = HostNamePortUtil.getHostName(httpRequest);

        LoggerUtil.info(httpRestLogger, ctx.channel().remoteAddress().toString(),
                httpRequest.getMethod().name(), httpRequest.getUri(), httpRequest.getProtocolVersion().text(),
                httpRequest.headers().get(HttpHeaders.Names.USER_AGENT));

        isPacRequest = false;/*w  w  w  . j  a  va2  s  . co m*/

        // pac request
        if (StringUtils.equals(originalHost, ApnProxyConfig.getConfig().getPacHost())) {
            isPacRequest = true;

            String pacContent = null;
            if (ApnProxyConfig.getConfig().getListenType() == ApnProxyListenType.SSL) {
                pacContent = buildPacForSsl();
            } else {
                pacContent = buildPacForPlain();
            }

            ByteBuf pacResponseContent = Unpooled.copiedBuffer(pacContent, CharsetUtil.UTF_8);
            FullHttpMessage pacResponseMsg = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK, pacResponseContent);
            HttpHeaders.setContentLength(pacResponseMsg, pacResponseContent.readableBytes());
            HttpHeaders.setHeader(pacResponseMsg, "X-APN-PROXY-PAC", "OK");
            HttpHeaders.setHeader(pacResponseMsg, "X-APN-PROXY-URL", "https://github.com/apn-proxy/apn-proxy");
            HttpHeaders.setHeader(pacResponseMsg, "X-APN-PROXY-MSG", "We need more commiters!");

            ctx.write(pacResponseMsg);
            ctx.flush();
            return false;
        }

        // forbid request to proxy server internal network
        for (String forbiddenIp : forbiddenIps) {
            if (StringUtils.startsWith(originalHost, forbiddenIp)) {
                String errorMsg = "Forbidden";
                ctx.write(HttpErrorUtil.buildHttpErrorMessage(HttpResponseStatus.FORBIDDEN, errorMsg));
                ctx.flush();
                return false;
            }
        }

        // forbid request to proxy server local
        if (StringUtils.equals(originalHost, "127.0.0.1") || StringUtils.equals(originalHost, "localhost")) {
            String errorMsg = "Forbidden Host";
            ctx.write(HttpErrorUtil.buildHttpErrorMessage(HttpResponseStatus.FORBIDDEN, errorMsg));
            ctx.flush();
            return false;
        }

        // forbid reqeust to some port
        int originalPort = HostNamePortUtil.getPort(httpRequest);
        for (int fobiddenPort : forbiddenPorts) {
            if (originalPort == fobiddenPort) {
                String errorMsg = "Forbidden Port";
                ctx.write(HttpErrorUtil.buildHttpErrorMessage(HttpResponseStatus.FORBIDDEN, errorMsg));
                ctx.flush();
                return false;
            }
        }

    } else {
        if (isPacRequest) {
            return false;
        }
    }

    return true;
}

From source file:io.reactivex.netty.protocol.http.client.HttpRequestHeaders.java

License:Apache License

public void setHeader(CharSequence name, Object value) {
    HttpHeaders.setHeader(nettyRequest, name, value);
}