Example usage for io.netty.handler.codec.http HttpMethod GET

List of usage examples for io.netty.handler.codec.http HttpMethod GET

Introduction

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

Prototype

HttpMethod GET

To view the source code for io.netty.handler.codec.http HttpMethod GET.

Click Source Link

Document

The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI.

Usage

From source file:org.apache.activemq.jms.example.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
    HttpRequest request = (HttpRequest) e.getMessage();
    if (request.getMethod() != HttpMethod.GET) {
        sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
        return;//from  ww w  .ja  v a2 s  .  co m
    }

    if (request.isChunked()) {
        sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        return;
    }

    String path = sanitizeUri(request.getUri());
    if (path == null) {
        sendError(ctx, HttpResponseStatus.FORBIDDEN);
        return;
    }

    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, HttpResponseStatus.NOT_FOUND);
        return;
    }
    if (!file.isFile()) {
        sendError(ctx, HttpResponseStatus.FORBIDDEN);
        return;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, HttpResponseStatus.NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(fileLength));

    Channel ch = e.getChannel();

    // Write the initial line and the header.
    ch.write(response);

    // Write the content.
    ChannelFuture writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));

    // Decide whether to close the connection or not.
    boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.getHeader(HttpHeaders.Names.CONNECTION))
            || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE
                    .equalsIgnoreCase(request.getHeader(HttpHeaders.Names.CONNECTION));

    if (close) {
        // Close the connection when the whole content is written out.
        writeFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:org.apache.activemq.test.WebServerComponentTest.java

License:Apache License

@Test
public void simpleServer() throws Exception {
    WebServerDTO webServerDTO = new WebServerDTO();
    webServerDTO.bind = "http://localhost:8161";
    webServerDTO.path = "webapps";
    WebServerComponent webServerComponent = new WebServerComponent();
    webServerComponent.configure(webServerDTO, "./src/test/resources/");
    webServerComponent.start();/* w  w  w  . j  a  v  a  2 s. c o  m*/
    // Make the connection attempt.
    CountDownLatch latch = new CountDownLatch(1);
    final ClientHandler clientHandler = new ClientHandler(latch);
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new HttpClientCodec());
            ch.pipeline().addLast(clientHandler);
        }
    });
    Channel ch = bootstrap.connect("localhost", 8161).sync().channel();

    URI uri = new URI(URL);
    // Prepare the HTTP request.
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
    request.headers().set(HttpHeaders.Names.HOST, "localhost");

    // Send the HTTP request.
    ch.writeAndFlush(request);
    assertTrue(latch.await(5, TimeUnit.SECONDS));
    assertEquals(clientHandler.body, "12345");
    // Wait for the server to close the connection.
    ch.close();
    webServerComponent.stop();
}

From source file:org.apache.asterix.api.http.servlet.ConnectorApiServletTest.java

License:Apache License

@Test
public void testGet() throws Exception {
    // Configures a test connector api servlet.
    ConnectorApiServlet let = new ConnectorApiServlet(new ConcurrentHashMap<>(), new String[] { "/" },
            (ICcApplicationContext) ExecutionTestUtil.integrationUtil.cc.getApplicationContext());
    Map<String, NodeControllerInfo> nodeMap = new HashMap<>();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PrintWriter outputWriter = new PrintWriter(outputStream);

    // Creates mocks.
    IHyracksClientConnection mockHcc = mock(IHyracksClientConnection.class);
    NodeControllerInfo mockInfo1 = mock(NodeControllerInfo.class);
    NodeControllerInfo mockInfo2 = mock(NodeControllerInfo.class);
    IServletRequest mockRequest = mock(IServletRequest.class);
    IServletResponse mockResponse = mock(IServletResponse.class);
    FullHttpRequest mockHttpRequest = mock(FullHttpRequest.class);

    // Put stuff in let map
    let.ctx().put(ServletConstants.HYRACKS_CONNECTION_ATTR, mockHcc);
    // Sets up mock returns.
    when(mockRequest.getHttpRequest()).thenReturn(mockHttpRequest);
    when(mockHttpRequest.method()).thenReturn(HttpMethod.GET);
    when(mockRequest.getParameter("dataverseName")).thenReturn("Metadata");
    when(mockRequest.getParameter("datasetName")).thenReturn("Dataset");
    when(mockResponse.writer()).thenReturn(outputWriter);
    when(mockHcc.getNodeControllerInfos()).thenReturn(nodeMap);
    when(mockInfo1.getNetworkAddress()).thenReturn(new NetworkAddress("127.0.0.1", 3099));
    when(mockInfo2.getNetworkAddress()).thenReturn(new NetworkAddress("127.0.0.2", 3099));

    // Calls ConnectorAPIServlet.formResponseObject.
    nodeMap.put("asterix_nc1", mockInfo1);
    nodeMap.put("asterix_nc2", mockInfo2);
    let.handle(mockRequest, mockResponse);

    // Constructs the actual response.
    ObjectMapper om = new ObjectMapper();
    ObjectNode actualResponse = (ObjectNode) om.readTree(outputStream.toString());

    // Checks the primary key, data type of the dataset.
    String primaryKey = actualResponse.get("keys").asText();
    Assert.assertEquals("DataverseName,DatasetName", primaryKey);
    ARecordType recordType = (ARecordType) JSONDeserializerForTypes.convertFromJSON(actualResponse.get("type"));
    Assert.assertEquals(getMetadataRecordType("Metadata", "Dataset"), recordType);

    // Checks the correctness of results.
    ArrayNode splits = (ArrayNode) actualResponse.get("splits");
    String path = (splits.get(0)).get("path").asText();
    Assert.assertTrue(path.endsWith("Metadata/Dataset/0/Dataset"));
}

From source file:org.apache.asterix.api.http.servlet.VersionApiServletTest.java

License:Apache License

@Test
public void testGet() throws Exception {
    // Configures a test version api servlet.
    VersionApiServlet servlet = new VersionApiServlet(new ConcurrentHashMap<>(), new String[] { "/" });
    Map<String, String> propMap = new HashMap<>();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PrintWriter outputWriter = new PrintWriter(outputStream);

    // Creates mocks.
    CcApplicationContext mockCtx = mock(CcApplicationContext.class);
    IServletRequest mockRequest = mock(IServletRequest.class);
    IHyracksClientConnection mockHcc = mock(IHyracksClientConnection.class);
    IServletResponse mockResponse = mock(IServletResponse.class);
    BuildProperties mockProperties = mock(BuildProperties.class);
    FullHttpRequest mockHttpRequest = mock(FullHttpRequest.class);

    // Put stuff in let map
    servlet.ctx().put(HYRACKS_CONNECTION_ATTR, mockHcc);
    servlet.ctx().put(ASTERIX_APP_CONTEXT_INFO_ATTR, mockCtx);
    // Sets up mock returns.
    when(mockResponse.writer()).thenReturn(outputWriter);
    when(mockRequest.getHttpRequest()).thenReturn(mockHttpRequest);
    when(mockHttpRequest.method()).thenReturn(HttpMethod.GET);
    when(mockCtx.getBuildProperties()).thenReturn(mockProperties);
    when(mockProperties.getAllProps()).thenReturn(propMap);

    propMap.put("git.build.user.email", "foo@bar.baz");
    propMap.put("git.build.host", "fulliautomatix");
    propMap.put("git.dirty", "true");
    propMap.put("git.remote.origin.url", "git@github.com:apache/incubator-asterixdb.git");
    propMap.put("git.closest.tag.name", "asterix-0.8.7-incubating");
    propMap.put("git.commit.id.describe-short", "asterix-0.8.7-incubating-19-dirty");
    propMap.put("git.commit.user.email", "foo@bar.baz");
    propMap.put("git.commit.time", "21.10.2015 @ 23:36:41 PDT");
    propMap.put("git.commit.message.full",
            "ASTERIXDB-1045: fix log file reading during recovery\n\nChange-Id: Ic83ee1dd2d7ba88180c25f4ec6c7aa8d0a5a7162\nReviewed-on: https://asterix-gerrit.ics.uci.edu/465\nTested-by: Jenkins <jenkins@fulliautomatix.ics.uci.edu>");
    propMap.put("git.build.version", "0.8.8-SNAPSHOT");
    propMap.put("git.commit.message.short", "ASTERIXDB-1045: fix log file reading during recovery");
    propMap.put("git.commit.id.abbrev", "e1dad19");
    propMap.put("git.branch", "foo/bar");
    propMap.put("git.build.user.name", "Asterix");
    propMap.put("git.closest.tag.commit.count", "19");
    propMap.put("git.commit.id.describe", "asterix-0.8.7-incubating-19-ge1dad19-dirty");
    propMap.put("git.commit.id", "e1dad1984640517366a7e73e323c9de27b0676f7");
    propMap.put("git.tags", "");
    propMap.put("git.build.time", "22.10.2015 @ 17:11:07 PDT");
    propMap.put("git.commit.user.name", "Obelix");

    // Calls VersionAPIServlet.formResponseObject.
    servlet.handle(mockRequest, mockResponse);

    // Constructs the actual response.

    ObjectMapper om = new ObjectMapper();
    ObjectNode actualResponse = (ObjectNode) om.readTree(outputStream.toByteArray());
    ObjectNode expectedResponse = om.createObjectNode();
    for (Map.Entry<String, String> e : propMap.entrySet()) {
        expectedResponse.put(e.getKey(), e.getValue());
    }/*  w  ww  .j a  va 2s  .  c  om*/

    // Checks the response contains all the expected keys.
    Assert.assertEquals(actualResponse.toString(), expectedResponse.toString());
}

From source file:org.apache.camel.component.netty4.http.DefaultNettyHttpBinding.java

License:Apache License

@Override
public HttpRequest toNettyRequest(Message message, String uri, NettyHttpConfiguration configuration)
        throws Exception {
    LOG.trace("toNettyRequest: {}", message);

    // the message body may already be a Netty HTTP response
    if (message.getBody() instanceof HttpRequest) {
        return (HttpRequest) message.getBody();
    }//  w w  w.j av a 2 s. c  o m

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

    Object body = message.getBody();
    if (body != null) {
        // support bodies as native Netty
        ByteBuf buffer;
        if (body instanceof ByteBuf) {
            buffer = (ByteBuf) body;
        } else {
            // try to convert to buffer first
            buffer = message.getBody(ByteBuf.class);
            if (buffer == null) {
                // fallback to byte array as last resort
                byte[] data = message.getMandatoryBody(byte[].class);
                buffer = NettyConverter.toByteBuffer(data);
            }
        }
        if (buffer != null) {
            request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri, buffer);
            int len = buffer.readableBytes();
            // set content-length
            request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, len);
            LOG.trace("Content-Length: {}", len);
        } else {
            // we do not support this kind of body
            throw new NoTypeConversionAvailableException(body, ByteBuf.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);

    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, false, true);
        }
        // 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.headers().add(key, headerValue);
            }
        }
    }

    // set the content type in the response.
    String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        request.headers().set(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.headers().set(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.headers().set(HttpHeaders.Names.CONNECTION, connection);
    LOG.trace("Connection: {}", connection);

    return request;
}

From source file:org.apache.camel.component.netty4.http.NettyHttpHelper.java

License:Apache License

/**
 * Creates the {@link HttpMethod} to use to call the remote server, often either its GET or POST.
 *
 * @param message  the Camel message//from ww  w . j a va2  s. co m
 * @return the created method
 */
public static HttpMethod createMethod(Message message, boolean hasPayload) {
    // use header first
    HttpMethod m = message.getHeader(Exchange.HTTP_METHOD, HttpMethod.class);
    if (m != null) {
        return m;
    }
    String name = message.getHeader(Exchange.HTTP_METHOD, String.class);
    if (name != null) {
        return HttpMethod.valueOf(name);
    }

    if (hasPayload) {
        // use POST if we have payload
        return HttpMethod.POST;
    } else {
        // fallback to GET
        return HttpMethod.GET;
    }
}

From source file:org.apache.dubbo.qos.command.decoder.HttpCommandDecoderTest.java

License:Apache License

@Test
public void decodeGet() throws Exception {
    HttpRequest request = mock(HttpRequest.class);
    when(request.getUri()).thenReturn("localhost:80/test");
    when(request.getMethod()).thenReturn(HttpMethod.GET);
    CommandContext context = HttpCommandDecoder.decode(request);
    assertThat(context.getCommandName(), equalTo("test"));
    assertThat(context.isHttp(), is(true));
    when(request.getUri()).thenReturn("localhost:80/test?a=b&c=d");
    context = HttpCommandDecoder.decode(request);
    assertThat(context.getArgs(), arrayContaining("b", "d"));
}

From source file:org.apache.dubbo.qos.server.handler.HttpProcessHandlerTest.java

License:Apache License

@Test
public void test2() throws Exception {
    ChannelHandlerContext context = mock(ChannelHandlerContext.class);
    ChannelFuture future = mock(ChannelFuture.class);
    when(context.writeAndFlush(any(FullHttpResponse.class))).thenReturn(future);
    HttpRequest message = Mockito.mock(HttpRequest.class);
    when(message.getUri()).thenReturn("localhost:80/greeting");
    when(message.getMethod()).thenReturn(HttpMethod.GET);
    HttpProcessHandler handler = new HttpProcessHandler();
    handler.channelRead0(context, message);
    verify(future).addListener(ChannelFutureListener.CLOSE);
    ArgumentCaptor<FullHttpResponse> captor = ArgumentCaptor.forClass(FullHttpResponse.class);
    verify(context).writeAndFlush(captor.capture());
    FullHttpResponse response = captor.getValue();
    assertThat(response.getStatus().code(), equalTo(200));
}

From source file:org.apache.dubbo.qos.server.handler.HttpProcessHandlerTest.java

License:Apache License

@Test
public void test3() throws Exception {
    ChannelHandlerContext context = mock(ChannelHandlerContext.class);
    ChannelFuture future = mock(ChannelFuture.class);
    when(context.writeAndFlush(any(FullHttpResponse.class))).thenReturn(future);
    HttpRequest message = Mockito.mock(HttpRequest.class);
    when(message.getUri()).thenReturn("localhost:80/test");
    when(message.getMethod()).thenReturn(HttpMethod.GET);
    HttpProcessHandler handler = new HttpProcessHandler();
    handler.channelRead0(context, message);
    verify(future).addListener(ChannelFutureListener.CLOSE);
    ArgumentCaptor<FullHttpResponse> captor = ArgumentCaptor.forClass(FullHttpResponse.class);
    verify(context).writeAndFlush(captor.capture());
    FullHttpResponse response = captor.getValue();
    assertThat(response.getStatus().code(), equalTo(404));
}

From source file:org.apache.flink.runtime.webmonitor.handlers.TaskManagerLogHandlerTest.java

License:Apache License

@Test
public void testLogFetchingFailure() throws Exception {
    // ========= setup TaskManager =================================================================================
    InstanceID tmID = new InstanceID();
    ResourceID tmRID = new ResourceID(tmID.toString());
    TaskManagerGateway taskManagerGateway = mock(TaskManagerGateway.class);
    when(taskManagerGateway.getAddress()).thenReturn("/tm/address");

    Instance taskManager = mock(Instance.class);
    when(taskManager.getId()).thenReturn(tmID);
    when(taskManager.getTaskManagerID()).thenReturn(tmRID);
    when(taskManager.getTaskManagerGateway()).thenReturn(taskManagerGateway);
    CompletableFuture<BlobKey> future = new FlinkCompletableFuture<>();
    future.completeExceptionally(new IOException("failure"));
    when(taskManagerGateway.requestTaskManagerLog(any(Time.class))).thenReturn(future);

    // ========= setup JobManager ==================================================================================

    ActorGateway jobManagerGateway = mock(ActorGateway.class);
    Object registeredTaskManagersAnswer = new JobManagerMessages.RegisteredTaskManagers(JavaConverters
            .collectionAsScalaIterableConverter(Collections.singletonList(taskManager)).asScala());

    when(jobManagerGateway.ask(isA(JobManagerMessages.RequestRegisteredTaskManagers$.class),
            any(FiniteDuration.class))).thenReturn(Future$.MODULE$.successful(registeredTaskManagersAnswer));
    when(jobManagerGateway.ask(isA(JobManagerMessages.getRequestBlobManagerPort().getClass()),
            any(FiniteDuration.class))).thenReturn(Future$.MODULE$.successful((Object) 5));
    when(jobManagerGateway.ask(isA(JobManagerMessages.RequestTaskManagerInstance.class),
            any(FiniteDuration.class)))
                    .thenReturn(Future$.MODULE$.successful(
                            (Object) new JobManagerMessages.TaskManagerInstance(Option.apply(taskManager))));
    when(jobManagerGateway.path()).thenReturn("/jm/address");

    JobManagerRetriever retriever = mock(JobManagerRetriever.class);
    when(retriever.getJobManagerGatewayAndWebPort())
            .thenReturn(Option.apply(new scala.Tuple2<ActorGateway, Integer>(jobManagerGateway, 0)));

    TaskManagerLogHandler handler = new TaskManagerLogHandler(retriever,
            ExecutionContext$.MODULE$.fromExecutor(Executors.directExecutor()),
            Future$.MODULE$.successful("/jm/address"), AkkaUtils.getDefaultClientTimeout(),
            TaskManagerLogHandler.FileMode.LOG, new Configuration(), false);

    final AtomicReference<String> exception = new AtomicReference<>();

    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.write(isA(ByteBuf.class))).thenAnswer(new Answer<Object>() {
        @Override//from  w w w  .  j  av a  2 s .c om
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ByteBuf data = invocationOnMock.getArgumentAt(0, ByteBuf.class);
            exception.set(new String(data.array(), ConfigConstants.DEFAULT_CHARSET));
            return null;
        }
    });

    Map<String, String> pathParams = new HashMap<>();
    pathParams.put(TaskManagersHandler.TASK_MANAGER_ID_KEY, tmID.toString());
    Routed routed = mock(Routed.class);
    when(routed.pathParams()).thenReturn(pathParams);
    when(routed.request()).thenReturn(
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/taskmanagers/" + tmID + "/log"));

    handler.respondAsLeader(ctx, routed, jobManagerGateway);

    Assert.assertEquals("Fetching TaskManager log failed.", exception.get());
}