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:com.xx_dev.apn.proxy.ApnProxyUserAgentTunnelHandler.java

License:Apache License

private String constructConnectRequestForProxy(HttpRequest httpRequest, ApnProxyRemote apnProxyRemote) {
    String CRLF = "\r\n";
    String url = httpRequest.getUri();
    StringBuilder sb = new StringBuilder();
    sb.append(httpRequest.getMethod().name()).append(" ").append(url).append(" ")
            .append(httpRequest.getProtocolVersion().text()).append(CRLF);

    Set<String> headerNames = httpRequest.headers().names();
    for (String headerName : headerNames) {
        if (StringUtils.equalsIgnoreCase(headerName, "Proxy-Connection")) {
            continue;
        }//from   ww w . j a  v a  2 s  . c om

        if (StringUtils.equalsIgnoreCase(headerName, HttpHeaders.Names.CONNECTION)) {
            continue;
        }

        for (String headerValue : httpRequest.headers().getAll(headerName)) {
            sb.append(headerName).append(": ").append(headerValue).append(CRLF);
        }
    }

    if (StringUtils.isNotBlank(apnProxyRemote.getProxyUserName())
            && StringUtils.isNotBlank(apnProxyRemote.getProxyPassword())) {
        String proxyAuthorization = apnProxyRemote.getProxyUserName() + ":" + apnProxyRemote.getProxyPassword();
        try {
            sb.append("Proxy-Authorization: Basic "
                    + Base64.encodeBase64String(proxyAuthorization.getBytes("UTF-8"))).append(CRLF);
        } catch (UnsupportedEncodingException e) {
        }

    }

    sb.append(CRLF);

    return sb.toString();
}

From source file:com.xx_dev.apn.proxy.utils.HostNamePortUtil.java

License:Apache License

public static String getHostName(HttpRequest httpRequest) {
    String originalHostHeader = httpRequest.headers().get(HttpHeaders.Names.HOST);

    if (StringUtils.isBlank(originalHostHeader) && httpRequest.getMethod().equals(HttpMethod.CONNECT)) {
        originalHostHeader = httpRequest.getUri();
    }//from ww w  .ja v a 2 s.co  m

    if (StringUtils.isNotBlank(originalHostHeader)) {
        String originalHost = StringUtils.split(originalHostHeader, ": ")[0];
        return originalHost;
    } else {
        String uriStr = httpRequest.getUri();
        try {
            URI uri = new URI(uriStr);

            String schema = uri.getScheme();

            String originalHost = uri.getHost();

            return originalHost;
        } catch (URISyntaxException e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }
}

From source file:com.xx_dev.apn.proxy.utils.HostNamePortUtil.java

License:Apache License

public static int getPort(HttpRequest httpRequest) {
    int originalPort = 80;

    if (httpRequest.getMethod().equals(HttpMethod.CONNECT)) {
        originalPort = 443;/*from  w ww .j a  va 2 s  .  c  om*/
    }

    String originalHostHeader = httpRequest.headers().get(HttpHeaders.Names.HOST);

    if (StringUtils.isBlank(originalHostHeader) && httpRequest.getMethod().equals(HttpMethod.CONNECT)) {
        originalHostHeader = httpRequest.getUri();
    }

    if (StringUtils.isNotBlank(originalHostHeader)) {
        if (StringUtils.split(originalHostHeader, ": ").length == 2) {
            originalPort = Integer.parseInt(StringUtils.split(originalHostHeader, ": ")[1]);
        }
    } else {
        String uriStr = httpRequest.getUri();
        try {
            URI uri = URI.create(uriStr);

            if (uri.getPort() > 0) {
                originalPort = uri.getPort();
            }
        } catch (IllegalArgumentException e) {
            logger.error(e.getMessage(), e);
            originalPort = -1;
        }
    }

    return originalPort;
}

From source file:com.zhuowenfeng.devtool.hs_server.handler.HttpServiceHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    HSServerContext hsContext = new HSServerContext();
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        hsContext.setRequest(request);//from  ww  w . j a va2 s  .  c o m

        String uri = request.getUri();
        hsContext.setRequestUri(uri);

        if (is100ContinueExpected(request)) {
            send100Continue(ctx);
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        JSONObject pathVariables = new JSONObject();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    pathVariables.put(key, val);
                }
            }
        }
        hsContext.setPathVariables(pathVariables);
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;
        ByteBuf content = httpContent.content();
        JSONObject requestContent = new JSONObject();
        if (content.isReadable()) {
            requestContent = JSONObject.fromObject(content.toString(CharsetUtil.UTF_8));
        }
        hsContext.setRequestContent(requestContent);
        if (msg instanceof LastHttpContent) {
            LastHttpContent trailer = (LastHttpContent) msg;
            JSONObject result = HttpServiceDispatcher.dispatch(hsContext);
            writeResponse(trailer, ctx, result);
        }
    }
}

From source file:divconq.web.http.ServerHandler.java

License:Open Source License

public void handleHttpRequest(ChannelHandlerContext ctx, HttpObject httpobj) throws Exception {
    if (httpobj instanceof HttpContent) {
        this.context.offerContent((HttpContent) httpobj);
        return;//ww w .  j  a  v  a  2s.co m
    }

    if (!(httpobj instanceof HttpRequest)) {
        this.context.sendRequestBad();
        return;
    }

    HttpRequest httpreq = (HttpRequest) httpobj;

    this.context.load(ctx, httpreq);

    // Handle a bad request.
    if (!httpreq.getDecoderResult().isSuccess()) {
        this.context.sendRequestBad();
        return;
    }

    Request req = this.context.getRequest();
    Response resp = this.context.getResponse();

    // to avoid lots of unused sessions
    if (req.pathEquals("/favicon.ico") || req.pathEquals("/robots.txt")) {
        this.context.sendNotFound();
        return;
    }

    // make sure we don't have a leftover task context
    OperationContext.clear();

    String origin = "http:" + NetUtil.formatIpAddress((InetSocketAddress) ctx.channel().remoteAddress());

    // TODO use X-Forwarded-For  if available, maybe a plug in approach to getting client's IP?

    DomainInfo dinfo = this.context.getSiteman().resolveDomainInfo(req.getHeader("Host"));

    if (dinfo == null) {
        this.context.sendForbidden();
        return;
    }

    WebDomain wdomain = this.context.getSiteman().getDomain(dinfo.getId());

    // check into url re-routing
    String reroute = wdomain.route(req, (SslHandler) ctx.channel().pipeline().get("ssl"));

    if (StringUtil.isNotEmpty(reroute)) {
        this.context.getResponse().setStatus(HttpResponseStatus.FOUND);
        this.context.getResponse().setHeader("Location", reroute);
        this.context.send();
        return;
    }

    Cookie sesscookie = req.getCookie("SessionId");
    Session sess = null;

    if (sesscookie != null) {
        String v = sesscookie.getValue();
        String sessionid = v.substring(0, v.lastIndexOf('_'));
        String accesscode = v.substring(v.lastIndexOf('_') + 1);

        sess = Hub.instance.getSessions().lookupAuth(sessionid, accesscode);
    }

    if (sess == null) {
        sess = Hub.instance.getSessions().create(origin, dinfo.getId());

        Logger.info("Started new session: " + sess.getId() + " on " + req.getPath() + " for " + origin);

        // TODO if ssl set client key on user context
        //req.getSecuritySession().getPeerCertificates();

        sess.setAdatper(new ISessionAdapter() {
            protected volatile ListStruct msgs = new ListStruct();

            @Override
            public void stop() {
                ServerHandler.this.context.close();
            }

            @Override
            public ListStruct popMessages() {
                ListStruct ret = this.msgs;
                this.msgs = new ListStruct();
                return ret;
            }

            @Override
            public void deliver(Message msg) {
                // keep no more than 100 messages - this is not a "reliable" approach, just basic comm help               
                while (this.msgs.getSize() > 99)
                    this.msgs.removeItem(0);

                this.msgs.addItem(msg);
            }
        });

        Cookie sk = new DefaultCookie("SessionId", sess.getId() + "_" + sess.getKey());
        sk.setPath("/");
        sk.setHttpOnly(true);

        resp.setCookie(sk);
    }

    this.context.setSession(sess);

    sess.touch();

    OperationContext tc = sess.setContext(origin);

    tc.info("Web request for host: " + req.getHeader("Host") + " url: " + req.getPath() + " by: " + origin
            + " session: " + sess.getId());

    /*
    System.out.println("sess proto: " + ((SslHandler)ctx.channel().pipeline().get("ssl")).engine().getSession().getProtocol());
    System.out.println("sess suite: " + ((SslHandler)ctx.channel().pipeline().get("ssl")).engine().getSession().getCipherSuite());
    */

    try {
        if (req.pathEquals(ServerHandler.BUS_PATH)) {
            // Allow only GET methods.
            if (req.getMethod() != HttpMethod.GET) {
                this.context.sendForbidden();
                return;
            }

            // Handshake
            WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                    ServerHandler.getWebSocketLocation(
                            "True".equals(this.context.getConfig().getAttribute("Secure")), httpreq),
                    null, false);

            this.handshaker = wsFactory.newHandshaker(httpreq);

            if (this.handshaker == null)
                WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
            else {
                DefaultFullHttpRequest freq = new DefaultFullHttpRequest(httpreq.getProtocolVersion(),
                        httpreq.getMethod(), httpreq.getUri());

                freq.headers().add(httpreq.headers());

                this.handshaker.handshake(ctx.channel(), freq);

                return;
            }

            this.context.sendForbidden();
            return;
        }

        // "upload" is it's own built-in extension.  
        if ((req.getPath().getNameCount() == 3) && req.getPath().getName(0).equals(ServerHandler.UPLOAD_PATH)) {
            if (!Hub.instance.isRunning()) { // only allow uploads when running
                this.context.sendRequestBad();
                return;
            }

            // currently only supporting POST/PUT of pure binary - though support for form uploads can be restored, see below
            // we cannot rely on content type being meaningful
            //if (!"application/octet-stream".equals(req.getContentType().getPrimary())) {
            //    this.context.sendRequestBad();
            //    return;
            //}

            // TODO add CORS support if needed

            if ((req.getMethod() != HttpMethod.PUT) && (req.getMethod() != HttpMethod.POST)) {
                this.context.sendRequestBad();
                return;
            }

            final String cid = req.getPath().getName(1);
            final String op = req.getPath().getName(2);

            final DataStreamChannel dsc = sess.getChannel(cid);

            if (dsc == null) {
                this.context.sendRequestBad();
                return;
            }

            dsc.setDriver(new IStreamDriver() {
                @Override
                public void cancel() {
                    Logger.error("Transfer canceled on channel: " + cid);
                    dsc.complete();
                    ServerHandler.this.context.sendRequestBad(); // TODO headers?
                }

                @Override
                public void nextChunk() {
                    Logger.debug("Continue on channel: " + cid);
                    ServerHandler.this.context.sendRequestOk();
                }

                @Override
                public void message(StreamMessage msg) {
                    if (msg.isFinal()) {
                        Logger.debug("Final on channel: " + cid);
                        dsc.complete();
                        ServerHandler.this.context.sendRequestOk();
                    }
                }
            });

            //if (req.getMethod() == HttpMethod.PUT) {
            this.context.setDecoder(new IContentDecoder() {
                protected boolean completed = false;
                protected int seq = 0;

                @Override
                public void release() {
                    // trust that http connection is closing or what ever needs to happen, we just need to deal with datastream

                    Logger.debug("Releasing data stream");

                    // if not done with request then something went wrong, kill data channel
                    if (!this.completed)
                        dsc.abort();
                }

                @Override
                public void offer(HttpContent chunk) {
                    boolean finalchunk = (chunk instanceof LastHttpContent);

                    //System.out.println("Chunk: " + finalchunk);

                    ByteBuf buffer = chunk.content();

                    if (!dsc.isClosed()) {
                        int size = buffer.readableBytes();

                        //System.out.println("Chunk size: " + size);

                        dsc.touch(); // TODO try to set progress on dsc

                        // TODO set hint in netty as to where this buffer was handled and sent

                        if (size > 0) {
                            buffer.retain(); // we will be using a reference up during send

                            StreamMessage b = new StreamMessage("Block", buffer);
                            b.setField("Sequence", this.seq);

                            //System.out.println("Buffer ref cnt a: " + buffer.refCnt());

                            OperationResult or = dsc.send(b);

                            //System.out.println("Buffer ref cnt b: " + buffer.refCnt());

                            // indicate we have read the buffer?
                            buffer.readerIndex(buffer.writerIndex());

                            if (or.hasErrors()) {
                                dsc.close();
                                return;
                            }

                            this.seq++;
                        }

                        // if last buffer of last block then mark the upload as completed
                        if (finalchunk) {
                            if ("Final".equals(op))
                                dsc.send(MessageUtil.streamFinal());
                            else
                                dsc.getDriver().nextChunk();
                        }
                    }

                    // means this block is completed, not necessarily entire file uploaded
                    if (finalchunk)
                        this.completed = true;
                }
            });

            //return;
            //}

            /* old approach that supported multipart posts TODO review/remove
            if (req.getMethod() == HttpMethod.POST) {
               StreamingDataFactory sdf = new StreamingDataFactory(dsc, op);
                       
               // TODO consider supporting non-multipart?
               final HttpPostMultipartRequestDecoder prd = new HttpPostMultipartRequestDecoder(sdf, httpreq); 
                    
                 this.context.setDecoder(new IContentDecoder() {               
                 @Override
                 public void release() {
             // trust that http connection is closing or what ever needs to happen, we just need to deal with datastream
                     
             // if not done with request then something went wrong, kill data channel
             if ((prd.getStatus() != MultiPartStatus.EPILOGUE) && (prd.getStatus() != MultiPartStatus.PREEPILOGUE))
                dsc.kill();
                 }
                         
                 @Override
                 public void offer(HttpContent chunk) {
             //the only thing we care about is the file, the file will stream to dsc - the rest can disappear
             prd.offer(chunk);      
                 }
              });
                         
                  return;
            }                         
            */

            //this.context.sendRequestBad();
            return;
        }

        // "download" is it's own built-in extension.  
        if ((req.getPath().getNameCount() == 2)
                && req.getPath().getName(0).equals(ServerHandler.DOWNLOAD_PATH)) {
            if (!Hub.instance.isRunning()) { // only allow downloads when running
                this.context.sendRequestBad();
                return;
            }

            if (req.getMethod() != HttpMethod.GET) {
                this.context.sendRequestBad();
                return;
            }

            String cid = req.getPath().getName(1);

            final DataStreamChannel dsc = sess.getChannel(cid);

            if (dsc == null) {
                this.context.sendRequestBad();
                return;
            }

            dsc.setDriver(new IStreamDriver() {
                //protected long amt = 0;
                protected long seq = 0;

                @Override
                public void cancel() {
                    dsc.complete();
                    ServerHandler.this.context.close();
                }

                @Override
                public void nextChunk() {
                    // meaningless in download
                }

                @Override
                public void message(StreamMessage msg) {
                    int seqnum = (int) msg.getFieldAsInteger("Sequence", 0);

                    if (seqnum != this.seq) {
                        this.error(1, "Bad sequence number: " + seqnum);
                        return;
                    }

                    if (msg.hasData()) {
                        //this.amt += msg.getData().readableBytes();
                        HttpContent b = new DefaultHttpContent(Unpooled.copiedBuffer(msg.getData())); // TODO not copied
                        ServerHandler.this.context.sendDownload(b);
                    }

                    this.seq++;

                    // TODO update progress

                    if (msg.isFinal()) {
                        ServerHandler.this.context.sendDownload(new DefaultLastHttpContent());
                        ServerHandler.this.context.close();
                        dsc.complete();
                    }
                }

                public void error(int code, String msg) {
                    dsc.send(MessageUtil.streamError(code, msg));
                    ServerHandler.this.context.close();
                }
            });

            // for some reason HyperSession is sending content. 
            this.context.setDecoder(new IContentDecoder() {
                @Override
                public void release() {
                }

                @Override
                public void offer(HttpContent chunk) {
                    if (!(chunk instanceof LastHttpContent))
                        Logger.error("Unexplained and unwanted content during download: " + chunk);
                }
            });

            // tell the client that chunked content is coming
            this.context.sendDownloadHeaders(dsc.getPath() != null ? dsc.getPath().getFileName() : null,
                    dsc.getMime());

            // get the data flowing
            dsc.send(new StreamMessage("Start"));

            return;
        }

        if ((req.getPath().getNameCount() == 1) && req.getPath().getName(0).equals(ServerHandler.STATUS_PATH)) {
            if (Hub.instance.getState() == HubState.Running)
                this.context.sendRequestOk();
            else
                this.context.sendRequestBad();

            return;
        }

        // "rpc" is it's own built-in extension.  all requests to rpc are routed through
        // DivConq bus, if the request is valid
        if (req.pathEquals(ServerHandler.RPC_PATH)) {
            if (req.getMethod() != HttpMethod.POST) {
                this.context.sendRequestBad();
                return;
            }

            //System.out.println("looks like we have a rpc message");

            // max 4MB of json? -- TODO is that max chunk size or max total?  we don't need 4MB chunk... 
            this.context.setDecoder(new HttpBodyRequestDecoder(4096 * 1024, new RpcHandler(this.context)));
            return;
        }

        // otherwise we need to figure out which extension is being called
        // "local" is also used to mean default extension
        String ext = req.pathEquals("/") ? "local" : req.getPath().getName(0);

        IWebExtension ex = "local".equals(ext) ? this.context.getSiteman().getDefaultExtension()
                : this.context.getSiteman().getExtension(ext);

        // still cannot figure it out, use default
        if (ex == null)
            ex = this.context.getSiteman().getDefaultExtension();

        // then have extension handle it
        if (ex != null) {
            //OperationResult res = new OperationResult();  

            OperationResult res = ex.handle(sess, this.context);
            //resp.addBody("Hello");
            //this.context.send();

            // no errors starting page processing, return 
            if (!res.hasErrors())
                return;

            resp.setHeader("X-dcResultCode", res.getCode() + "");
            resp.setHeader("X-dcResultMesage", res.getMessage());
            this.context.sendNotFound();
            return;
        }
    } catch (Exception x) {
        this.context.sendInternalError();
        return;
    }

    this.context.sendNotFound();
}

From source file:divconq.web.Request.java

License:Open Source License

public void load(ChannelHandlerContext ctx, HttpRequest req) {
    this.method = req.getMethod();
    this.headers = req.headers();

    String value = req.headers().get(Names.COOKIE);

    if (StringUtil.isNotEmpty(value)) {
        Set<Cookie> cset = CookieDecoder.decode(value);

        for (Cookie cookie : cset)
            this.cookies.put(cookie.getName(), cookie);
    }//from  w  w w. java 2  s. c  o  m

    QueryStringDecoder decoderQuery = new QueryStringDecoder(req.getUri());
    this.parameters = decoderQuery.parameters(); // TODO decode
    this.path = new CommonPath(QueryStringDecoder.decodeComponent(decoderQuery.path()));
    this.orgpath = this.path;

    this.contentType = new ContentTypeParser(this.headers.get(Names.CONTENT_TYPE));
}

From source file:edu.upennlib.redirect.RedirectHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
    QueryStringDecoder orig = new QueryStringDecoder(msg.getUri());
    List<String> vals = orig.parameters().get(REDIRECT_PARAM_KEY);
    String val;
    if (vals == null || vals.isEmpty() || (val = vals.get(0)) == null) {
        badRequest("no redirect specified", ctx);
        return;//from   ww  w. ja v  a  2  s  .c o m
    }
    Matcher m = PRE_PATH.matcher(val);
    String parsed = null;
    if (!m.find() || !validHosts.contains(parsed = m.group())) {
        badRequest("redirect not permitted: " + val + ", parsed=" + parsed, ctx);
        return;
    }
    DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND);
    resp.headers().add(LOCATION, val);
    resp.headers().add(CONNECTION, CLOSE);
    ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
}

From source file:errorcode.DaumStatusServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    FullHttpResponse response = null;/*from  w ww  . j av  a 2  s.  c  o  m*/

    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());

        if (is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }
        boolean keepAlive = isKeepAlive(req);
        if (queryDecoder.path().startsWith("/503.html")) {
            response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(E503));
            response.setStatus(SERVICE_UNAVAILABLE);
        } else {
            response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(E404));
            response.setStatus(NOT_FOUND);
        }

        response.headers().set(CONTENT_TYPE, "text/html");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

From source file:example.crm.NettyFileRouteBuilder.java

License:Apache License

@Override
public void configure() throws Exception {
    from("netty4-http:http://localhost:9003/public?matchOnUriPrefix=true").process(new Processor() {
        @Override// w ww . ja v  a  2 s  .  c  om
        public void process(Exchange exchange) throws Exception {
            NettyHttpMessage in = exchange.getIn(NettyHttpMessage.class);

            HttpRequest request = in.getHttpRequest();
            final Message out = exchange.getOut();
            if (request.getMethod() != GET) {
                setErrorResponse(out, METHOD_NOT_ALLOWED);
                return;
            }

            final String path = sanitizeUri(request.getUri());
            if (path == null) {
                setErrorResponse(out, FORBIDDEN);
                return;
            }

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

            // Cache Validation
            String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
            if (ifModifiedSince != null && ifModifiedSince.length() != 0) {
                SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
                Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

                // Only compare up to the second because the datetime format we send to the client does
                // not have milliseconds
                long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
                long fileLastModifiedSeconds = file.lastModified() / 1000;
                if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {

                    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, NOT_MODIFIED);

                    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

                    Calendar time = new GregorianCalendar();
                    out.setHeader(DATE, dateFormatter.format(time.getTime()));
                    out.setBody(response);

                    return;
                }
            }

            final byte[] content = Files.readAllBytes(file.toPath());
            HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                    NettyConverter.toByteBuffer(content));

            response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.length);
            setDateAndCacheHeaders(response, file);

            String mimeType = Files.probeContentType(file.toPath());
            out.setHeader(Exchange.CONTENT_TYPE, mimeType);

            out.setBody(response);
        }
    });
}

From source file:fileShare.HttpUploadServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        System.out.println("==================================HttpRequest==================================");
        System.out.println(msg.toString());
        URI uri = new URI(request.getUri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);//from w ww  .  jav  a 2 s  .  co  m
            return;
        }
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");

        responseContent.append("VERSION: " + request.getProtocolVersion().text() + "\r\n");

        responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n");
        responseContent.append("\r\n\r\n");

        // new getMethod
        List<Entry<String, String>> headers = request.headers().entries();
        for (Entry<String, String> entry : headers) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().get(COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = CookieDecoder.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie.toString() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
            }
        }
        responseContent.append("\r\n\r\n");

        // if GET Method: should not try to create a HttpPostRequestDecoder
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        } catch (IncompatibleDataDecoderException e1) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So OK but stop here
            responseContent.append(e1.getMessage());
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            writeResponse(ctx.channel());
            return;
        }

        readingChunks = HttpHeaders.isTransferEncodingChunked(request);
        responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        if (readingChunks) {
            // Chunk version
            responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                System.out.println(
                        "==================================HttpContent==================================");
                //?
                System.out.println(new String(((DefaultHttpContent) chunk).content().array()));
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append(e1.getMessage());
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    }
}