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:org.ireland.jnetty.http.HttpServletRequestImpl.java

License:Open Source License

/**
 * Extract Parameters from query string and form HttpServletRequestImpl Body(application/x-www-form-urlencoded [POST
 * | PUT])/*from w  ww .  j  a  v  a2 s .  co m*/
 */
public void extractParameters() {

    if (_paramsExtracted)
        return;

    _paramsExtracted = true;

    if (_parameters == null)
        _parameters = new HashMap<String, List<String>>();

    // Handle query string

    if (_queryEncoding == null) {
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());

        _parameters.putAll(queryStringDecoder.parameters());

    } else {
        try {
            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri(),
                    Charset.forName(_queryEncoding));

            _parameters.putAll(queryStringDecoder.parameters());

        } catch (UnsupportedCharsetException e) {
            if (LOG.isDebugEnabled())
                LOG.warn(e);
            else
                LOG.warn(e.toString());
        }
    }

    // handle form _content (application/x-www-form-urlencoded)
    String encoding = getCharacterEncoding();
    String content_type = getContentType();

    if (content_type != null && content_type.length() > 0) {
        content_type = ContentTypeUtil.getContentTypeWithoutCharset(content_type);

        // application/x-www-form-urlencoded( POST or PUT )
        if (HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED.equals(content_type)
                && (HttpMethod.POST.name().equals(getMethod()) || HttpMethod.PUT.name().equals(getMethod()))) {
            int content_length = getContentLength();
            if (content_length > 0) {
                try {
                    Charset bodyCharset = Charset.forName(encoding);
                    String bodyContent = new String(getRowBodyContent(), bodyCharset);

                    // Add form params to query params
                    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(bodyContent, bodyCharset,
                            false);

                    if (_parameters == null)
                        _parameters = queryStringDecoder.parameters();
                    else//merge
                    {
                        Map<String, List<String>> map = queryStringDecoder.parameters();

                        for (Entry<String, List<String>> e : map.entrySet()) {
                            if (!_parameters.containsKey(e.getKey())) {
                                _parameters.put(e.getKey(), e.getValue());
                            } else// parameter with the same name exist,merge
                            {
                                List<String> value = _parameters.get(e.getKey());

                                if (value == null)
                                    _parameters.put(e.getKey(), e.getValue());
                                else {
                                    value.addAll(e.getValue()); // merge
                                    _parameters.put(e.getKey(), value);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    if (LOG.isDebugEnabled())
                        e.printStackTrace();
                    else
                        LOG.warn(e.toString());
                }
            }
        }
    }
}

From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.handler.HttpHMACAuthenticationHandlerTest.java

License:Apache License

@Test
public void testChannelReadBasicAuthNoAuthHeader() {
    final ChannelHandlerContext ctx = createMock(ChannelHandlerContext.class);
    final FullHttpRequest msg = createMock(FullHttpRequest.class);
    final HttpHeaders headers = createMock(HttpHeaders.class);
    final Authenticator authenticator = createMock(Authenticator.class);
    final ChannelFuture cf = createMock(ChannelFuture.class);

    expect(msg.getMethod()).andReturn(HttpMethod.POST);
    expect(msg.headers()).andReturn(headers).anyTimes();
    expect(headers.get(eq("Authorization"))).andReturn(null);
    expect(ctx.writeAndFlush(eqHttpStatus(UNAUTHORIZED))).andReturn(cf);
    expect(cf.addListener(ChannelFutureListener.CLOSE)).andReturn(null);
    expect(msg.release()).andReturn(false);
    HttpHMACAuthenticationHandler handler = new HttpHMACAuthenticationHandler(authenticator);
    replayAll();/*from w  w  w . ja  va2s . c  om*/
    handler.channelRead(ctx, (Object) msg);
    verifyAll();
}

From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.handler.HttpHMACAuthenticationHandlerTest.java

License:Apache License

@Test
public void testChannelReadBasicAuthIncorrectScheme() {
    final ChannelHandlerContext ctx = createMock(ChannelHandlerContext.class);
    final FullHttpRequest msg = createMock(FullHttpRequest.class);
    final HttpHeaders headers = createMock(HttpHeaders.class);
    final Authenticator authenticator = createMock(Authenticator.class);
    final ChannelFuture cf = createMock(ChannelFuture.class);

    expect(msg.getMethod()).andReturn(HttpMethod.POST);
    expect(msg.headers()).andReturn(headers).anyTimes();
    expect(headers.get("Authorization")).andReturn("bogus");
    expect(ctx.writeAndFlush(eqHttpStatus(UNAUTHORIZED))).andReturn(cf);
    expect(cf.addListener(ChannelFutureListener.CLOSE)).andReturn(null);
    expect(msg.release()).andReturn(false);

    final HttpHMACAuthenticationHandler handler = new HttpHMACAuthenticationHandler(authenticator);
    replayAll();//  w  w  w  .  j  a  va 2s.  c o  m
    handler.channelRead(ctx, (Object) msg);
    verifyAll();
}

From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.handler.HttpHMACAuthenticationHandlerTest.java

License:Apache License

@Test
public void testChannelReadBasicAuth() throws Exception {
    final ChannelHandlerContext ctx = createMock(ChannelHandlerContext.class);
    final FullHttpRequest msg = createMock(FullHttpRequest.class);
    final HttpHeaders headers = createMock(HttpHeaders.class);
    final Authenticator authenticator = createMock(Authenticator.class);
    final String encodedUserNameAndPass = Base64.getEncoder().encodeToString("user:pass".getBytes());
    expect(msg.getMethod()).andReturn(HttpMethod.POST);
    expect(msg.headers()).andReturn(headers).anyTimes();
    expect(msg.getUri()).andReturn("/");
    expect(headers.get(eq("Authorization"))).andReturn("Basic " + encodedUserNameAndPass);
    expect(ctx.fireChannelRead(isA(FullHttpRequest.class))).andReturn(ctx);
    expect(authenticator.authenticate(isA(Map.class))).andReturn(new AuthenticatedUser("foo"));
    final HttpHMACAuthenticationHandler handler = new HttpHMACAuthenticationHandler(authenticator);
    replayAll();/*from w  w w  . jav a  2 s  .  c om*/
    handler.channelRead(ctx, (Object) msg);
    verifyAll();
}

From source file:org.jboss.aerogear.simplepush.server.netty.SimplePushSockJSServiceTest.java

License:Apache License

private FullHttpRequest httpPostRequest(final String path) {
    return new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, path);
}

From source file:org.jooby.internal.netty.NettyRequest.java

License:Apache License

private Multimap<String, String> decodeParams() throws IOException {
    if (params == null) {
        params = ArrayListMultimap.create();
        files = ArrayListMultimap.create();

        query.parameters().forEach((name, values) -> values.forEach(value -> params.put(name, value)));

        HttpMethod method = req.method();
        boolean hasBody = method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT)
                || method.equals(HttpMethod.PATCH);
        boolean formLike = false;
        if (req.headers().contains("Content-Type")) {
            String contentType = req.headers().get("Content-Type").toLowerCase();
            formLike = (contentType.startsWith(MediaType.multipart.name())
                    || contentType.startsWith(MediaType.form.name()));
        }/*from w  ww.  j a  va2  s .co m*/
        if (hasBody && formLike) {
            HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(), req);
            try {
                Function<HttpPostRequestDecoder, Boolean> hasNext = it -> {
                    try {
                        return it.hasNext();
                    } catch (HttpPostRequestDecoder.EndOfDataDecoderException ex) {
                        return false;
                    }
                };
                while (hasNext.apply(decoder)) {
                    HttpData field = (HttpData) decoder.next();
                    try {
                        String name = field.getName();
                        if (field.getHttpDataType() == HttpDataType.FileUpload) {
                            files.put(name, new NettyUpload((FileUpload) field, tmpdir));
                        } else {
                            params.put(name, field.getString());
                        }
                    } finally {
                        field.release();
                    }
                }
            } finally {
                decoder.destroy();
            }
        }
    }
    return params;
}

From source file:org.kaaproject.kaa.server.transports.http.transport.netty.RequestDecoder.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject httpObject) throws Exception {

    DecoderResult result = httpObject.getDecoderResult();
    if (!result.isSuccess()) {
        throw new BadRequestException(result.cause());
    }/*from  ww w.  j  av  a2s .  c om*/

    Attribute<UUID> sessionUuidAttr = ctx.channel().attr(AbstractNettyServer.UUID_KEY);

    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;
        LOG.trace("Session: {} got valid HTTP request:\n{}", sessionUuidAttr.get().toString(),
                httpRequest.headers().toString());
        if (httpRequest.getMethod().equals(HttpMethod.POST)) {
            String uri = httpRequest.getUri();
            AbstractCommand cp = (AbstractCommand) commandFactory.getCommandProcessor(uri);
            cp.setSessionUuid(sessionUuidAttr.get());
            cp.setRequest(httpRequest);
            cp.parse();
            ctx.fireChannelRead(cp);
        } else {
            LOG.error("Got invalid HTTP method: expecting only POST");
            throw new BadRequestException(
                    "Incorrect method " + httpRequest.getMethod().toString() + ", expected POST");
        }
    } else {
        LOG.warn("Session: {} got invalid HTTP object:\n{}", sessionUuidAttr.get().toString(), httpObject);
    }
}

From source file:org.kaaproject.kaa.server.transports.http.transport.netty.RequestDecoderTest.java

License:Apache License

@Test
public void httpPostRequestTest() throws Exception {
    HttpObject request = createHttpRequestMock(HttpMethod.POST, true, HttpRequest.class);
    requestDecoder.channelRead0(channelHandlerContext, request);
    verify(channelHandlerContext).fireChannelRead(any(Object.class));
}

From source file:org.kaaproject.kaa.server.transports.http.transport.netty.RequestDecoderTest.java

License:Apache License

@Test
public void nonHttpRequestObjectTest() throws Exception {
    HttpObject request = createHttpRequestMock(HttpMethod.POST, true, HttpObject.class);
    requestDecoder.channelRead0(channelHandlerContext, request);
    verify(channelHandlerContext, never()).fireChannelRead(any(Object.class));
}

From source file:org.knoxcraft.netty.server.HttpUploadServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    try {//w w  w  .  j a  v  a2  s .c  o  m
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest fullRequest = (FullHttpRequest) msg;
            if (fullRequest.getUri().startsWith("/kctupload")) {

                if (fullRequest.getMethod().equals(HttpMethod.GET)) {
                    // HTTP Get request!
                    // Write the HTML page with the form
                    writeMenu(ctx);
                } else if (fullRequest.getMethod().equals(HttpMethod.POST)) {
                    /* 
                     * HTTP Post request! Handle the uploaded form
                     * HTTP parameters:
                            
                    /kctupload
                    username (should match player's Minecraft name)
                    language (java, python, etc)
                    jsonfile (a file upload, or empty)
                    sourcefile (a file upload, or empty)
                    jsontext (a JSON string, or empty)
                    sourcetext (code as a String, or empty)
                     */

                    String language = null;
                    String playerName = null;
                    String client = null;
                    String jsonText = null;
                    String sourceText = null;
                    Map<String, UploadedFile> files = new LinkedHashMap<String, UploadedFile>();

                    HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(fullRequest);
                    try {
                        logger.trace("is multipart? " + decoder.isMultipart());
                        while (decoder.hasNext()) {
                            InterfaceHttpData data = decoder.next();
                            if (data == null)
                                continue;

                            try {
                                if (data.getHttpDataType() == HttpDataType.Attribute) {
                                    Attribute attribute = (Attribute) data;
                                    String name = attribute.getName();
                                    String value = attribute.getValue();
                                    logger.trace(String.format("http attribute: %s => %s", name, value));
                                    if (name.equals("language")) {
                                        language = value;
                                    } else if (name.equals("playerName")) {
                                        playerName = value;
                                    } else if (name.equals("client")) {
                                        client = value;
                                    } else if (name.equals("jsontext")) {
                                        jsonText = value;
                                    } else if (name.equals("sourcetext")) {
                                        sourceText = value;
                                    } else {
                                        logger.warn(String.format("Unknown kctupload attribute: %s => %s", name,
                                                value));
                                    }
                                } else if (data.getHttpDataType() == HttpDataType.FileUpload) {
                                    // Handle file upload
                                    // We may have json, source, or both
                                    FileUpload fileUpload = (FileUpload) data;
                                    logger.debug(String.format("http file upload name %s, filename: ",
                                            data.getName(), fileUpload.getFilename()));
                                    String filename = fileUpload.getFilename();
                                    ByteBuf buf = fileUpload.getByteBuf();
                                    String fileBody = new String(buf.array(), "UTF-8");
                                    files.put(data.getName(), new UploadedFile(filename, fileBody));
                                }
                            } finally {
                                data.release();
                            }
                        }
                    } finally {
                        if (decoder != null) {
                            // clean up resources
                            decoder.cleanFiles();
                            decoder.destroy();
                        }
                    }

                    /*
                     * Error checking here makes the most sense, since we can send back a reasonable error message
                     * to the uploading client at this point. Makes less sense to wait to compile.
                     * 
                     * Upload possibilities:
                     * 
                     * bluej: file1, file2, etc. All source code. Language should be set to Java.
                     * Convert to JSON, then to KCTScript. Signal an error if one happens.
                     * 
                     * web: jsontext and/or sourcetext. json-only is OK; source-only is OK if it's Java. 
                     * Cannot send source-only for non-Java languages, since we can't build them (yet).
                     * 
                     * anything else: convert to Json and hope for the best
                     */
                    try {
                        KCTUploadHook hook = new KCTUploadHook();
                        StringBuilder res = new StringBuilder();

                        if (playerName == null || playerName.equals("")) {
                            // XXX How do we know that the playerName is valid?
                            // TODO: authenticate against Mojang's server?
                            throw new TurtleException("You must specify your MineCraft player name!");
                        }

                        if (client == null) {
                            throw new TurtleException("Your uploading and submission system must specify "
                                    + "the type of client used for the upload (i.e. bluej, web, pykc, etc)");
                        }

                        hook.setPlayerName(playerName);
                        res.append(
                                String.format("Hello %s! Thanks for using KnoxCraft Turtles\n\n", playerName));

                        TurtleCompiler turtleCompiler = new TurtleCompiler(logger);
                        int success = 0;
                        int failure = 0;
                        if (client.equalsIgnoreCase("web") || client.equalsIgnoreCase("testclient")
                                || client.startsWith("pykc")) {
                            // WEB OR PYTHON UPLOAD
                            logger.trace("Upload from web");
                            // must have both Json and source, either in text area or as uploaded files
                            //XXX Conlfict of comments of the top and here??? What do we need both/ only JSon?
                            //Is there a want we want, thus forcing it
                            if (sourceText != null && jsonText != null) {
                                KCTScript script = turtleCompiler.parseFromJson(jsonText);
                                script.setLanguage(language);
                                script.setSourceCode(sourceText);
                                res.append(String.format(
                                        "Successfully uploaded KnoxCraft Turtle program "
                                                + "named %s, in programming language %s\n",
                                        script.getScriptName(), script.getLanguage()));
                                success++;
                                hook.addScript(script);
                            } else if (files.containsKey("jsonfile") && files.containsKey("sourcefile")) {
                                UploadedFile sourceUpload = files.get("sourcefile");
                                UploadedFile jsonUpload = files.get("jsonfile");
                                KCTScript script = turtleCompiler.parseFromJson(jsonUpload.body);
                                script.setLanguage(language);
                                script.setSourceCode(sourceUpload.body);
                                res.append(String.format(
                                        "Successfully uploaded KnoxCraft Turtle program "
                                                + "named %s, in programming language %s\n",
                                        script.getScriptName(), script.getLanguage()));
                                success++;
                                hook.addScript(script);
                            } else {
                                throw new TurtleException(
                                        "You must upload BOTH json and the corresponding source code "
                                                + " (either as files or pasted into the text areas)");
                            }
                        } else if ("bluej".equalsIgnoreCase(client)) {
                            // BLUEJ UPLOAD
                            logger.trace("Upload from bluej");
                            for (Entry<String, UploadedFile> entry : files.entrySet()) {
                                try {
                                    UploadedFile uploadedFile = entry.getValue();
                                    res.append(String.format("Trying to upload and compile file %s\n",
                                            uploadedFile.filename));
                                    logger.trace(String.format("Trying to upload and compile file %s\n",
                                            uploadedFile.filename));
                                    KCTScript script = turtleCompiler
                                            .compileJavaTurtleCode(uploadedFile.filename, uploadedFile.body);
                                    logger.trace("Returned KCTScript (it's JSON is): " + script.toJSONString());
                                    hook.addScript(script);
                                    res.append(String.format(
                                            "Successfully uploaded file %s and compiled KnoxCraft Turtle program "
                                                    + "named %s in programming language %s\n\n",
                                            uploadedFile.filename, script.getScriptName(),
                                            script.getLanguage()));
                                    success++;
                                } catch (TurtleCompilerException e) {
                                    logger.warn("Unable to compile Turtle code", e);
                                    res.append(String.format("%s\n\n", e.getMessage()));
                                    failure++;
                                } catch (TurtleException e) {
                                    logger.error("Error in compiling (possibly a server side error)", e);
                                    res.append(String.format("Unable to process Turtle code %s\n\n",
                                            e.getMessage()));
                                    failure++;
                                } catch (Exception e) {
                                    logger.error("Unexpected error compiling Turtle code to KCTScript", e);
                                    failure++;
                                    res.append(String.format("Failed to load script %s\n", entry.getKey()));
                                }
                            }
                        } else {
                            // UNKNOWN CLIENT UPLOAD
                            // TODO Unknown client; make a best effort to handle upload
                            res.append(String.format(
                                    "Unknown upload client: %s; making our best effort to handle the upload"));
                        }

                        res.append(String.format("\nSuccessfully uploaded %d KnoxCraft Turtles programs\n",
                                success));
                        if (failure > 0) {
                            res.append(String.format("\nFailed to upload %d KnoxCraft Turtles programs\n",
                                    failure));
                        }
                        Canary.hooks().callHook(hook);
                        writeResponse(ctx.channel(), fullRequest, res.toString(), client);
                    } catch (TurtleException e) {
                        // XXX can this still happen? Don't we catch all of these?
                        writeResponse(ctx.channel(), fullRequest, e.getMessage(), "error");
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error("Internal Server Error: Channel error", e);
        throw e;
    }
}