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

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

Introduction

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

Prototype

HttpMethod PUT

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

Click Source Link

Document

The PUT method requests that the enclosed entity be stored under the supplied Request-URI.

Usage

From source file:com.spotify.google.cloud.pubsub.client.Pubsub.java

License:Apache License

/**
 * Make a PUT request.//from w  w w . ja  v a  2 s  .co m
 */
private <T> PubsubFuture<T> put(final String operation, final String path, final Object payload,
        final ResponseReader<T> responseReader) {
    return request(operation, HttpMethod.PUT, path, payload, responseReader);
}

From source file:com.strategicgains.restexpress.plugin.cache.DateHeaderPostprocessorTest.java

License:Apache License

@Test
public void shouldNotAddDateHeaderOnPut() {
    FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT,
            "/foo?param1=bar&param2=blah&yada");
    httpRequest.headers().add("Host", "testing-host");
    Response response = new Response();
    processor.process(new Request(httpRequest, null), response);
    assertFalse(response.hasHeader(HttpHeaders.Names.DATE));
}

From source file:com.strategicgains.restexpress.plugin.swagger.SwaggerPluginTest.java

License:Apache License

@BeforeClass
public static void intialize() {
    RestAssured.port = PORT;/*ww  w.  j a v  a 2  s .c om*/

    DummyController controller = new DummyController();
    SERVER.setBaseUrl(BASE_URL);

    SERVER.uri("/", controller).action("health", HttpMethod.GET).name("root");

    SERVER.uri("/anothers/{userId}", controller).action("readAnother", HttpMethod.GET);

    SERVER.uri("/users.{format}", controller).action("readAll", HttpMethod.GET)
            .action("options", HttpMethod.OPTIONS).method(HttpMethod.POST).name("Users Collection");

    SERVER.uri("/users/{userId}.{format}", controller).method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE)
            .action("options", HttpMethod.OPTIONS).name("Individual User");

    SERVER.uri("/users/{userId}/orders.{format}", controller).action("readAll", HttpMethod.GET)
            .method(HttpMethod.POST).name("User Orders Collection");

    SERVER.uri("/orders.{format}", controller).action("readAll", HttpMethod.GET).method(HttpMethod.POST)
            .name("Orders Collection");

    SERVER.uri("/orders/{orderId}.{format}", controller)
            .method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE).name("Individual Order");

    SERVER.uri("/orders/{orderId}/items.{format}", controller).action("readAll", HttpMethod.GET)
            .method(HttpMethod.POST).name("Order Line-Items Collection");

    SERVER.uri("/orders/{orderId}/items/{itemId}.{format}", controller)
            .method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE).name("Individual Order Line-Item");

    SERVER.uri("/products.{format}", controller).action("readAll", HttpMethod.GET).method(HttpMethod.POST)
            .name("Orders Collection");

    SERVER.uri("/products/{orderId}.{format}", controller)
            .method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE).name("Individual Order");

    SERVER.uri("/health", controller).flag("somevalue").action("health", HttpMethod.GET).name("health");

    SERVER.uri("/nicknametest", controller).method(HttpMethod.GET).name(" |nickName sh0uld_str1p-CHARS$. ");

    SERVER.uri("/annotations/{userId}/users", controller)
            .action("readWithApiOperationAnnotation", HttpMethod.GET).method(HttpMethod.GET)
            .name("Read with Annotations");

    SERVER.uri("/annotations/hidden", controller).action("thisIsAHiddenAPI", HttpMethod.GET)
            .method(HttpMethod.GET).name("thisIsAHiddenAPI");

    SERVER.uri("/annotations/{userId}", controller).action("updateWithApiResponse", HttpMethod.PUT)
            .method(HttpMethod.PUT).name("Update with Annotations");

    SERVER.uri("/annotations/{userId}/users/list", controller)
            .action("createWithApiImplicitParams", HttpMethod.POST).method(HttpMethod.POST)
            .name("Create with Implicit Params");

    SERVER.uri("/annotations/{userId}/users/newlist", controller).action("createWithApiParam", HttpMethod.POST)
            .method(HttpMethod.POST).name("Create with Api Param");

    SERVER.uri("/annotations/{userId}/users/list2", controller)
            .action("createWithApiModelRequest", HttpMethod.POST).method(HttpMethod.POST)
            .name("Create with Implicit Params");

    new SwaggerPlugin().apiVersion("1.0").swaggerVersion("1.2").flag("flag1").flag("flag2")
            .parameter("parm1", "value1").parameter("parm2", "value2").register(SERVER);

    SERVER.bind(PORT);
}

From source file:com.titilink.camel.rest.client.CamelClient.java

License:LGPL

/**
 * put//w ww.ja  v a  2  s  .  c  o m
 *
 * @param uri               
 * @param reqBuffer         ?
 * @param additionalHeaders header????token 
 * @param msTimeout         ?0?10s
 * @return json 
 */
public static RestResponse handlePut(URI uri, byte[] reqBuffer, Map<String, String> additionalHeaders,
        ChallengeResponse challengeResponse, long msTimeout) {
    return handle(HttpMethod.PUT, uri, reqBuffer, additionalHeaders, challengeResponse, true, msTimeout);
}

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

License:Open Source License

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

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

License:Open Source License

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

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

    if (this.callback.hasErrors()) {
        callback.complete();/*from w ww .j a va2 s. co  m*/
        return;
    }

    // send a request to get things going      
    HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT,
            "/upload/" + chanid + "/Final");

    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()));
    req.headers().set(HttpHeaders.Names.CONTENT_LENGTH, size - offset);

    // send request headers - must flush here in case CL = 0
    this.dest.writeAndFlush(req);

    // now start sending the file
    long sent = offset;
    callback.getContext().setAmountCompleted((int) (sent * 100 / size));

    ByteBuf bb = null;

    try {
        bb = Hub.instance.getBufferAllocator().directBuffer(64 * 1024); // TODO review if direct is best here

        long toskip = offset;

        if (src instanceof SeekableByteChannel) {
            ((SeekableByteChannel) src).position(toskip);
        } else {
            while (toskip > 0) {
                int skip = (int) Math.min(bb.capacity(), toskip);
                toskip -= bb.writeBytes(src, skip);
                bb.clear();
            }
        }

        // now start writing the upload
        int amt = bb.writeBytes(src, bb.capacity());

        while (amt != -1) {
            bb.retain(); // this ups ref cnt to 2 - we plan to reuse the buffer

            this.dest.writeAndFlush(bb).sync();

            sent += amt;

            if (size > 0)
                callback.getContext().setAmountCompleted((int) (sent * 100 / size));

            // by the time we get here, that buffer has been used up and we can use it for the next buffer
            if (bb.refCnt() != 1)
                throw new IOException("Buffer reference count is not correct");

            // stop writing if canceled
            if (!this.dest.isOpen()) {
                this.finish(); // might already be finished but to be sure (this is helpful when api.abortStream is called)
                break;
            }

            bb.clear();

            amt = bb.writeBytes(src, bb.capacity());
        }

        // we are now done with it
        bb.release();
    } catch (Exception x) {
        try {
            if (bb != null)
                bb.release();
        } catch (Exception x2) {
        }

        callback.error(1, "Local read error: " + x);
        this.finish();
    }
}

From source file:divconq.http.multipart.HttpPostRequestEncoder.java

License:Apache License

/**
 *
 * @param factory/*from   w  ww.  j  a v a 2s . c o m*/
 *            the factory used to create InterfaceHttpData
 * @param request
 *            the request to encode
 * @param multipart
 *            True if the FORM is a ENCTYPE="multipart/form-data"
 * @param charset
 *            the charset to use as default
 * @param encoderMode
 *            the mode for the encoder to use. See {@link EncoderMode} for the details.
 * @throws NullPointerException
 *             for request or charset or factory
 * @throws ErrorDataEncoderException
 *             if the request is not a POST
 */
public HttpPostRequestEncoder(HttpDataFactory factory, HttpRequest request, boolean multipart, Charset charset,
        EncoderMode encoderMode) throws ErrorDataEncoderException {
    if (factory == null) {
        throw new NullPointerException("factory");
    }
    if (request == null) {
        throw new NullPointerException("request");
    }
    if (charset == null) {
        throw new NullPointerException("charset");
    }
    HttpMethod method = request.getMethod();
    if (!(method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PATCH)
            || method.equals(HttpMethod.OPTIONS))) {
        throw new ErrorDataEncoderException("Cannot create a Encoder if not a POST");
    }
    this.request = request;
    this.charset = charset;
    this.factory = factory;
    // Fill default values
    bodyListDatas = new ArrayList<InterfaceHttpData>();
    // default mode
    isLastChunk = false;
    isLastChunkSent = false;
    isMultipart = multipart;
    multipartHttpDatas = new ArrayList<InterfaceHttpData>();
    this.encoderMode = encoderMode;
    if (isMultipart) {
        initDataMultipart();
    }
}

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  . jav a2s .com
    }

    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:edumsg.netty.EduMsgNettyServerInitializer.java

License:Open Source License

@Override
protected void initChannel(SocketChannel arg0) {
    CorsConfig corsConfig = CorsConfig.withAnyOrigin()
            .allowedRequestHeaders("X-Requested-With", "Content-Type", "Content-Length")
            .allowedRequestMethods(HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE,
                    HttpMethod.OPTIONS)/*from www.  j  a  v a2s .  c  om*/
            .build();
    ChannelPipeline p = arg0.pipeline();
    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(arg0.alloc()));
    }
    p.addLast("decoder", new HttpRequestDecoder());
    p.addLast("encoder", new HttpResponseEncoder());
    p.addLast(new CorsHandler(corsConfig));
    p.addLast(new EduMsgNettyServerHandler());
}

From source file:godfinger.http.HttpServerInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel channel) {
    CorsConfig corsConfig = CorsConfig.withAnyOrigin().allowCredentials()
            .allowedRequestMethods(HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE)
            .allowedRequestHeaders("accept", "content-type", "session-id").build();

    ChannelPipeline pipeline = channel.pipeline();
    pipeline.addLast(new HttpServerCodec());
    pipeline.addLast(new FaviconHandler());
    pipeline.addLast(new CorsHandler(corsConfig));
    pipeline.addLast(new HttpObjectAggregator(1024 * 1024));
    pipeline.addLast(new HttpRequestHandler(requestProcessor));
}