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

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

Introduction

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

Prototype

HttpMethod POST

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

Click Source Link

Document

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line.

Usage

From source file:com.android.tools.idea.diagnostics.crash.GoogleCrashTest.java

License:Apache License

@Ignore
@Test//from   www.ja  va 2 s  .  com
public void checkServerReceivesPostedData() throws Exception {
    String expectedReportId = "deadcafe";
    Map<String, String> attributes = new ConcurrentHashMap<>();

    myTestServer.setResponseSupplier(httpRequest -> {
        if (httpRequest.method() != HttpMethod.POST) {
            return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
        }

        HttpPostRequestDecoder requestDecoder = new HttpPostRequestDecoder(httpRequest);
        try {
            for (InterfaceHttpData httpData : requestDecoder.getBodyHttpDatas()) {
                if (httpData instanceof Attribute) {
                    Attribute attr = (Attribute) httpData;
                    attributes.put(attr.getName(), attr.getValue());
                }
            }
        } catch (IOException e) {
            return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
        } finally {
            requestDecoder.destroy();
        }

        return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                Unpooled.wrappedBuffer(expectedReportId.getBytes(UTF_8)));
    });

    CrashReport report = CrashReport.Builder.createForException(ourIndexNotReadyException)
            .setProduct("AndroidStudioTestProduct").setVersion("1.2.3.4").build();
    CompletableFuture<String> reportId = myReporter.submit(report);

    assertEquals(expectedReportId, reportId.get());

    // assert that the server get the expected data
    assertEquals("AndroidStudioTestProduct", attributes.get(GoogleCrash.KEY_PRODUCT_ID));
    assertEquals("1.2.3.4", attributes.get(GoogleCrash.KEY_VERSION));

    // Note: the exception message should have been elided
    assertEquals("com.intellij.openapi.project.IndexNotReadyException: <elided>\n" + STACK_TRACE,
            attributes.get(GoogleCrash.KEY_EXCEPTION_INFO));

    List<String> descriptions = Arrays.asList("2.3.0.0\n1.8.0_73-b02", "2.3.0.1\n1.8.0_73-b02");
    report = CrashReport.Builder.createForCrashes(descriptions).setProduct("AndroidStudioTestProduct")
            .setVersion("1.2.3.4").build();

    attributes.clear();

    reportId = myReporter.submit(report);
    assertEquals(expectedReportId, reportId.get());

    // check that the crash count and descriptions made through
    assertEquals(descriptions.size(), Integer.parseInt(attributes.get("numCrashes")));
    assertEquals("2.3.0.0\n1.8.0_73-b02\n\n2.3.0.1\n1.8.0_73-b02", attributes.get("crashDesc"));

    Path testData = Paths.get(AndroidTestBase.getTestDataPath());
    List<String> threadDump = Files.readAllLines(testData.resolve(Paths.get("threadDumps", "1.txt")), UTF_8);
    report = CrashReport.Builder.createForPerfReport("td.txt", Joiner.on('\n').join(threadDump)).build();

    attributes.clear();

    reportId = myReporter.submit(report);
    assertEquals(expectedReportId, reportId.get());
    assertEquals(threadDump.stream().collect(Collectors.joining("\n")), attributes.get("td.txt"));
}

From source file:com.barchart.netty.rest.client.transport.TestURLConnectionTransport.java

License:BSD License

@Before
public void setUp() throws Exception {

    final ServerSocket s = new ServerSocket(0);
    port = s.getLocalPort();// w  w w  . j  ava2  s . c  o m
    s.close();

    final HttpServer server = Servers.createHttpServer().requestHandler("/test", new RequestHandlerBase() {
        @Override
        public void handle(final HttpServerRequest request) throws IOException {

            if (request.getMethod() == HttpMethod.POST) {
                request.response().setStatus(HttpResponseStatus.OK);
            } else {
                request.response().setStatus(HttpResponseStatus.BAD_REQUEST);
            }
            request.response().write(request.getMethod().name());
            request.response().finish();

        }
    });

    server.listen(port, "localhost").sync();

}

From source file:com.barchart.netty.rest.server.RestHandlerBase.java

License:BSD License

@Override
public void handle(final HttpServerRequest request) throws IOException {

    final HttpMethod method = request.getMethod();

    try {/*from  w ww .j a  v  a 2s .c  o  m*/
        if (method == HttpMethod.GET) {
            get(request);
        } else if (method == HttpMethod.POST) {
            post(request);
        } else if (method == HttpMethod.PUT) {
            put(request);
        } else if (method == HttpMethod.DELETE) {
            delete(request);
        } else {
            complete(request.response(), HttpResponseStatus.METHOD_NOT_ALLOWED,
                    method.name() + " not implemented");
        }
    } catch (final Throwable t) {
        complete(request.response(), HttpResponseStatus.INTERNAL_SERVER_ERROR, t.getMessage());
    }

}

From source file:com.barchart.netty.rest.server.TestRestHandler.java

License:BSD License

@Test
public void testPost() throws Exception {

    request.method = HttpMethod.POST;
    service.handle(request);/*from  ww  w  . j a v  a  2  s.com*/

    assertEquals(1, handler.requests);
    assertEquals(0, handler.get);
    assertEquals(0, handler.put);
    assertEquals(1, handler.post);
    assertEquals(0, handler.delete);
    assertEquals(0, handler.exceptions);

}

From source file:com.chiorichan.http.HttpHandler.java

License:Mozilla Public License

/**
 * Handles the HTTP request. Each HTTP subsystem will be explicitly activated until a resolve is determined.
 *
 * @throws IOException/* w w w  .  j  a v a  2 s.c om*/
 *              Universal exception for all Input/Output errors
 * @throws HttpError
 *              for HTTP Errors
 * @throws PermissionException
 *              for permission problems, like access denied
 * @throws MultipleException
 *              for multiple Scripting Factory Evaluation Exceptions
 * @throws ScriptingException
 *              for Scripting Factory Evaluation Exception
 * @throws SessionException
 *              for problems initializing a new or used session
 */
private void handleHttp() throws Exception // IOException, HttpError, SiteException, PermissionException, MultipleException, ScriptingException, SessionException
{
    log.log(Level.INFO, request.methodString() + " " + request.getFullUrl());

    Session sess = request.startSession();

    log.log(Level.FINE, "Session {id=%s,timeout=%s,new=%s}", sess.getSessId(), sess.getTimeout(), sess.isNew());

    if (response.getStage() == HttpResponseStage.CLOSED)
        throw new IOException("Connection reset by peer"); // This is not the only place 'Connection reset by peer' is thrown

    RequestEvent requestEvent = new RequestEvent(request);

    try {
        EventBus.instance().callEventWithException(requestEvent);
    } catch (EventException ex) {
        throw new IOException(
                "Exception encountered during request event call, most likely the fault of a plugin.", ex);
    }

    response.setStatus(requestEvent.getStatus());

    if (requestEvent.isCancelled()) {
        int status = requestEvent.getStatus();
        String reason = requestEvent.getReason();

        if (status == 200) {
            status = 502;
            reason = "Navigation Cancelled by Plugin Event";
        }

        NetworkManager.getLogger().warning("Navigation was cancelled by a Plugin Event");

        throw new HttpError(status, reason);
    }

    if (response.isCommitted())
        return;

    // Throws IOException and HttpError
    fi = new WebInterpreter(request);
    response.annotations.putAll(fi.getAnnotations());

    currentSite = request.getLocation();
    sess.setSite(currentSite);

    if (request.getSubdomain().length() > 0
            && !currentSite.getSubdomain(request.getSubdomain()).isMaped(request.getDomain())) {
        if ("www".equalsIgnoreCase(request.getSubdomain())
                || AppConfig.get().getBoolean("sites.redirectMissingSubDomains")) {
            log.log(Level.SEVERE, "Redirecting non-existent subdomain '%s' to root domain '%s'",
                    request.getSubdomain(), request.getFullUrl(""));
            response.sendRedirect(request.getFullUrl(""));
        } else {
            log.log(Level.SEVERE, "The requested subdomain '%s' is non-existent.", request.getSubdomain(),
                    request.getFullDomain(""));
            response.sendError(HttpResponseStatus.NOT_FOUND, "Subdomain not found");
        }
        return;
    }

    File docRoot = currentSite.getSubdomain(request.getSubdomain()).directory();

    Validate.notNull(docRoot);

    if (sess.isLoginPresent())
        log.log(Level.FINE, "Account {id=%s,displayName=%s}", sess.getId(), sess.getDisplayName());

    /*
     * Start: SSL enforcer
     *
     * Acts on the value of annotation 'SSL'.
     * REQUIRED means a forbidden error will be thrown is it can not be accomplished
     *
     * Options include:
     * Preferred: If SSL is available, we preferred to be switched to it
     * PostOnly: SSL is REQUIRED is this is a POST request
     * GetOnly: SSL is REQUIRED if this is a GET request
     * Required: SSL is REQUIRED, no exceptions!
     * Deny: SSL is DENIED, no exceptions!
     * Ignore: We don't care one way or other, do nothing! DEFAULT
     */
    SslLevel sslLevel = SslLevel.parse(fi.get("ssl"));
    boolean required = false;

    switch (sslLevel) {
    case Preferred:
        if (NetworkManager.isHttpsRunning())
            required = true;
        break;
    case PostOnly:
        if (request.method() == HttpMethod.POST)
            required = true;
        break;
    case GetOnly:
        if (request.method() == HttpMethod.GET)
            required = true;
        break;
    case Required:
        required = true;
        break;
    case Deny:
        if (ssl) {
            if (!response.switchToUnsecure())
                response.sendError(HttpCode.HTTP_FORBIDDEN, "This page requires an unsecure connection.");
            return;
        }
        break;
    case Ignore:
        break;
    }

    if (required && !ssl) {
        if (!response.switchToSecure())
            response.sendError(HttpCode.HTTP_FORBIDDEN, "This page requires a secure connection.");
        return;
    }
    /*
     * End: SSL enforcer
     */

    if (fi.getStatus() != HttpResponseStatus.OK)
        throw new HttpError(fi.getStatus());

    /*
     * Start: Apache Configuration Section
     *
     * Loads a Apache configuration and .htaccess files into a common handler, then parsed for directives like access restrictions and basic auth
     * TODO Load server-wide Apache Configuration then merge with Site Configuration
     */
    ApacheHandler htaccess = new ApacheHandler();
    response.setApacheParser(htaccess);

    try {
        boolean result = htaccess.handleDirectives(currentSite.getApacheConfig(), this);

        if (htaccess.overrideNone() || htaccess.overrideListNone()) // Ignore .htaccess files
        {
            if (fi.hasFile())
                if (!htaccess.handleDirectives(new ApacheConfiguration(fi.getFile().getParentFile()), this))
                    result = false;

            if (!htaccess.handleDirectives(new ApacheConfiguration(docRoot), this))
                result = false;
        }

        if (!result) {
            if (!response.isCommitted())
                response.sendError(500,
                        "Your request was blocked by an internal configuration directive, exact details are unknown.");
            return;
        }
    } catch (ApacheDirectiveException e) {
        log.log(Level.SEVERE, "Caught Apache directive exception: " + e.getMessage());

        // TODO Throw 500 unless told not to
    }
    /*
     * End: Apache Configuration Section
     */

    if (!fi.hasFile() && !fi.hasHTML())
        response.setStatus(HttpResponseStatus.NO_CONTENT);

    sess.setGlobal("__FILE__", fi.getFile());

    request.putRewriteParams(fi.getRewriteParams());
    response.setContentType(fi.getContentType());
    response.setEncoding(fi.getEncoding());

    request.getServer().put(ServerVars.DOCUMENT_ROOT, docRoot);

    request.setGlobal("_SERVER", request.getServer());
    request.setGlobal("_POST", request.getPostMap());
    request.setGlobal("_GET", request.getGetMap());
    request.setGlobal("_REWRITE", request.getRewriteMap());
    request.setGlobal("_FILES", request.getUploadedFiles());

    // TODO Implement NONCE requirement for login page
    NonceLevel level = NonceLevel.parse(fi.get("nonce"));
    boolean nonceProvided = sess.nonce() == null ? false
            : request.getRequestMap().get(sess.nonce().key()) != null;
    boolean processNonce = false;

    switch (level) {
    case Required:
        processNonce = true;
        break;
    case GetOnly:
        processNonce = request.method() == HttpMethod.GET || nonceProvided;
        break;
    case PostOnly:
        processNonce = request.method() == HttpMethod.POST || nonceProvided;
        break;
    case Flexible:
        processNonce = nonceProvided;
        break;
    case Disabled:
    default:
        // Do Nothing
    }

    Map<String, String> nonceMap = Maps.newHashMap();

    if (processNonce) {
        if (!nonceProvided) {
            log.log(Level.SEVERE,
                    "The request has failed NONCE validation, because the nonce key was not present!");
            response.sendError(HttpResponseStatus.FORBIDDEN, "Your request has failed NONCE validation!");
            return;
        }

        Nonce nonce = sess.nonce();

        if (level == NonceLevel.Required)
            // Required NonceLevels are of the highest protected state
            sess.destroyNonce();

        try {
            if (!(request.getRequestMap().get(nonce.key()) instanceof String))
                throw new NonceException("Nonce token is not a string");
            nonce.validateWithException((String) request.getRequestMap().get(nonce.key()));
        } catch (NonceException e) {
            log.log(Level.SEVERE,
                    "The request has failed NONCE validation, because " + e.getMessage().toLowerCase() + "!");
            response.sendError(HttpResponseStatus.FORBIDDEN, "Your request has failed NONCE validation!");
            sess.destroyNonce();
            return;
        } finally {
            log.log(Level.INFO, "The request has passed the NONCE validation!");
            request.nonceProcessed(true);
            nonceMap = nonce.mapValues();
        }
    }

    if (request.validateLogins())
        return;

    if (level != NonceLevel.Disabled)
        request.setGlobal("_NONCE", nonceMap);

    try {
        if (request.getUploadedFiles().size() > 0)
            log.log(Level.INFO,
                    "Uploads {"
                            + StringFunc.limitLength(
                                    Joiner.on(",").skipNulls().join(request.getUploadedFiles().values()), 255)
                            + "}");

        if (request.getGetMap().size() > 0)
            log.log(Level.INFO, "Params GET {" + StringFunc.limitLength(
                    Joiner.on(",").withKeyValueSeparator("=").useForNull("null").join(request.getGetMap()), 255)
                    + "}");

        if (request.getPostMap().size() > 0)
            log.log(Level.INFO, "Params POST {" + StringFunc.limitLength(
                    Joiner.on(",").withKeyValueSeparator("=").useForNull("null").join(request.getPostMap()),
                    255) + "}");

        if (request.getRewriteMap().size() > 0)
            log.log(Level.INFO, "Params REWRITE {" + StringFunc.limitLength(
                    Joiner.on(",").withKeyValueSeparator("=").useForNull("null").join(request.getRewriteMap()),
                    255) + "}");

        if (fi.getAnnotations().size() > 0)
            log.log(Level.INFO, "Params ANNOTATIONS {" + StringFunc.limitLength(
                    Joiner.on(",").withKeyValueSeparator("=").useForNull("null").join(fi.getAnnotations()), 255)
                    + "}");
    } catch (Throwable t) {
        t.printStackTrace();
    }

    if (AppConfig.get().getBoolean("advanced.security.requestMapEnabled", true))
        request.setGlobal("_REQUEST", request.getRequestMap());

    ByteBuf rendered = Unpooled.buffer();

    ScriptingFactory factory = request.getEvalFactory();
    factory.setEncoding(fi.getEncoding());

    NetworkSecurity.isForbidden(htaccess, currentSite, fi);

    String req = fi.get("reqperm");

    if (req == null)
        req = "-1";

    sess.requirePermission(req, currentSite.getId());

    // Enhancement: Allow HTML to be ran under different shells. Default is embedded.
    if (fi.hasHTML()) {
        ScriptingResult result = factory.eval(
                ScriptingContext.fromSource(fi.getHTML(), "<embedded>").request(request).site(currentSite));

        if (result.hasExceptions())
            // TODO Print notices to output like PHP does
            for (ScriptingException e : result.getExceptions()) {
                ExceptionReport.throwExceptions(e);
                log.exceptions(e);
                if (e.reportingLevel().isEnabled())
                    rendered.writeBytes(e.getMessage().getBytes());
            }

        if (result.isSuccessful()) {
            rendered.writeBytes(result.content());
            if (result.getObject() != null && !(result.getObject() instanceof NullObject))
                try {
                    rendered.writeBytes(ObjectFunc.castToStringWithException(result.getObject()).getBytes());
                } catch (Exception e) {
                    log.log(Level.SEVERE, "Exception Excountered: %s", e.getMessage());
                    if (Versioning.isDevelopment())
                        log.log(Level.SEVERE, e.getStackTrace()[0].toString());
                }
        }

        log.log(Level.INFO, "EvalHtml {timing=%sms,success=%s}", Timings.mark(this), result.isSuccessful());
    }

    if (fi.hasFile()) {
        if (fi.isDirectoryRequest()) {
            processDirectoryListing();
            return;
        }

        ScriptingResult result = factory.eval(ScriptingContext.fromFile(fi).request(request).site(currentSite));

        if (result.hasExceptions())
            // TODO Print notices to output like PHP does
            for (ScriptingException e : result.getExceptions()) {
                ExceptionReport.throwExceptions(e);
                log.exceptions(e);
                if (e.reportingLevel().isEnabled() && e.getMessage() != null)
                    rendered.writeBytes(e.getMessage().getBytes());
            }

        if (result.isSuccessful()) {
            rendered.writeBytes(result.content());
            if (result.getObject() != null && !(result.getObject() instanceof NullObject))
                try {
                    rendered.writeBytes(ObjectFunc.castToStringWithException(result.getObject()).getBytes());
                } catch (Exception e) {
                    rendered.writeBytes(result.getObject().toString().getBytes());
                    log.log(Level.SEVERE, "Exception encountered while writing returned object to output. %s",
                            e.getMessage());
                    if (Versioning.isDevelopment())
                        log.log(Level.SEVERE, e.getStackTrace()[0].toString());
                }
        }

        log.log(Level.INFO, "EvalFile {file=%s,timing=%sms,success=%s}", fi.getFilePath(), Timings.mark(this),
                result.isSuccessful());
    }

    // if the connection was in a MultiPart mode, wait for the mode to change then return gracefully.
    if (response.stage == HttpResponseStage.MULTIPART) {
        while (response.stage == HttpResponseStage.MULTIPART)
            // I wonder if there is a better way to handle multipart responses.
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new HttpError(500, "Internal Server Error encountered during multipart execution.");
            }

        return;
    }
    // If the connection was closed from page redirect, return gracefully.
    else if (response.stage == HttpResponseStage.CLOSED || response.stage == HttpResponseStage.WRITTEN)
        return;

    // Allows scripts to directly override interpreter values. For example: Themes, Views, Titles
    for (Entry<String, String> kv : response.annotations.entrySet())
        fi.put(kv.getKey(), kv.getValue());

    RenderEvent renderEvent = new RenderEvent(this, rendered, fi.getEncoding(), fi.getAnnotations());

    try {
        EventBus.instance().callEventWithException(renderEvent);
        if (renderEvent.getSource() != null)
            rendered = renderEvent.getSource();
    } catch (EventException ex) {
        throw new ScriptingException(ReportingLevel.E_ERROR,
                "Caught EventException while trying to fire the RenderEvent", ex.getCause());
    }

    log.log(Level.INFO, "Written {bytes=%s,total_timing=%sms}", rendered.readableBytes(), Timings.finish(this));

    try {
        response.write(rendered);
    } catch (IllegalReferenceCountException e) {
        log.log(Level.SEVERE, "Exception encountered while writting script object to output, %s",
                e.getMessage());
    }
}

From source file:com.cmz.http.upload.HttpUploadClient.java

License:Apache License

/**
 * Standard post without multipart but already support on Factory (memory management)
 *
 * @return the list of HttpData object (attribute and file) to be reused on next post
 *//*from  w  w w . ja v a  2s . co m*/
private static List<InterfaceHttpData> formpost(Bootstrap bootstrap, String host, int port, URI uriSimple,
        File file, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception {
    // XXX /formpost
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uriSimple.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false => not multipart

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute
    bodyRequestEncoder.addBodyAttribute("getform", "POST");
    bodyRequestEncoder.addBodyAttribute("info", "first value");
    bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue &");
    bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea);
    bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong);
    bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);

    // finalize request
    request = bodyRequestEncoder.finalizeRequest();

    // Create the bodylist to be reused on the last version with Multipart support
    List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked()
        // either do it through ChunkedWriteHandler
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Do not clear here since we will reuse the InterfaceHttpData on the next request
    // for the example (limit action on client side). Take this as a broadcast of the same
    // request on both Post actions.
    //
    // On standard program, it is clearly recommended to clean all files after each request
    // bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
    return bodylist;
}

From source file:com.cmz.http.upload.HttpUploadClient.java

License:Apache License

/**
 * Multipart example/*from   w w  w . ja v a  2  s .  c  o  m*/
 */
private static void formpostmultipart(Bootstrap bootstrap, String host, int port, URI uriFile,
        HttpDataFactory factory, Iterable<Entry<String, String>> headers, List<InterfaceHttpData> bodylist)
        throws Exception {
    // XXX /formpostmultipart
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uriFile.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, true); // true => multipart

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute from previous request in formpost()
    bodyRequestEncoder.setBodyHttpDatas(bodylist);

    // finalize request
    bodyRequestEncoder.finalizeRequest();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) {
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Now no more use of file representation (and list of HttpData)
    bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
}

From source file:com.corundumstudio.socketio.transport.PollingTransport.java

License:Apache License

private void handleMessage(FullHttpRequest req, UUID sessionId, QueryStringDecoder queryDecoder,
        ChannelHandlerContext ctx) throws IOException {
    String origin = req.headers().get(HttpHeaders.Names.ORIGIN);
    if (queryDecoder.parameters().containsKey("disconnect")) {
        ClientHead client = clientsBox.get(sessionId);
        client.onChannelDisconnect();/*w ww  .ja  va  2 s  . com*/
        ctx.channel().writeAndFlush(new XHRPostMessage(origin, sessionId));
    } else if (HttpMethod.POST.equals(req.getMethod())) {
        onPost(sessionId, ctx, origin, req.content());
    } else if (HttpMethod.GET.equals(req.getMethod())) {
        onGet(sessionId, ctx, origin);
    } else if (HttpMethod.OPTIONS.equals(req.getMethod())) {
        onOptions(sessionId, ctx, origin);
    } else {
        log.error("Wrong {} method invocation for {}", req.getMethod(), sessionId);
        sendError(ctx);
    }
}

From source file:com.corundumstudio.socketio.transport.XHRPollingTransport.java

License:Apache License

private void handleMessage(FullHttpRequest req, QueryStringDecoder queryDecoder, ChannelHandlerContext ctx)
        throws IOException {
    String[] parts = queryDecoder.path().split("/");
    if (parts.length > 3) {
        UUID sessionId = UUID.fromString(parts[4]);

        String origin = req.headers().get(HttpHeaders.Names.ORIGIN);
        if (queryDecoder.parameters().containsKey("disconnect")) {
            MainBaseClient client = sessionId2Client.get(sessionId);
            client.onChannelDisconnect();
            ctx.channel().writeAndFlush(new XHROutMessage(origin, sessionId));
        } else if (HttpMethod.POST.equals(req.getMethod())) {
            onPost(sessionId, ctx, origin, req.content());
        } else if (HttpMethod.GET.equals(req.getMethod())) {
            onGet(sessionId, ctx, origin);
        }//www.j  a v a2s  .com
    } else {
        log.warn("Wrong {} method request path: {}, from ip: {}. Channel closed!", req.getMethod(), path,
                ctx.channel().remoteAddress());
        ctx.channel().close();
    }
}

From source file:com.couchbase.client.core.endpoint.config.ConfigHandler.java

License:Apache License

@Override
protected HttpRequest encodeRequest(final ChannelHandlerContext ctx, final ConfigRequest msg) throws Exception {
    HttpMethod httpMethod = HttpMethod.GET;
    if (msg instanceof FlushRequest || msg instanceof InsertBucketRequest
            || msg instanceof UpdateBucketRequest) {
        httpMethod = HttpMethod.POST;
    } else if (msg instanceof RemoveBucketRequest) {
        httpMethod = HttpMethod.DELETE;/*from   w  w  w.  j  a  v  a2 s .c o m*/
    }

    ByteBuf content;
    if (msg instanceof InsertBucketRequest) {
        content = Unpooled.copiedBuffer(((InsertBucketRequest) msg).payload(), CharsetUtil.UTF_8);
    } else if (msg instanceof UpdateBucketRequest) {
        content = Unpooled.copiedBuffer(((UpdateBucketRequest) msg).payload(), CharsetUtil.UTF_8);
    } else {
        content = Unpooled.EMPTY_BUFFER;
    }

    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, msg.path(), content);
    request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent());
    if (msg instanceof InsertBucketRequest || msg instanceof UpdateBucketRequest) {
        request.headers().set(HttpHeaders.Names.ACCEPT, "*/*");
        request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
    }
    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
    request.headers().set(HttpHeaders.Names.HOST, remoteHttpHost(ctx));

    addHttpBasicAuth(ctx, request, msg.bucket(), msg.password());
    return request;
}