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:co.paralleluniverse.comsat.webactors.netty.WebActorHandler.java

License:Open Source License

static void sendHttpRedirect(ChannelHandlerContext ctx, FullHttpRequest req, String newUri) {
    final FullHttpResponse res = new DefaultFullHttpResponse(req.getProtocolVersion(), FOUND);
    HttpHeaders.setHeader(res, LOCATION, newUri);
    writeHttpResponse(ctx, req, res, true);
}

From source file:com.bloom.zerofs.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 w w w.  j a va  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 (responseMetadataWriteInitiated.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.bloom.zerofs.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  w ww. ja v a2 s.  c  o 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();
        errorResponseStatus = ResponseStatus.getResponseStatus(restServiceErrorCode);
        status = getHttpResponseStatus(errorResponseStatus);
        if (status == HttpResponseStatus.BAD_REQUEST) {
            errReason.append(" [").append(Utils.getRootCause(cause).getMessage()).append("]");
        }
    } else {
        nettyMetrics.internalServerErrorCount.inc();
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        errorResponseStatus = ResponseStatus.InternalServerError;
    }
    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 = !forceClose && HttpHeaders.isKeepAlive(responseMetadata) && request != null
            && !request.getRestMethod().equals(RestMethod.POST)
            && !CLOSE_CONNECTION_ERROR_STATUSES.contains(status);
    HttpHeaders.setKeepAlive(response, keepAlive);
    return response;
}

From source file:com.corundumstudio.socketio.handler.ResourceHandler.java

License:Apache License

/**
 * Sets the Date header for the HTTP response
 *
 * @param response//from w w w .java  2s . c  om
 *            HTTP response
 */
private void setDateHeader(HttpResponse response) {
    SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

    Calendar time = new GregorianCalendar();
    HttpHeaders.setHeader(response, HttpHeaders.Names.DATE, dateFormatter.format(time.getTime()));
}

From source file:com.corundumstudio.socketio.handler.ResourceHandler.java

License:Apache License

/**
 * Sends an Error response with status message
 *
 * @param ctx/*from ww  w .  j a  v  a 2 s . c  o m*/
 * @param status
 */
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
    HttpHeaders.setHeader(response, CONTENT_TYPE, "text/plain; charset=UTF-8");
    ByteBuf content = Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8);

    ctx.channel().write(response);
    // Close the connection as soon as the error message is sent.
    ctx.channel().write(content).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.corundumstudio.socketio.handler.ResourceHandler.java

License:Apache License

/**
 * Sets the Date and Cache headers for the HTTP Response
 *
 * @param response/* ww w  .jav  a 2s .  com*/
 *            HTTP response
 * @param fileToCache
 *            file to extract content type
 */
private void setDateAndCacheHeaders(HttpResponse response, long lastModified) {
    SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

    // Date header
    Calendar time = new GregorianCalendar();
    HttpHeaders.setHeader(response, HttpHeaders.Names.DATE, dateFormatter.format(time.getTime()));

    // Add cache headers
    time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
    HttpHeaders.setHeader(response, HttpHeaders.Names.EXPIRES, dateFormatter.format(time.getTime()));
    HttpHeaders.setHeader(response, HttpHeaders.Names.CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
    HttpHeaders.setHeader(response, HttpHeaders.Names.LAST_MODIFIED,
            dateFormatter.format(new Date(lastModified)));
}

From source file:com.corundumstudio.socketio.handler.ResourceHandler.java

License:Apache License

/**
 * Sets the content type header for the HTTP Response
 *
 * @param response/*w ww .ja  v  a 2 s. c o m*/
 *            HTTP response
 * @param file
 *            file to extract content type
 */
private void setContentTypeHeader(HttpResponse response, URLConnection resUrlConnection) {
    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    String resName = resUrlConnection.getURL().getFile();
    HttpHeaders.setHeader(response, HttpHeaders.Names.CONTENT_TYPE, mimeTypesMap.getContentType(resName));
}

From source file:com.cu.http.container.core.adaptor.NettyServletResponse.java

License:Apache License

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

From source file:com.cu.http.container.core.adaptor.NettyServletResponse.java

License:Apache License

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

From source file:com.cu.http.container.core.adaptor.NettyServletResponse.java

License:Apache License

@Override
public void setContentType(String type) {
    HttpHeaders.setHeader(this.originalResponse, HttpHeaders.Names.CONTENT_TYPE, type);
}