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:de.albahrani.pi4j.rest.sysinfo.RaspberrySystemInfoControllerTestRest.java

License:Apache License

@Test
public void testSystemClockInfo() {
    RestExpress server = mock(RestExpress.class);
    RaspberrySystemInfoController controller = new RaspberrySystemInfoController();

    Map<String, ParameterizedRouteBuilder> routeBuilders = new HashMap<>();

    String[] expectedRouteNames = new String[] { "test/clock", "test/java", "test/memory", "test/cpu",
            "test/os", "test/features", "test" };
    for (int i = 0; i < expectedRouteNames.length; i++) {
        String expectedRouteName = expectedRouteNames[i];
        ParameterizedRouteBuilder routeBuilder = mock(ParameterizedRouteBuilder.class);
        when(server.uri(eq(expectedRouteName), eq(controller))).thenReturn(routeBuilder);
        when(routeBuilder.action(anyString(), any())).thenReturn(routeBuilder);
        routeBuilders.put(expectedRouteName, routeBuilder);
    }/*from  w w w.j  ava 2 s . c  o m*/
    controller.attach(server, "test");

    Set<Entry<String, ParameterizedRouteBuilder>> entrySet = routeBuilders.entrySet();
    for (Entry<String, ParameterizedRouteBuilder> entry : entrySet) {
        verify(server).uri(entry.getKey(), controller);
        ParameterizedRouteBuilder routeBuilder = entry.getValue();
        verify(routeBuilder).action(anyString(), eq(HttpMethod.GET));
        verify(routeBuilder).action(anyString(), eq(HttpMethod.OPTIONS));
        verifyNoMoreInteractions(routeBuilder);
    }
    verifyNoMoreInteractions(server);
}

From source file:de.albahrani.pi4j.rest.sysinfo.RaspberrySystemInfoControllerTestRest.java

License:Apache License

@Test
public void testCorsSetting() {
    RaspberrySystemInfoController controller = new RaspberrySystemInfoController();
    Pi4jSystemInfoFacade systemInfoProvider = createSystemInfoProviderMock();
    controller.setSystemInfo(systemInfoProvider);

    Request request = mock(Request.class);
    when(request.getHttpMethod()).thenReturn(HttpMethod.GET, HttpMethod.OPTIONS);
    Response response = new Response();

    controller.setAllowedCorsOrigin("http://abc.def.com");
    controller.getSystemClockInfo(request, response);

    String origin = response.getHeader("Access-Control-Allow-Origin");
    assertEquals("http://abc.def.com", origin);

    Response responseOptions = new Response();
    controller.getSystemClockInfo(request, responseOptions);
    String originOptions = responseOptions.getHeader("Access-Control-Allow-Origin");
    assertEquals("http://abc.def.com", originOptions);

}

From source file:de.dfki.kiara.util.URILoader.java

License:Open Source License

public static ByteBuffer load(URI uri) throws IOException {
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;//from  ww  w . ja v a 2s  .  c o m
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        throw new IOException("Only HTTP(S) is supported.");
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    HttpClientHandler handler = new HttpClientHandler();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpClientInitializer(sslCtx, handler));

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                uri.getRawPath());
        request.headers().set(HttpHeaders.Names.HOST, host);
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

        // Send the HTTP request.
        ch.writeAndFlush(request);

        // Wait for the server to close the connection.
        ch.closeFuture().sync();
    } catch (InterruptedException ex) {
        throw new IOException("Loading interrupted", ex);
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }

    Throwable error = handler.getError();
    if (error != null)
        throw new IOException("Could not load content", error);

    if (!HttpResponseStatus.OK.equals(handler.getStatus()))
        throw new IOException("HTTP response error: " + handler.getStatus());

    return ByteBuffer.wrap(handler.getContent(), 0, handler.getContentSize());
}

From source file:discord4j.rest.route.Route.java

License:Open Source License

public static <T> Route<T> get(String uri, Class<T> responseType) {
    return new Route<>(HttpMethod.GET, uri, responseType);
}

From source file:divconq.api.internal.DownloadHandler.java

License:Open Source License

public void start(final HyperSession parent, WritableByteChannel dest, String chanid,
        Map<String, Cookie> cookies, long size, long offset, final OperationCallback callback) {
    this.dest = dest;
    this.cookies = cookies;
    this.callback = callback;
    this.size = size;
    this.sent = offset;

    this.src = this.allocateChannel(parent, callback);

    if (this.callback.hasErrors()) {
        callback.complete();//  w w w  . j a v a 2  s.co  m
        return;
    }

    // send a request to get things going

    HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/download/" + chanid);

    req.headers().set(Names.HOST, parent.getInfo().getHost());
    req.headers().set(Names.USER_AGENT, "DivConq HyperAPI Client 1.0");
    req.headers().set(Names.CONNECTION, HttpHeaders.Values.CLOSE);
    req.headers().set(Names.COOKIE, ClientCookieEncoder.encode(this.cookies.values()));

    // send request
    this.src.writeAndFlush(req);
}

From source file:divconq.bus.net.ServerHandler.java

License:Open Source License

@Override
public void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    // Handle a bad request.
    if (!req.getDecoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;/*from  w  w  w . j  av  a 2s  .  c  om*/
    }

    // Allow only GET methods.
    if (req.getMethod() != HttpMethod.GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // Send the demo page and favicon.ico
    if ("/".equals(req.getUri())) {
        ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req));
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

        res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpHeaders.setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
        return;
    }

    if ("/favicon.ico".equals(req.getUri())) {
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
        sendHttpResponse(ctx, req, res);
        return;
    }

    if (CommonHandler.BUS_PATH.equals(req.getUri())) {
        // Handshake
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                getWebSocketLocation(req), null, false);

        this.handshaker = wsFactory.newHandshaker(req);

        if (this.handshaker == null)
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        else
            this.handshaker.handshake(ctx.channel(), req);

        return;
    }

    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
    this.sendHttpResponse(ctx, req, res);
}

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;/*from   w  ww. j av a2  s .c  om*/
    }

    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:dna.central.httpClient.HttpSnoopClient.java

License:Apache License

@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;/*from w w w.  j a va2s.co m*/
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx));

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                uri.getRawPath());
        request.headers().set(HttpHeaders.Names.HOST, host);
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

        // Set some example cookies.
        request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder
                .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar")));

        // Send the HTTP request.
        ch.writeAndFlush(request);

        // Wait for the server to close the connection.
        ch.closeFuture().sync();
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}

From source file:dpfmanager.shell.modules.server.get.HttpGetHandler.java

License:Open Source License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.uri());
        if (request.method().equals(HttpMethod.GET)) {
            // New GET request
            String path = uri.getPath();
            tractReadGet(ctx, path);//from   w ww  .  j av a  2  s.  c o m
            return;
        } else {
            sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
            return;
        }
    }
}

From source file:eastwind.webpush.WebPushHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws JsonProcessingException {
    // Handle a bad request.
    if (!req.decoderResult().isSuccess()) {
        sendHttpResponse(ctx, req,//from  ww w . j  a v  a 2 s. com
                new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
        return;
    }

    // Allow only GET methods.
    if (req.method() != HttpMethod.GET) {
        sendHttpResponse(ctx, req,
                new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN));
        return;
    }

    String uid = null;
    String uuid = null;
    Channel channel = ctx.channel();

    int q = req.uri().indexOf("?");
    String path = req.uri();
    if (q != -1) {
        path = path.substring(0, q);
    }
    List<String> l = Lists.newLinkedList(Splitter.on("/").omitEmptyStrings().trimResults().split(path));
    if (l.size() >= 2) {
        uid = l.get(0);
        uuid = l.get(1);
        Session s = sessionManager.get(uid, uuid);
        if (s == null) {
            logger.info("expired:{}-{}", uid, uuid);
            sendHttpResponse(ctx, req,
                    new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN));
        }
        if (l.size() == 2) {
            s.setChannel(channel);
            s.trySendMessages();
        } else {
            String oper = l.get(2);
            handleHttpOper(ctx, req, s, oper);
        }
    } else {
        String params = "";
        if (q != -1) {
            String uri = req.uri();
            if (q < uri.length() - 1) {
                params = uri.substring(q + 1);
            }
        }
        try {
            uid = action.active(channel.remoteAddress(), params);
        } catch (Throwable th) {
            logger.warn("active:", th);
            sendHttpResponse(ctx, req,
                    new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR,
                            Unpooled.copiedBuffer(th.getClass().getName(), Charset.forName("utf-8"))));
            return;
        }
        if (uid != null) {
            uuid = sessionManager.create(uid).getUuid();
            logger.info("active:{}-{}", uid, uuid);
            SessionGroup sg = sessionManager.get(uid);
            timer.newTimeout(new SessionCleaner(sg), lost, TimeUnit.MILLISECONDS);
        }

        // websocket
        if ("Upgrade".equals(req.headers().get(HttpHeaderNames.CONNECTION))
                && "websocket".equals(req.headers().get(HttpHeaderNames.UPGRADE))) {
            // Handshake
            WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                    getWebSocketLocation(req, ""), null, true);
            handshaker = wsFactory.newHandshaker(req);
            if (handshaker == null) {
                WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(channel);
                return;
            } else {
                handshaker.handshake(channel, req);
                UserLite.set(channel, new UserLite(uid, uuid));
            }
        } else {
            String content = String.format("{\"uid\":\"%s\", \"uuid\":\"%s\"}", uid, uuid);
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                    Unpooled.copiedBuffer(content, Charset.forName("utf-8"))));
        }
    }
}