Package org.jboss.netty.handler.codec.http

Examples of org.jboss.netty.handler.codec.http.HttpResponse


    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        if (!handshakeCompleted) {
            HttpResponse response = (HttpResponse)e.getMessage();
            final HttpResponseStatus status = new HttpResponseStatus(101, "Web Socket Protocol Handshake");

            final boolean validStatus = response.getStatus().equals(status);
            final boolean validUpgrade = response.getHeader(Names.UPGRADE).equals(Values.WEBSOCKET);
            final boolean validConnection = response.getHeader(Names.CONNECTION).equals(Values.UPGRADE);

            if (!validStatus || !validUpgrade || !validConnection) {
                throw new WebSocketException("Invalid handshake response");
            }
           
            handshakeCompleted = true;
            ctx.getPipeline().replace("decoder", "ws-decoder", new WebSocketFrameDecoder());
            callback.onConnect(this);
            return;
        }

        if (e.getMessage() instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) e.getMessage();
            throw new WebSocketException("Unexpected HttpResponse (status=" + response.getStatus() + ", content=" + response.getContent().toString(CharsetUtil.UTF_8) + ")");
        }

        DefaultWebSocketFrame frame = (DefaultWebSocketFrame)e.getMessage();
        callback.onMessage(this, frame);
    }
View Full Code Here


        this.status = HttpResponseStatus.valueOf(status);
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
        response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
        response.setContent(ChannelBuffers.copiedBuffer(text, Charset.forName("UTF-8")));
        e.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
    }
View Full Code Here

        // the response code is 200 for OK and 500 for failed
        boolean failed = message.getExchange().isFailed();
        int defaultCode = failed ? 500 : 200;

        int code = message.getHeader(Exchange.HTTP_RESPONSE_CODE, defaultCode, int.class);
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code));
        LOG.trace("HTTP Status Code: {}", code);

        TypeConverter tc = message.getExchange().getContext().getTypeConverter();

        // append headers
        // must use entrySet to ensure case of keys is preserved
        for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            // use an iterator as there can be multiple values. (must not use a delimiter)
            final Iterator<?> it = ObjectHelper.createIterator(value, null);
            while (it.hasNext()) {
                String headerValue = tc.convertTo(String.class, it.next());
                if (headerValue != null && headerFilterStrategy != null
                        && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) {
                    LOG.trace("HTTP-Header: {}={}", key, headerValue);
                    response.headers().add(key, headerValue);
                }
            }
        }

        Object body = message.getBody();
        Exception cause = message.getExchange().getException();
        // support bodies as native Netty
        ChannelBuffer buffer;

        // if there was an exception then use that as body
        if (cause != null) {
            if (configuration.isTransferException()) {
                // we failed due an exception, and transfer it as java serialized object
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos);
                oos.writeObject(cause);
                oos.flush();
                IOHelper.close(oos, bos);

                // the body should be the serialized java object of the exception
                body = ChannelBuffers.copiedBuffer(bos.toByteArray());
                // force content type to be serialized java object
                message.setHeader(Exchange.CONTENT_TYPE, NettyHttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
            } else {
                // we failed due an exception so print it as plain text
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                cause.printStackTrace(pw);

                // the body should then be the stacktrace
                body = ChannelBuffers.copiedBuffer(sw.toString().getBytes());
                // force content type to be text/plain as that is what the stacktrace is
                message.setHeader(Exchange.CONTENT_TYPE, "text/plain");
            }

            // and mark the exception as failure handled, as we handled it by returning it as the response
            ExchangeHelper.setFailureHandled(message.getExchange());
        }

        if (body instanceof ChannelBuffer) {
            buffer = (ChannelBuffer) body;
        } else {
            // try to convert to buffer first
            buffer = message.getBody(ChannelBuffer.class);
            if (buffer == null) {
                // fallback to byte array as last resort
                byte[] data = message.getBody(byte[].class);
                if (data != null) {
                    buffer = ChannelBuffers.copiedBuffer(data);
                } else {
                    // and if byte array fails then try String
                    String str;
                    if (body != null) {
                        str = message.getMandatoryBody(String.class);
                    } else {
                        str = "";
                    }
                    buffer = ChannelBuffers.copiedBuffer(str.getBytes());
                }
            }
        }
        if (buffer != null) {
            response.setContent(buffer);
            // We just need to reset the readerIndex this time
            if (buffer.readerIndex() == buffer.writerIndex()) {
                buffer.setIndex(0, buffer.writerIndex());
            }
            // TODO How to enable the chunk transport
            int len = buffer.readableBytes();
            // set content-length
            response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, len);
            LOG.trace("Content-Length: {}", len);
        }

        // set the content type in the response.
        String contentType = MessageHelper.getContentType(message);
        if (contentType != null) {
            // set content-type
            response.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
            LOG.trace("Content-Type: {}", contentType);
        }

        // configure connection to accordingly to keep alive configuration
        // favor using the header from the message
        String connection = message.getHeader(HttpHeaders.Names.CONNECTION, String.class);
        if (connection == null) {
            // fallback and use the keep alive from the configuration
            if (configuration.isKeepAlive()) {
                connection = HttpHeaders.Values.KEEP_ALIVE;
            } else {
                connection = HttpHeaders.Values.CLOSE;
            }
        }
        response.headers().set(HttpHeaders.Names.CONNECTION, connection);
        // Just make sure we close the channel when the connection value is close
        if (connection.equalsIgnoreCase(HttpHeaders.Values.CLOSE)) {
            message.setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true);
        }
        LOG.trace("Connection: {}", connection);
View Full Code Here

            // store handler as attachment
            ctx.setAttachment(handler);
            handler.messageReceived(ctx, messageEvent);
        } else {
            // this resource is not found, so send empty response back
            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
            response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
            response.headers().set(Exchange.CONTENT_LENGTH, 0);
            response.setContent(ChannelBuffers.copiedBuffer(new byte[]{}));
            messageEvent.getChannel().write(response);
        }
    }
View Full Code Here

            handler.exceptionCaught(ctx, e);
        } else {
            // we cannot throw the exception here
            LOG.warn("HttpServerChannelHandler is not found as attachment to handle exception, send 404 back to the client.", e.getCause());
            // Now we just send 404 back to the client
            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
            response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
            response.headers().set(Exchange.CONTENT_LENGTH, 0);
            // Here we don't want to expose the exception detail to the client
            response.setContent(ChannelBuffers.copiedBuffer(new byte[]{}));
            ctx.getChannel().write(response);
        }
    }
View Full Code Here

        LOG.debug("Message received: {}", request);

        if (consumer.isSuspended()) {
            // are we suspended?
            LOG.debug("Consumer suspended, cannot service request {}", request);
            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, SERVICE_UNAVAILABLE);
            response.setChunked(false);
            response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
            response.headers().set(Exchange.CONTENT_LENGTH, 0);
            response.setContent(ChannelBuffers.copiedBuffer(new byte[]{}));
            messageEvent.getChannel().write(response);
            return;
        }

        // if its an OPTIONS request then return which methods is allowed
        if ("OPTIONS".equals(request.getMethod().getName())) {
            String s;
            if (consumer.getEndpoint().getHttpMethodRestrict() != null) {
                s = "OPTIONS," + consumer.getEndpoint().getHttpMethodRestrict();
            } else {
                // allow them all
                s = "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,CONNECT,PATCH";
            }
            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
            response.setChunked(false);
            response.headers().set("Allow", s);
            response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
            response.headers().set(Exchange.CONTENT_LENGTH, 0);
            messageEvent.getChannel().write(response);
            return;
        }
        if (consumer.getEndpoint().getHttpMethodRestrict() != null
                && !consumer.getEndpoint().getHttpMethodRestrict().contains(request.getMethod().getName())) {
            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED);
            response.setChunked(false);
            response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
            response.headers().set(Exchange.CONTENT_LENGTH, 0);
            response.setContent(ChannelBuffers.copiedBuffer(new byte[]{}));
            messageEvent.getChannel().write(response);
            return;
        }
        if ("TRACE".equals(request.getMethod().getName()) && !consumer.getEndpoint().isTraceEnabled()) {
            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED);
            response.setChunked(false);
            response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
            response.headers().set(Exchange.CONTENT_LENGTH, 0);
            response.setContent(ChannelBuffers.copiedBuffer(new byte[]{}));
            messageEvent.getChannel().write(response);
            return;
        }
        // must include HOST header as required by HTTP 1.1
        if (!request.headers().names().contains(HttpHeaders.Names.HOST)) {
            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, BAD_REQUEST);
            response.setChunked(false);
            response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
            response.headers().set(Exchange.CONTENT_LENGTH, 0);
            response.setContent(ChannelBuffers.copiedBuffer(new byte[]{}));
            messageEvent.getChannel().write(response);
            return;
        }

        // is basic auth configured
        NettyHttpSecurityConfiguration security = consumer.getEndpoint().getSecurityConfiguration();
        if (security != null && security.isAuthenticate() && "Basic".equalsIgnoreCase(security.getConstraint())) {
            String url = request.getUri();

            // drop parameters from url
            if (url.contains("?")) {
                url = ObjectHelper.before(url, "?");
            }

            // we need the relative path without the hostname and port
            URI uri = new URI(request.getUri());
            String target = uri.getPath();

            // strip the starting endpoint path so the target is relative to the endpoint uri
            String path = consumer.getConfiguration().getPath();
            if (path != null && target.startsWith(path)) {
                target = target.substring(path.length());
            }

            // is it a restricted resource?
            String roles;
            if (security.getSecurityConstraint() != null) {
                // if restricted returns null, then the resource is not restricted and we should not authenticate the user
                roles = security.getSecurityConstraint().restricted(target);
            } else {
                // assume any roles is valid if no security constraint has been configured
                roles = "*";
            }
            if (roles != null) {
                // basic auth subject
                HttpPrincipal principal = extractBasicAuthSubject(request);

                // authenticate principal and check if the user is in role
                Subject subject = null;
                boolean inRole = true;
                if (principal != null) {
                    subject = authenticate(security.getSecurityAuthenticator(), security.getLoginDeniedLoggingLevel(), principal);
                    if (subject != null) {
                        String userRoles = security.getSecurityAuthenticator().getUserRoles(subject);
                        inRole = matchesRoles(roles, userRoles);
                    }
                }

                if (principal == null || subject == null || !inRole) {
                    if (principal == null) {
                        LOG.debug("Http Basic Auth required for resource: {}", url);
                    } else if (subject == null) {
                        LOG.debug("Http Basic Auth not authorized for username: {}", principal.getUsername());
                    } else {
                        LOG.debug("Http Basic Auth not in role for username: {}", principal.getUsername());
                    }
                    // restricted resource, so send back 401 to require valid username/password
                    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, UNAUTHORIZED);
                    response.headers().set("WWW-Authenticate", "Basic realm=\"" + security.getRealm() + "\"");
                    response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
                    response.headers().set(Exchange.CONTENT_LENGTH, 0);
                    response.setContent(ChannelBuffers.copiedBuffer(new byte[]{}));
                    messageEvent.getChannel().write(response);
                    return;
                } else {
                    LOG.debug("Http Basic Auth authorized for username: {}", principal.getUsername());
                }
View Full Code Here

    private static class TestResponseHandler extends
             SimpleChannelUpstreamHandler {
  @Override
      public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
      throws Exception {
      HttpResponse responce = (HttpResponse) e.getMessage();
      buf.append(responce.getContent().toString(CharsetUtil.UTF_8));
      super.messageReceived(ctx, e);
  }
View Full Code Here

  private static class TestResponseHandler extends
      SimpleChannelUpstreamHandler {
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
        throws Exception {
      HttpResponse responce = (HttpResponse) e.getMessage();
      buf.append(responce.getContent().toString(CharsetUtil.UTF_8));
      super.messageReceived(ctx, e);
    }
View Full Code Here

      }

      public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
        throws Exception {
      HttpRequest request = (HttpRequest) e.getMessage();
      HttpResponse response = null;

      QueryStringDecoder queryStringDecoder = new QueryStringDecoder(
          request.getUri());
      buf.setLength(0);
      if (request.getMethod() == HttpMethod.GET) {
        try {
          String requestResult = CountandraUtils
              .processRequest(request.getUri());

          // buf.append("REQUEST_URI: " + request.getUri() +
          // "\r\n\r\n");
          buf.append(requestResult);
          //System.out.println("Buffer Appended");
          response = new DefaultHttpResponse(HTTP_1_1, OK);
          response.setContent(ChannelBuffers.copiedBuffer(
              buf.toString(), CharsetUtil.UTF_8));
          response.setHeader(CONTENT_TYPE,
              "text/plain; charset=UTF-8");
          // e.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);

        } catch (CountandraException ce) {
          response = new DefaultHttpResponse(HTTP_1_1,
              NOT_IMPLEMENTED);
          System.out.println("CATCH");
        } finally {
          e.getChannel().write(response)
              .addListener(ChannelFutureListener.CLOSE);
        }

      } else if (request.getMethod() == HttpMethod.POST) {
        if (request.getUri().equals(PROCESSINSERT)) {
          // System.out.println("In insert");

          buf.setLength(0);
          buf.append(((HttpRequest) e.getMessage()).getContent()
              .toString(CharsetUtil.UTF_8));
          String postContent = buf.toString();
          // System.out.println(postContent);
          CountandraUtils.processInsertRequest(postContent);
       
          recInsertCount++;
          if ((recInsertCount % CountandraUtils.BATCH_SIZE) == 1) {
              CountandraUtils.finishBatch();
             
              endtimestamp = System.currentTimeMillis();
              System.out.print("It took " );
              System.out.print( endtimestamp - starttimestamp );
              System.out.print(" ms to insert ");
              System.out.print(CountandraUtils.BATCH_SIZE);
              System.out.println("records through http");

              CountandraUtils.startBatch();
          }
          starttimestamp = endtimestamp;
         
         
          // Writing response, wait till it is completely written and
          // close channel after that
          response = new DefaultHttpResponse(HTTP_1_1, OK);
          response.setContent(ChannelBuffers.copiedBuffer("ok",
              CharsetUtil.UTF_8));
          response.setHeader(CONTENT_TYPE,
              "text/plain; charset=UTF-8");
          e.getChannel().write(response)
              .addListener(ChannelFutureListener.CLOSE);
          // System.out.println("sending close  insert");

        } else if (request.getUri().equals(INITCASSANDRADB)) {
          CountandraUtils.initBasicDataStructures();

          response = new DefaultHttpResponse(HTTP_1_1, OK);
          response.setContent(ChannelBuffers.copiedBuffer("ok",
              CharsetUtil.UTF_8));
          response.setHeader(CONTENT_TYPE,
              "text/plain; charset=UTF-8");
          e.getChannel().write(response)
              .addListener(ChannelFutureListener.CLOSE);

        }

        else if (request.getUri().equals(PROCESSINTERNALTEST)) {
          try {
            FileInputStream fstream = new FileInputStream(
                "textfile.txt");

            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(
                new InputStreamReader(in));
            String strLine;

            long starttimestamp = System.currentTimeMillis();
            int recCount = 0;

            while ((strLine = br.readLine()) != null) {
              recCount++;
              CountandraUtils.processInsertRequest(strLine);
            }

            System.out.print("Wrote ");
            System.out.print(recCount);
            System.out.print(" records ");
            System.out.print(" in ");
            System.out
                .print((System.currentTimeMillis() - starttimestamp) / 1000);
            System.out.print(" seconds ");
            response = new DefaultHttpResponse(HTTP_1_1, OK);
            response.setContent(ChannelBuffers.copiedBuffer("ok",
                CharsetUtil.UTF_8));
            response.setHeader(CONTENT_TYPE,
                "text/plain; charset=UTF-8");
            e.getChannel().write(response)
                .addListener(ChannelFutureListener.CLOSE);

          } catch (Exception ex) {// Catch exception if any
View Full Code Here

        // the response code is 200 for OK and 500 for failed
        boolean failed = message.getExchange().isFailed();
        int defaultCode = failed ? 500 : 200;

        int code = message.getHeader(Exchange.HTTP_RESPONSE_CODE, defaultCode, int.class);
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code));
        LOG.trace("HTTP Status Code: {}", code);

        TypeConverter tc = message.getExchange().getContext().getTypeConverter();

        // append headers
        // must use entrySet to ensure case of keys is preserved
        for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            // use an iterator as there can be multiple values. (must not use a delimiter)
            final Iterator<?> it = ObjectHelper.createIterator(value, null);
            while (it.hasNext()) {
                String headerValue = tc.convertTo(String.class, it.next());
                if (headerValue != null && headerFilterStrategy != null
                        && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) {
                    LOG.trace("HTTP-Header: {}={}", key, headerValue);
                    response.addHeader(key, headerValue);
                }
            }
        }

        Object body = message.getBody();
        Exception cause = message.getExchange().getException();
        // support bodies as native Netty
        ChannelBuffer buffer;

        // if there was an exception then use that as body
        if (cause != null) {
            if (configuration.isTransferException()) {
                // we failed due an exception, and transfer it as java serialized object
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos);
                oos.writeObject(cause);
                oos.flush();
                IOHelper.close(oos, bos);

                // the body should be the serialized java object of the exception
                body = ChannelBuffers.copiedBuffer(bos.toByteArray());
                // force content type to be serialized java object
                message.setHeader(Exchange.CONTENT_TYPE, NettyHttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
            } else {
                // we failed due an exception so print it as plain text
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                cause.printStackTrace(pw);

                // the body should then be the stacktrace
                body = ChannelBuffers.copiedBuffer(sw.toString().getBytes());
                // force content type to be text/plain as that is what the stacktrace is
                message.setHeader(Exchange.CONTENT_TYPE, "text/plain");
            }

            // and mark the exception as failure handled, as we handled it by returning it as the response
            ExchangeHelper.setFailureHandled(message.getExchange());
        }

        if (body instanceof ChannelBuffer) {
            buffer = (ChannelBuffer) body;
        } else {
            // try to convert to buffer first
            buffer = message.getBody(ChannelBuffer.class);
            if (buffer == null) {
                // fallback to byte array as last resort
                byte[] data = message.getBody(byte[].class);
                if (data != null) {
                    buffer = ChannelBuffers.copiedBuffer(data);
                } else {
                    // and if byte array fails then try String
                    String str;
                    if (body != null) {
                        str = message.getMandatoryBody(String.class);
                    } else {
                        str = "";
                    }
                    buffer = ChannelBuffers.copiedBuffer(str.getBytes());
                }
            }
        }
        if (buffer != null) {
            response.setContent(buffer);
            // We just need to reset the readerIndex this time
            if (buffer.readerIndex() == buffer.writerIndex()) {
                buffer.setIndex(0, buffer.writerIndex());
            }
            // TODO How to enable the chunk transport
            int len = buffer.readableBytes();
            // set content-length
            response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, len);
            LOG.trace("Content-Length: {}", len);
        }

        // set the content type in the response.
        String contentType = MessageHelper.getContentType(message);
        if (contentType != null) {
            // set content-type
            response.setHeader(HttpHeaders.Names.CONTENT_TYPE, contentType);
            LOG.trace("Content-Type: {}", contentType);
        }

        // configure connection to accordingly to keep alive configuration
        // favor using the header from the message
        String connection = message.getHeader(HttpHeaders.Names.CONNECTION, String.class);
        if (connection == null) {
            // fallback and use the keep alive from the configuration
            if (configuration.isKeepAlive()) {
                connection = HttpHeaders.Values.KEEP_ALIVE;
            } else {
                connection = HttpHeaders.Values.CLOSE;
            }
        }
        response.setHeader(HttpHeaders.Names.CONNECTION, connection);
        LOG.trace("Connection: {}", connection);

        return response;
    }
View Full Code Here

TOP

Related Classes of org.jboss.netty.handler.codec.http.HttpResponse

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.