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

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

Introduction

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

Prototype

@Deprecated
public static String getHeader(HttpMessage message, CharSequence name) 

Source Link

Usage

From source file:org.apache.cxf.transport.http.netty.server.servlet.NettyHttpServletRequest.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override// w ww. jav a2s . c  o  m
public Enumeration getLocales() {
    Collection<Locale> locales = Utils.parseAcceptLanguageHeader(
            HttpHeaders.getHeader(this.originalRequest, HttpHeaders.Names.ACCEPT_LANGUAGE));

    if (locales == null || locales.isEmpty()) {
        locales = new ArrayList<>();
        locales.add(Locale.getDefault());
    }
    return Utils.enumeration(locales);
}

From source file:org.atmosphere.nettosphere.BridgeRuntime.java

License:Apache License

private void handleHttp(final ChannelHandlerContext ctx, final Object messageEvent)
        throws URISyntaxException, IOException {

    boolean skipClose = false;
    AtmosphereResponse response = null;//from  w w  w.  j a v  a  2 s. c  om
    AtmosphereRequest request = null;
    Action a = null;
    boolean resumeOnBroadcast = false;
    boolean keptOpen = false;
    ChannelWriter asyncWriter = null;
    String method = "GET";
    boolean writeHeader = false;
    boolean forceSuspend = false;
    boolean aggregateBodyInMemory = config.aggregateRequestBodyInMemory();

    try {
        if (messageEvent instanceof HttpRequest) {
            final HttpRequest hrequest = (HttpRequest) messageEvent;

            byte[] body = EMPTY;
            if (FullHttpRequest.class.isAssignableFrom(messageEvent.getClass())) {
                ByteBuf b = FullHttpRequest.class.cast(messageEvent).content();
                if (b.isReadable()) {
                    body = new byte[b.readableBytes()];
                    b.readBytes(body);
                }
            }

            // First let's try to see if it's a static resources
            if (!hrequest.getUri().contains(HeaderConfig.X_ATMOSPHERE)) {
                try {
                    hrequest.headers().add(STATIC_MAPPING, "true");
                    super.channelRead(ctx, messageEvent);

                    if (HttpHeaders.getHeader(hrequest, SERVICED) != null) {
                        return;
                    }
                } catch (Exception e) {
                    logger.debug("Unexpected State", e);
                } finally {
                    hrequest.headers().set(STATIC_MAPPING, "false");
                }
            }

            boolean ka = HttpHeaders.isKeepAlive(hrequest);
            asyncWriter = config.supportChunking() ? new ChunkedWriter(ctx.channel(), true, ka)
                    : new StreamWriter(ctx.channel(), true, ka);

            method = hrequest.getMethod().name();

            request = createAtmosphereRequest(ctx, hrequest, body);
            request.setAttribute(KEEP_ALIVE, new Boolean(ka));

            // Hacky. Is the POST doesn't contains a body, we must not close the connection yet.
            AtmosphereRequestImpl.Body b = request.body();
            if (!aggregateBodyInMemory && !hrequest.getMethod().equals(GET) && !b.isEmpty()
                    && (b.hasString() && b.asString().isEmpty()) || (b.hasBytes() && b.asBytes().length == 0)) {
                forceSuspend = true;
            }
        } else {
            request = State.class.cast(ctx.attr(ATTACHMENT).get()).request;
            boolean isLast = HttpChunkedInput.class.cast(messageEvent).isEndOfInput();
            Boolean ka = (Boolean) request.getAttribute(KEEP_ALIVE);

            asyncWriter = config.supportChunking() ? new ChunkedWriter(ctx.channel(), isLast, ka)
                    : new StreamWriter(ctx.channel(), isLast, ka);
            method = request.getMethod();
            ByteBuf internalBuffer = HttpChunkedInput.class.cast(messageEvent).readChunk(ctx).content();

            if (!aggregateBodyInMemory && internalBuffer.hasArray()) {
                request.body(internalBuffer.array());
            } else {
                logger.trace("Unable to read in memory the request's bytes. Using stream");
                request.body(new ByteBufInputStream(internalBuffer));
            }

            if (!isLast) {
                forceSuspend = true;
            }
        }

        response = new AtmosphereResponseImpl.Builder().asyncIOWriter(asyncWriter).writeHeader(writeHeader)
                .destroyable(false).header("Connection", "Keep-Alive").header("Server", "Nettosphere/3.0")
                .request(request).build();

        if (config.supportChunking()) {
            response.setHeader("Transfer-Encoding", "chunked");
        }

        a = framework.doCometSupport(request, response);
        if (forceSuspend) {
            a.type(Action.TYPE.SUSPEND);
            // leave the stream open
            keptOpen = true;
        }

        String transport = (String) request.getAttribute(FrameworkConfig.TRANSPORT_IN_USE);
        if (transport == null) {
            transport = request.getHeader(X_ATMOSPHERE_TRANSPORT);
        }

        if (a.type() == Action.TYPE.SUSPEND) {
            if (transport != null && (transport.equalsIgnoreCase(HeaderConfig.STREAMING_TRANSPORT)
                    || transport.equalsIgnoreCase(SSE_TRANSPORT))) {
                keptOpen = true;
            } else if (transport != null && (transport.equalsIgnoreCase(HeaderConfig.LONG_POLLING_TRANSPORT)
                    || transport.equalsIgnoreCase(HeaderConfig.JSONP_TRANSPORT))) {
                resumeOnBroadcast = true;
            }
        }

        final Action action = (Action) request.getAttribute(NettyCometSupport.SUSPEND);
        final State state = new State(request, action == null ? Action.CONTINUE : action);

        ctx.attr(ATTACHMENT).set(state);

        if (action != null && action.type() == Action.TYPE.SUSPEND) {
            if (action.timeout() != -1) {
                final AtomicReference<ChannelWriter> w = new AtomicReference<ChannelWriter>(asyncWriter);
                final AtomicReference<Future<?>> f = new AtomicReference<Future<?>>();
                f.set(suspendTimer.scheduleAtFixedRate(new Runnable() {
                    @Override
                    public void run() {
                        if (!w.get().isClosed()
                                && (System.currentTimeMillis() - w.get().lastTick()) > action.timeout()) {
                            AtmosphereResourceImpl impl = state.resource();
                            if (impl != null) {
                                asynchronousProcessor.endRequest(impl, false);
                                f.get().cancel(true);
                            }
                        }
                    }
                }, action.timeout(), action.timeout(), TimeUnit.MILLISECONDS));
            }
        } else if (action != null && action.type() == Action.TYPE.RESUME) {
            resumeOnBroadcast = false;
        }
    } catch (AtmosphereMappingException ex) {
        if (method.equalsIgnoreCase("GET")) {
            logger.trace("Unable to map the request {}, trying static file", messageEvent);
        }
    } catch (Throwable e) {
        logger.error("Unable to process request", e);
        throw new IOException(e);
    } finally {
        try {
            if (asyncWriter != null && !resumeOnBroadcast && !keptOpen) {
                if (!skipClose && response != null) {
                    asyncWriter.close(response);
                } else {
                    httpChannels.add(ctx.channel());
                }
            }
        } finally {
            if (request != null && a != null && a.type() != Action.TYPE.SUSPEND) {
                request.destroy();
                response.destroy();
                framework.notify(Action.TYPE.DESTROYED, request, response);
            }
        }
    }
}

From source file:org.atmosphere.nettosphere.BridgeRuntime.java

License:Apache License

private Map<String, String> getHeaders(final HttpRequest request) {
    final Map<String, String> headers = new HashMap<String, String>();

    for (String name : request.headers().names()) {
        // TODO: Add support for multi header
        headers.put(name, HttpHeaders.getHeader(request, name));
    }//from  ww  w . j av  a  2s.  com

    return headers;
}

From source file:org.ebayopensource.scc.cache.CacheResultVerifier.java

License:Apache License

protected String match(FullHttpResponse actualResp) {
    String eTag = HttpHeaders.getHeader(m_cacheResp, "ETag");
    String actualETag = HttpHeaders.getHeader(actualResp, "ETag");
    if (actualETag != null && actualETag.equals(eTag)) {
        return null;
    } else if (actualETag != null && !actualETag.equals(eTag)) {
        return String.format("ETag mismatch: cache - %s; actual - %s", eTag, actualETag);
    } else if (actualETag == null && eTag == null) {
        // match status code
        if (actualResp.getStatus().compareTo(m_cacheResp.getStatus()) != 0) {
            return String.format("Status code mismatch: cache - %s; actual - %s",
                    m_cacheResp.getStatus().code(), actualResp.getStatus().code());
        }// w w w.  j  ava  2 s  .  c  o m

        // match headers
        HttpHeaders actualHeaders = actualResp.headers();
        HttpHeaders headers = m_cacheResp.headers();
        List<String> mh = new ArrayList<>();// mismatched headers
        checkHeaderDiffer(actualHeaders, headers, mh);
        if (!mh.isEmpty()) {
            return String.format("Mismatched headers: %s", mh.toString());
        }
        checkHeaderDiffer(headers, actualHeaders, mh);
        if (!mh.isEmpty()) {
            return String.format("Mismatched headers: %s", mh.toString());
        }

        // match entity
        ByteBuf actualContent = actualResp.content();
        ByteBuf content = m_cacheResp.content();
        int len = actualContent.readableBytes();
        if (len != content.readableBytes()) {
            return "Mismatched body input stream.";
        }

        for (int i = 0; i < len; i++) {
            if (actualContent.getByte(i) != content.getByte(i)) {
                return "Mismatched body input stream.";
            }
        }
    }
    return null;
}

From source file:org.nosceon.titanite.HeaderParams.java

License:Apache License

@Override
public String getString(String name) {
    return HttpHeaders.getHeader(message, name);
}

From source file:org.nosceon.titanite.HeaderParams.java

License:Apache License

public Date getDate(String name) {
    return Optional.ofNullable(HttpHeaders.getHeader(message, name)).flatMap((o) -> {
        try {/*from w w  w  .  j av a  2 s. c  o  m*/
            return Optional.of(HttpHeaders.getDateHeader(message, name));
        } catch (ParseException e) {
            return Optional.empty();
        }
    }).orElse(null);
}

From source file:org.robotbrains.support.web.server.netty.NettyWebServerHandler.java

License:Apache License

/**
 * Get a handshaker factory for the incoming request.
 *
 * @param req//from w w  w. ja  v a 2  s .  c o m
 *          the request which has come in
 *
 * @return the handshaker factory for the request
 */
private WebSocketServerHandshakerFactory getWebSocketHandshakerFactory(HttpRequest req) {
    String host = HttpHeaders.getHeader(req, HttpHeaders.Names.HOST);

    synchronized (webSocketHandshakerFactories) {
        WebSocketServerHandshakerFactory wsFactory = webSocketHandshakerFactories.get(host);
        if (wsFactory == null) {
            wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(host), null, false);
            webSocketHandshakerFactories.put(host, wsFactory);
        }

        return wsFactory;
    }
}

From source file:org.robotbrains.support.web.server.netty.NettyWebServerHandler.java

License:Apache License

/**
 * Add in a response header if there isn't a header with that name already.
 *
 * @param response/*  www.  java  2  s .c  om*/
 *          the HTTP response
 * @param name
 *          the name of the header
 * @param value
 *          the value of the header
 */
public void addHeaderIfNotExists(HttpResponse response, String name, Object value) {

    if (HttpHeaders.getHeader(response, name) == null) {
        HttpHeaders.addHeader(response, name, value);
    }
}