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

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


  client.setPipelineFactory(new ClientPipelineFactory());

  // Connect to server, wait till connection is established, get channel
  // to write to
  Channel channel;
  HttpRequest request;
  ChannelBuffer buffer;

  channel = client.connect(new InetSocketAddress("127.0.0.1", 8080))
      .awaitUninterruptibly().getChannel();
  request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
           "/init");

  buffer = ChannelBuffers.copiedBuffer(" ", Charset.defaultCharset());
  request.addHeader(
        org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH,
        buffer.readableBytes());
  request.setContent(buffer);
  channel.write(request).awaitUninterruptibly().getChannel()
      .getCloseFuture().awaitUninterruptibly();

  client.releaseExternalResources();
View Full Code Here


    client.releaseExternalResources();
  }

  public static void insertData(String content) {
    Channel channel = null;
    HttpRequest request;
    ChannelBuffer buffer;
    try {
      channel = client
          .connect(new InetSocketAddress("localhost", httpPort))
          .awaitUninterruptibly().getChannel();
      request = new DefaultHttpRequest(HttpVersion.HTTP_1_1,
          HttpMethod.POST, "/insert");
      buffer = ChannelBuffers.copiedBuffer(content,
          Charset.defaultCharset());
      request.addHeader(
          org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH,
          buffer.readableBytes());
      request.setContent(buffer);
      channel.write(request).awaitUninterruptibly().getChannel()
          .getCloseFuture().awaitUninterruptibly();

    } catch (Exception e) {// Catch exception if any
      System.err.println("Error: " + e.getMessage());
View Full Code Here

    CountandraUtils.startBatch();
      }

      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);
View Full Code Here

        if (message.getBody() instanceof HttpRequest) {
            return (HttpRequest) message.getBody();
        }

        // just assume GET for now, we will later change that to the actual method to use
        HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri);

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

        // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
        // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
        Map<String, Object> skipRequestHeaders = null;
        if (configuration.isBridgeEndpoint()) {
            String queryString = message.getHeader(Exchange.HTTP_QUERY, String.class);
            if (queryString != null) {
                skipRequestHeaders = URISupport.parseQuery(queryString);
            }
            // Need to remove the Host key as it should be not used
            message.getHeaders().remove("host");
        }

        // 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();

            // we should not add headers for the parameters in the uri if we bridge the endpoint
            // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
            if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
                continue;
            }

            // use an iterator as there can be multiple values. (must not use a delimiter)
            final Iterator<?> it = ObjectHelper.createIterator(value, null, true);
            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);
                    request.addHeader(key, headerValue);
                }
            }
        }

        Object body = message.getBody();
        if (body != null) {
            // support bodies as native Netty
            ChannelBuffer buffer;
            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.getMandatoryBody(byte[].class);
                    buffer = ChannelBuffers.copiedBuffer(data);
                }
            }
            if (buffer != null) {
                request.setContent(buffer);
                int len = buffer.readableBytes();
                // set content-length
                request.setHeader(HttpHeaders.Names.CONTENT_LENGTH, len);
                LOG.trace("Content-Length: {}", len);
            } else {
                // we do not support this kind of body
                throw new NoTypeConversionAvailableException(body, ChannelBuffer.class);
            }
        }

        // update HTTP method accordingly as we know if we have a body or not
        HttpMethod method = NettyHttpHelper.createMethod(message, body != null);
        request.setMethod(method);

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

        // must include HOST header as required by HTTP 1.1
        // use URI as its faster than URL (no DNS lookup)
        URI u = new URI(uri);
        String host = u.getHost();
        request.setHeader(HttpHeaders.Names.HOST, host);
        LOG.trace("Host: {}", host);

        // 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;
            }
        }
        request.setHeader(HttpHeaders.Names.CONNECTION, connection);
        LOG.trace("Connection: {}", connection);

        return request;
    }
View Full Code Here

    @Override
    public Exchange createExchange(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
        Exchange exchange = createExchange();

        // use the http binding
        HttpRequest request = (HttpRequest) messageEvent.getMessage();
        Message in = getNettyHttpBinding().toCamelMessage(request, exchange, getConfiguration());
        exchange.setIn(in);
       
        // setup the common message headers
        updateMessageHeader(in, ctx, messageEvent);
View Full Code Here

        if (message.getBody() instanceof HttpRequest) {
            return (HttpRequest) message.getBody();
        }

        // just assume GET for now, we will later change that to the actual method to use
        HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri);

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

        // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
        // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
        Map<String, Object> skipRequestHeaders = null;
        if (configuration.isBridgeEndpoint()) {
            String queryString = message.getHeader(Exchange.HTTP_QUERY, String.class);
            if (queryString != null) {
                skipRequestHeaders = URISupport.parseQuery(queryString);
            }
            // Need to remove the Host key as it should be not used
            message.getHeaders().remove("host");
        }

        // 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();

            // we should not add headers for the parameters in the uri if we bridge the endpoint
            // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
            if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
                continue;
            }

            // use an iterator as there can be multiple values. (must not use a delimiter)
            final Iterator<?> it = ObjectHelper.createIterator(value, null, true);
            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);
                    request.addHeader(key, headerValue);
                }
            }
        }

        Object body = message.getBody();
        if (body != null) {
            // support bodies as native Netty
            ChannelBuffer buffer;
            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.getMandatoryBody(byte[].class);
                    buffer = ChannelBuffers.copiedBuffer(data);
                }
            }
            if (buffer != null) {
                request.setContent(buffer);
                int len = buffer.readableBytes();
                // set content-length
                request.setHeader(HttpHeaders.Names.CONTENT_LENGTH, len);
                LOG.trace("Content-Length: {}", len);
            } else {
                // we do not support this kind of body
                throw new NoTypeConversionAvailableException(body, ChannelBuffer.class);
            }
        }

        // update HTTP method accordingly as we know if we have a body or not
        HttpMethod method = NettyHttpHelper.createMethod(message, body != null);
        request.setMethod(method);

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

        // must include HOST header as required by HTTP 1.1
        // use URI as its faster than URL (no DNS lookup)
        URI u = new URI(uri);
        String host = u.getHost();
        request.setHeader(HttpHeaders.Names.HOST, host);
        LOG.trace("Host: {}", host);

        // 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;
            }
        }
        request.setHeader(HttpHeaders.Names.CONNECTION, connection);
        LOG.trace("Connection: {}", connection);

        return request;
    }
View Full Code Here

    @Override
    public Exchange createExchange(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
        Exchange exchange = createExchange();

        // use the http binding
        HttpRequest request = (HttpRequest) messageEvent.getMessage();
        Message in = getNettyHttpBinding().toCamelMessage(request, exchange, getConfiguration());
        exchange.setIn(in);
       
        // setup the common message headers
        updateMessageHeader(in, ctx, messageEvent);
View Full Code Here

    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
        // store request, as this channel handler is created per pipeline
        HttpRequest request = (HttpRequest) messageEvent.getMessage();

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

        HttpServerChannelHandler handler = getHandler(request);
        if (handler != null) {
View Full Code Here

            } else {
                msg = exchange.getIn(NettyHttpMessage.class);
            }
            if (msg != null && msg.getBody() == value) {
                // ensure the http request content is reset so we can read all the content out-of-the-box
                HttpRequest request = msg.getHttpRequest();
                request.getContent().resetReaderIndex();
                return request;
            }
        }

        return null;
View Full Code Here

    @Override
    public Exchange createExchange(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
        Exchange exchange = createExchange();

        // use the http binding
        HttpRequest request = (HttpRequest) messageEvent.getMessage();
        Message in = getNettyHttpBinding().toCamelMessage(request, exchange, getConfiguration());
        exchange.setIn(in);
       
        // setup the common message headers
        updateMessageHeader(in, ctx, messageEvent);
View Full Code Here

TOP

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

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.