Example usage for io.netty.handler.codec.http HttpRequest getUri

List of usage examples for io.netty.handler.codec.http HttpRequest getUri

Introduction

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

Prototype

@Deprecated
String getUri();

Source Link

Usage

From source file:io.urmia.md.model.ObjectRequest.java

License:Open Source License

public ObjectRequest(HttpRequest httpRequest) throws ExceptionInInitializerError {

    final URI uri;
    try {/* w ww  .ja  v a2  s .c  o m*/
        uri = new URI(httpRequest.getUri());
    } catch (URISyntaxException e) {
        throw new ExceptionInInitializerError(e);
    }

    Optional<ObjectName> oon = ObjectName.of(uri);

    if (!oon.isPresent())
        throw new ExceptionInInitializerError("object name invalid: " + httpRequest.getUri());

    objectName = oon.get();

    HttpHeaders headers = httpRequest.headers();

    this.typeDirectory = isDirectory(headers);
    this.durability = getDurability(headers);
    this.typeLink = isLink(headers);
    this.location = getLinkLocation(headers);

    Map<String, String> params = StringUtils.isBlank(uri.getQuery()) ? Collections.<String, String>emptyMap()
            : HTTP_PARAM_SPLIT.split(uri.getQuery());
    this.limit = getLimit(params);
}

From source file:io.urmia.st.StorageServerHandler.java

License:Open Source License

private void handleGET(ChannelHandlerContext ctx, HttpRequest request) throws IOException {

    log.info("handleGET req: {}", request);

    final String uri = request.getUri();

    // todo: handle args: limit, object=true, directory=true, marker=xyz, sort_order=reverse, sort=mtime
    final int queryPos = uri.lastIndexOf('?');
    final String uriNoArgs = queryPos == -1 ? uri : uri.substring(0, queryPos);

    log.info("GET uriNoArgs: {}", uriNoArgs);

    final String path = BASE + uriNoArgs;

    File file = new File(path);

    if (file.exists()) {
        if (file.isFile()) {
            downloadFile(ctx, file);/*from w ww  . j a  v  a  2s .c  om*/
            return;
        }

        if (file.isDirectory()) {
            listDirectory(ctx, file);
            return;
        }
    }

    sendError(ctx, NOT_FOUND);
}

From source file:io.urmia.st.StorageServerHandler.java

License:Open Source License

private void handleDELETE(ChannelHandlerContext ctx, HttpRequest request) throws IOException {
    log.info("handleDELETE req: {}", request);

    final String uri = request.getUri();

    final int queryPos = uri.lastIndexOf('?');
    final String uriNoArgs = queryPos == -1 ? uri : uri.substring(0, queryPos);

    log.info("DELETE uriNoArgs: {}", uriNoArgs);

    final String path = BASE + uriNoArgs;

    File file = new File(path);

    if (!file.exists()) {
        sendError(ctx, HttpResponseStatus.NOT_FOUND);
        access.success(ctx, "DELETE", uri, requestStartMS);
        return;/*from   w ww  . j a  v  a 2s .c  o m*/
    }

    if (file.isDirectory()) {
        File[] files = file.listFiles();
        if (files != null && files.length != 0) {
            writeResponse(ctx, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST,
                    errorBody("DirectoryNotEmptyError", uriNoArgs + " is not empty")), true);
            //sendError(ctx, HttpResponseStatus.BAD_REQUEST); // dir not empty
            return;
        }
    }

    if (file.delete()) {
        log.info("deleted: {}", path);
        writeResponse(ctx, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT),
                true);
        access.success(ctx, "DELETE", uri + " -> " + file.getAbsolutePath(), requestStartMS);
    } else {
        log.info("unable to delete: {}", path);
        sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        access.fail(ctx, "DELETE", uri, requestStartMS);
    }

}

From source file:io.urmia.st.StorageServerHandler.java

License:Open Source License

private void handleHEAD(ChannelHandlerContext ctx, HttpRequest request) throws IOException {

    log.info("handleHEAD uri: {} ", request.getUri());

    HttpResponseStatus status = HttpResponseStatus.NO_CONTENT;

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status);

    String uri = request.getUri(); // HEAD /abbaspour/stor/20120624_002h.jpg HTTP/1.1

    final String path = BASE + uri;

    File f = new File(path);

    if (f.exists()) {
        if (f.isDirectory()) {
            response.headers().set(CONTENT_TYPE, "application/x-json-stream; type=directory");
        } else {//from w  w w .j  a v  a  2  s  .  c  o m
            setContentTypeHeader(response, f);
            response.headers().set(CONTENT_MD5, DigestUtils.md5sum(f));
        }
    }

    access.success(ctx, "HEAD", request.getUri(), requestStartMS);

    ctx.writeAndFlush(response); // VoidChannelPromise
}

From source file:io.urmia.st.StorageServerHandler.java

License:Open Source License

private void handlePUT(ChannelHandlerContext ctx, HttpRequest request) /*throws IOException*/ {

    log.debug("handlePUT: {}", request);

    final String location = getLocation(request);

    String uri = request.getUri();

    if (location != null) {
        String existing = BASE + location;
        String link = BASE + uri;
        log.debug("ln {} -> {}", link, existing);
        link(ctx, existing, link);/*w ww .  ja  v a  2s .c om*/
        return;
    }

    boolean isDir = isDirectory(request.headers().get("content-type"));
    // PUT

    String p = BASE + uri;

    log.info("creating {} at: {}", isDir ? "dir" : "file", p);

    File file = new File(p);

    if (isDir) {
        log.info("mkdir at: {}", p);
        final boolean done = file.mkdirs();

        if (done) {
            access.success(ctx, "MKDIR", uri, requestStartMS);
            ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT));
        } else {
            access.fail(ctx, "MKDIR", uri, requestStartMS);
            sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        }

    } else {
        file.getParentFile().mkdirs();
        this.uri = uri;

        // todo: handle 'location' header for 'mln()'. e.i. no content
        //Path path = file.toPath();
        //fileChannel = FileChannel.open(path, CREATE, WRITE);
        try {
            fileChannel = new FileOutputStream(file).getChannel(); // todo: should close fis?
        } catch (FileNotFoundException e) {
            log.error("exception in opening file channel: {}, err: {}", file, e.getMessage());
            writeResponse(ctx, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST,
                    errorBody("UploadError", "invalid path: " + uri)), true);
            return;
        }

        readingChunks = HttpHeaders.isTransferEncodingChunked(request);
        //log.info("is chunk: {}", readingChunks);

        ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); // VoidChannelPromise
    }
}

From source file:io.werval.server.netty.HttpRequestAggregator.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext context, HttpRequest newRequestHeader, List<Object> out)
        throws IOException {
    // Belt and braces
    // Needed as the channel is reused when Keep-Alive play its role
    cleanup();/*from ww w .  jav  a 2 s .c  om*/

    // Let's go
    HttpRequest currentRequestHeader = aggregatedRequestHeader;
    assert currentRequestHeader == null;
    assert consumedContentlength == 0;
    // assert bodyFile == null;
    // assert bodyBuf == null;

    if (is100ContinueExpected(newRequestHeader)) {
        context.write(HTTP_100_CONTINUE);
    }

    if (!newRequestHeader.getDecoderResult().isSuccess()) {
        removeTransferEncodingChunked(newRequestHeader);
        aggregatedRequestHeader = null;
        out.add(newRequestHeader);
        return;
    }

    // Generate new request identity
    String requestIdentity = helper.generateNewRequestIdentity();

    // Http Request Received Event
    context.channel().attr(Attrs.REQUEST_IDENTITY).set(requestIdentity);
    eventsSpi.emit(new HttpEvent.RequestReceived(requestIdentity, newRequestHeader.getMethod().name(),
            newRequestHeader.getUri()));

    currentRequestHeader = new DefaultHttpRequest(newRequestHeader.getProtocolVersion(),
            newRequestHeader.getMethod(), newRequestHeader.getUri());
    currentRequestHeader.headers().set(newRequestHeader.headers());

    removeTransferEncodingChunked(currentRequestHeader);

    aggregatedRequestHeader = currentRequestHeader;
}

From source file:io.werval.server.netty.HttpRequestAggregator.java

License:Apache License

private void handleHttpContent(ChannelHandlerContext context, HttpContent chunk, List<Object> out)
        throws IOException {
    HttpRequest currentRequestHeader = aggregatedRequestHeader;
    assert currentRequestHeader != null;

    int readableBytes = chunk.content().readableBytes();
    if (maxContentLength != -1 && consumedContentlength + readableBytes > maxContentLength) {
        LOG.warn("Request Entity is too large, content length exceeded {} bytes.", maxContentLength);
        ByteBuf body = copiedBuffer("HTTP content length exceeded " + maxContentLength + " bytes.", US_ASCII);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, REQUEST_ENTITY_TOO_LARGE, body);
        response.headers().set(CONTENT_TYPE, "text/plain; charset=" + US_ASCII.name().toLowerCase(US));
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        response.headers().set(CONNECTION, CLOSE);
        context.write(response).addListener(ChannelFutureListener.CLOSE); // HERE
        return;//  w w w. ja  va2  s.c  om
    }

    // Append chunk data to aggregated buffer or file
    if (chunk.content().isReadable()) {
        // Test disk threshold
        if (consumedContentlength + readableBytes > diskThreshold) {
            // Overflow to disk
            if (bodyFile == null) {
                // Start
                bodyFile = new File(diskOverflowDirectory, TEMP_FILE_ID_GEN.newIdentity());
                try (OutputStream bodyOutputStream = new FileOutputStream(bodyFile)) {
                    if (bodyBuf != null) {
                        bodyBuf.readBytes(bodyOutputStream, bodyBuf.readableBytes());
                        bodyBuf.release();
                        bodyBuf = null;
                    }
                    chunk.content().readBytes(bodyOutputStream, readableBytes);
                }
            } else {
                // Continue
                try (OutputStream bodyOutputStream = new FileOutputStream(bodyFile, true)) {
                    chunk.content().readBytes(bodyOutputStream, readableBytes);
                }
            }
        } else {
            // In-memory
            if (bodyBuf == null) {
                // Start
                bodyBuf = chunk.content().retain();
            } else {
                // Continue
                bodyBuf = wrappedBuffer(bodyBuf, chunk.content().retain());
            }
        }
        consumedContentlength += readableBytes;
    }

    // Last Chunk?
    final boolean last;
    if (!chunk.getDecoderResult().isSuccess()) {
        currentRequestHeader.setDecoderResult(DecoderResult.failure(chunk.getDecoderResult().cause()));
        last = true;
    } else {
        last = chunk instanceof LastHttpContent;
    }

    if (last) {
        // Merge trailing headers
        if (chunk instanceof LastHttpContent) {
            currentRequestHeader.headers().add(((LastHttpContent) chunk).trailingHeaders());
        }

        // Set the 'Content-Length' header
        currentRequestHeader.headers().set(CONTENT_LENGTH, String.valueOf(consumedContentlength));

        // Create aggregated request
        FullHttpRequest fullRequest;
        ByteBuf content = null;
        if (bodyFile != null) {
            content = new FileByteBuff(bodyFile);
        } else if (bodyBuf != null) {
            content = bodyBuf.retain();
        }
        if (content != null) {
            fullRequest = new DefaultFullHttpRequest(currentRequestHeader.getProtocolVersion(),
                    currentRequestHeader.getMethod(), currentRequestHeader.getUri(), content);
        } else {
            fullRequest = new DefaultFullHttpRequest(currentRequestHeader.getProtocolVersion(),
                    currentRequestHeader.getMethod(), currentRequestHeader.getUri());
        }
        fullRequest.headers().set(currentRequestHeader.headers());

        // All done
        aggregatedRequestHeader = null;
        consumedContentlength = 0;

        // Fire aggregated request
        out.add(fullRequest);
    }
}

From source file:jj.http.server.methods.OptionsMethodHandler.java

License:Apache License

@Override
protected void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest request) {
    DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    StringBuilder sb = new StringBuilder();
    if ("*".equals(request.getUri())) {
        for (HttpMethod method : methodHandlers.keySet()) {
            sb.append(method).append(",");
        }//from   w w  w .j a  va2s  .co m
        sb.deleteCharAt(sb.length() - 1);
    } else {
        for (HttpMethod method : router.matchURI(OPTIONS, new URIMatch(request.getUri())).routes.keySet()) {
            sb.append(method).append(",");
        }
        sb.append(HEAD).append(",").append(TRACE).append(",").append(OPTIONS);
    }
    response.headers().set(HttpHeaders.Names.ALLOW, sb.toString());
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:malcolm.HttpProxyFrontendHandler.java

License:Apache License

private void channelReadHttpRequest(final ChannelHandlerContext ctx, final HttpRequest req) {
    System.out.println(req.getMethod() + " " + req.getUri());
    this.proxyRequest(ctx, req, f -> {
        if (f.isSuccess()) {
            logger.debug("write complete");
            // TODO f.channel().read() ?
        } else {//from w w  w  .ja  va  2s. c  o  m
            logger.debug("write failed");
            // TODO bad gateway?
        }
    });
}

From source file:me.zhuoran.amoeba.netty.server.http.AmoebaHttpRequest.java

License:Apache License

public AmoebaHttpRequest(HttpRequest request, String channelId) {
    if (request != null && channelId != null) {
        this.httpRequest = request;
        this.uri = request.getUri();
        this.method = request.getMethod().toString();
        if (this.getMethod().equals("GET")) {
            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
            this.params = queryStringDecoder.parameters();
        }//from ww  w.j ava 2s.  co m

    } else {
        throw new IllegalArgumentException();
    }
}