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.flink.runtime.webmonitor.HttpRequestHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    try {/*from   w ww  .ja  v  a2  s.c  o m*/
        if (msg instanceof HttpRequest) {
            currentRequest = (HttpRequest) msg;
            currentRequestPath = null;

            if (currentDecoder != null) {
                currentDecoder.destroy();
                currentDecoder = null;
            }

            if (currentRequest.getMethod() == HttpMethod.GET
                    || currentRequest.getMethod() == HttpMethod.DELETE) {
                // directly delegate to the router
                ctx.fireChannelRead(currentRequest);
            } else if (currentRequest.getMethod() == HttpMethod.POST) {
                // POST comes in multiple objects. First the request, then the contents
                // keep the request and path for the remaining objects of the POST request
                currentRequestPath = new QueryStringDecoder(currentRequest.getUri()).path();
                currentDecoder = new HttpPostRequestDecoder(DATA_FACTORY, currentRequest);
            } else {
                throw new IOException("Unsupported HTTP method: " + currentRequest.getMethod().name());
            }
        } else if (currentDecoder != null && msg instanceof HttpContent) {
            // received new chunk, give it to the current decoder
            HttpContent chunk = (HttpContent) msg;
            currentDecoder.offer(chunk);

            try {
                while (currentDecoder.hasNext()) {
                    InterfaceHttpData data = currentDecoder.next();

                    // IF SOMETHING EVER NEEDS POST PARAMETERS, THIS WILL BE THE PLACE TO HANDLE IT
                    // all fields values will be passed with type Attribute.

                    if (data.getHttpDataType() == HttpDataType.FileUpload) {
                        DiskFileUpload file = (DiskFileUpload) data;
                        if (file.isCompleted()) {
                            String name = file.getFilename();

                            File target = new File(tmpDir, UUID.randomUUID() + "_" + name);
                            file.renameTo(target);

                            QueryStringEncoder encoder = new QueryStringEncoder(currentRequestPath);
                            encoder.addParam("filepath", target.getAbsolutePath());
                            encoder.addParam("filename", name);

                            currentRequest.setUri(encoder.toString());
                        }
                    }

                    data.release();
                }
            } catch (EndOfDataDecoderException ignored) {
            }

            if (chunk instanceof LastHttpContent) {
                HttpRequest request = currentRequest;
                currentRequest = null;
                currentRequestPath = null;

                currentDecoder.destroy();
                currentDecoder = null;

                // fire next channel handler
                ctx.fireChannelRead(request);
            }
        }
    } catch (Throwable t) {
        currentRequest = null;
        currentRequestPath = null;

        if (currentDecoder != null) {
            currentDecoder.destroy();
            currentDecoder = null;
        }

        if (ctx.channel().isActive()) {
            byte[] bytes = ExceptionUtils.stringifyException(t).getBytes(ENCODING);

            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(bytes));

            response.headers().set(HttpHeaders.Names.CONTENT_ENCODING, "utf-8");
            response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());

            ctx.writeAndFlush(response);
        }
    }
}

From source file:org.apache.flink.runtime.webmonitor.testutils.HttpTestClient.java

License:Apache License

/**
 * Sends a simple GET request to the given path. You only specify the $path part of
 * http://$host:$host/$path.//  w  ww. j  a v  a2  s.  co  m
 *
 * @param path The $path to GET (http://$host:$host/$path)
 */
public void sendGetRequest(String path, FiniteDuration timeout) throws TimeoutException, InterruptedException {
    if (!path.startsWith("/")) {
        path = "/" + path;
    }

    HttpRequest getRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
    getRequest.headers().set(HttpHeaders.Names.HOST, host);
    getRequest.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);

    sendRequest(getRequest, timeout);
}

From source file:org.apache.hadoop.hdfs.server.datanode.web.dtp.TestDtpHttp2.java

License:Apache License

@Test
public void test() throws InterruptedException, ExecutionException {
    int streamId = 3;
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    request.headers().add(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), streamId);
    Promise<FullHttpResponse> promise = CHANNEL.eventLoop().newPromise();
    synchronized (RESPONSE_HANDLER) {
        CHANNEL.writeAndFlush(request);// www  .  jav  a2s . co  m
        RESPONSE_HANDLER.put(streamId, promise);
    }
    assertEquals(HttpResponseStatus.OK, promise.get().status());
    ByteBuf content = promise.get().content();
    assertEquals("HTTP/2 DTP", content.toString(StandardCharsets.UTF_8));
}

From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.FSImageHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpRequest request) throws Exception {
    if (request.method() != HttpMethod.GET) {
        DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED);
        resp.headers().set(CONNECTION, CLOSE);
        ctx.write(resp).addListener(ChannelFutureListener.CLOSE);
        return;//from  w w w  . j a  v a  2s . c o m
    }

    QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
    final String op = getOp(decoder);

    final String content;
    String path = getPath(decoder);
    switch (op) {
    case "GETFILESTATUS":
        content = image.getFileStatus(path);
        break;
    case "LISTSTATUS":
        content = image.listStatus(path);
        break;
    case "GETACLSTATUS":
        content = image.getAclStatus(path);
        break;
    case "GETXATTRS":
        List<String> names = getXattrNames(decoder);
        String encoder = getEncoder(decoder);
        content = image.getXAttrs(path, names, encoder);
        break;
    case "LISTXATTRS":
        content = image.listXAttrs(path);
        break;
    default:
        throw new IllegalArgumentException("Invalid value for webhdfs parameter" + " \"op\"");
    }

    LOG.info("op=" + op + " target=" + path);

    DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.wrappedBuffer(content.getBytes(Charsets.UTF_8)));
    resp.headers().set(CONTENT_TYPE, APPLICATION_JSON_UTF8);
    resp.headers().set(CONTENT_LENGTH, resp.content().readableBytes());
    resp.headers().set(CONNECTION, CLOSE);
    ctx.write(resp).addListener(ChannelFutureListener.CLOSE);
}

From source file:org.apache.hyracks.control.cc.web.ApplicationInstallationHandler.java

License:Apache License

@Override
public void handle(IServletRequest request, IServletResponse response) {
    String localPath = localPath(request);
    while (localPath.startsWith("/")) {
        localPath = localPath.substring(1);
    }//  www. j  a  v  a  2  s .  com
    final String[] params = localPath.split("&");
    if (params.length != 2 || params[0].isEmpty() || params[1].isEmpty()) {
        response.setStatus(HttpResponseStatus.BAD_REQUEST);
        return;
    }
    final String deployIdString = params[0];
    final String fileName = params[1];
    final String rootDir = ccs.getServerContext().getBaseDir().toString();

    final String deploymentDir = rootDir.endsWith(File.separator) ? rootDir + "applications/" + deployIdString
            : rootDir + File.separator + "/applications/" + File.separator + deployIdString;
    final HttpMethod method = request.getHttpRequest().method();
    try {
        response.setStatus(HttpResponseStatus.OK);
        if (method == HttpMethod.PUT) {
            final ByteBuf content = request.getHttpRequest().content();
            writeToFile(content, deploymentDir, fileName);
        } else if (method == HttpMethod.GET) {
            readFromFile(fileName, deploymentDir, response);
        } else {
            response.setStatus(HttpResponseStatus.METHOD_NOT_ALLOWED);
        }
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Unhandled exception ", e);
        response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.apache.hyracks.http.server.AbstractServlet.java

License:Apache License

@Override
public void handle(IServletRequest request, IServletResponse response) {
    try {/*  ww w  .  j a  va 2 s  .co m*/
        final HttpMethod method = request.getHttpRequest().method();
        if (HttpMethod.GET.equals(method)) {
            get(request, response);
        } else if (HttpMethod.HEAD.equals(method)) {
            head(request, response);
        } else if (HttpMethod.POST.equals(method)) {
            post(request, response);
        } else if (HttpMethod.PUT.equals(method)) {
            put(request, response);
        } else if (HttpMethod.DELETE.equals(method)) {
            delete(request, response);
        } else if (HttpMethod.OPTIONS.equals(method)) {
            options(request, response);
        } else {
            notAllowed(method, response);
        }
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Unhandled exception", e);
        response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
    } catch (Throwable th) { //NOSONAR Just logging and then throwing again
        try {
            LOGGER.log(Level.WARNING, "Unhandled throwable", th);
        } catch (Throwable loggingFailure) {// NOSONAR... swallow logging failure
        }
        throw th;
    }
}

From source file:org.apache.hyracks.http.server.AbstractServlet.java

License:Apache License

@SuppressWarnings("squid:S1172")
protected void get(IServletRequest request, IServletResponse response) throws Exception {
    // designed to be extended but an error in standard case
    notAllowed(HttpMethod.GET, response);
}

From source file:org.apache.hyracks.http.server.util.ServletUtils.java

License:Apache License

public static IServletRequest toServletRequest(FullHttpRequest request) throws IOException {
    return request.method() == HttpMethod.GET ? ServletUtils.get(request) : ServletUtils.post(request);
}

From source file:org.apache.tajo.HttpFileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

    if (request.getMethod() != HttpMethod.GET) {
        sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
        return;//from  w  w w  .j  a  v  a2s. c  o m
    }

    final 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);
    HttpHeaders.setContentLength(response, fileLength);
    setContentTypeHeader(response);

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

    // Write the content.
    ChannelFuture writeFuture;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) != null) {
        // Cannot use zero-copy with HTTPS.
        lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)));
    } else {
        // No encryption - use zero-copy.
        final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength);
        writeFuture = ctx.write(region);
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        writeFuture.addListener(new ChannelProgressiveFutureListener() {
            @Override
            public void operationProgressed(ChannelProgressiveFuture future, long progress, long total)
                    throws Exception {
                LOG.trace(String.format("%s: %d / %d", path, progress, total));
            }

            @Override
            public void operationComplete(ChannelProgressiveFuture future) throws Exception {
                region.release();
            }
        });
    }

    // Decide whether to close the connection or not.
    if (!HttpHeaders.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:org.apache.tajo.pullserver.HttpDataServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

    if (request.getMethod() != HttpMethod.GET) {
        sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
        return;//from  w w w  .  ja  v  a 2  s . co  m
    }

    String base = ContainerLocalizer.USERCACHE + "/" + userName + "/" + ContainerLocalizer.APPCACHE + "/"
            + appId + "/output" + "/";

    final Map<String, List<String>> params = new QueryStringDecoder(request.getUri()).parameters();

    List<FileChunk> chunks = Lists.newArrayList();
    List<String> taskIds = splitMaps(params.get("ta"));
    int sid = Integer.valueOf(params.get("sid").get(0));
    int partitionId = Integer.valueOf(params.get("p").get(0));
    for (String ta : taskIds) {

        File file = new File(base + "/" + sid + "/" + ta + "/output/" + partitionId);
        FileChunk chunk = new FileChunk(file, 0, file.length());
        chunks.add(chunk);
    }

    FileChunk[] file = chunks.toArray(new FileChunk[chunks.size()]);

    // Write the content.
    if (file == null) {
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT);
        if (!HttpHeaders.isKeepAlive(request)) {
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
            ctx.writeAndFlush(response);
        }
    } else {
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        ChannelFuture writeFuture = null;
        long totalSize = 0;
        for (FileChunk chunk : file) {
            totalSize += chunk.length();
        }
        HttpHeaders.setContentLength(response, totalSize);

        if (HttpHeaders.isKeepAlive(request)) {
            response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        }
        // Write the initial line and the header.
        writeFuture = ctx.write(response);

        for (FileChunk chunk : file) {
            writeFuture = sendFile(ctx, chunk);
            if (writeFuture == null) {
                sendError(ctx, HttpResponseStatus.NOT_FOUND);
                return;
            }
        }
        if (ctx.pipeline().get(SslHandler.class) == null) {
            writeFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        } else {
            ctx.flush();
        }

        // Decide whether to close the connection or not.
        if (!HttpHeaders.isKeepAlive(request)) {
            // Close the connection when the whole content is written out.
            writeFuture.addListener(ChannelFutureListener.CLOSE);
        }
    }

}