Example usage for io.netty.handler.codec.http.multipart HttpPostRequestDecoder getBodyHttpData

List of usage examples for io.netty.handler.codec.http.multipart HttpPostRequestDecoder getBodyHttpData

Introduction

In this page you can find the example usage for io.netty.handler.codec.http.multipart HttpPostRequestDecoder getBodyHttpData.

Prototype

@Override
    public InterfaceHttpData getBodyHttpData(String name) 

Source Link

Usage

From source file:com.bay1ts.bay.core.Request.java

License:Apache License

/**
 * ?Content-Type:application/x-www-form-urlencoded post body ?(htmlform)
 *
 * @param name ??form post inputname// ww w. j a  v a  2 s .c o m
 * @return value
 */
public String postBody(String name) {
    HttpPostRequestDecoder httpPostRequestDecoder = new HttpPostRequestDecoder(
            new DefaultHttpDataFactory(false), this.fullHttpRequest);
    InterfaceHttpData data = httpPostRequestDecoder.getBodyHttpData(name);
    if (data != null && data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
        Attribute attribute = (Attribute) data;
        String value = null;
        try {
            value = attribute.getValue();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            data.release();
        }
        return value;
    }
    return null;
}

From source file:com.cats.version.httpserver.VersionProtocolMessageHandler.java

License:Apache License

private String decodeMessage(FullHttpRequest request) throws IOException {
    HttpPostRequestDecoder httpPostRequestDecoder = new HttpPostRequestDecoder(request);
    InterfaceHttpData data = httpPostRequestDecoder.getBodyHttpData("msg");
    if (data.getHttpDataType() == HttpDataType.Attribute) {
        Attribute attribute = (Attribute) data;
        String strMsg = attribute.getValue();
        return strMsg;
    }/*from ww  w .  j a  v a  2s .  c  om*/
    return null;
}

From source file:com.digisky.outerproxy.server.OuterProxyHttpServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    LogMgr.debug("channelRead0()", "channelRead0");
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);//from ww  w .j a va 2  s. c  om
        }
    }
    if (msg instanceof HttpContent) {
        String type = request.getUri().split("/")[1];
        if (type.equals("email_activate") == true) { // GET?
            String[] tmp = request.getUri().split("=");
            String acode = tmp[tmp.length - 1];
            LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + acode);
            ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"acode\":\"" + acode + "\"}");
            return;
        } else if (type.equals("email_pwd_reset") == true) { //?
            String[] tmp = request.getUri().split("=");
            String vcode = tmp[tmp.length - 1];
            LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + vcode);
            ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"vcode\":\"" + vcode + "\"}");
            return;
        }

        //email_active  email_pwd_reset, 
        //???
        HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request);
        InterfaceHttpData postData = decoder.getBodyHttpData("val");
        if (postData instanceof FileUpload == false) {//outerProxy????
            ctx.close();
            return;
        }
        FileUpload binData = (FileUpload) postData;
        ByteBuf content = null;
        try {
            content = binData.getByteBuf();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //content??. , 0. ?(head)?id, json?, ?. ??, ???. 
        //?content?head
        int index = content.bytesBefore((byte) 0);
        if (index < 0) {
            LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "ellegal request.");
            ctx.channel().close();
            return;
        }
        byte[] head = new byte[index];
        content.readBytes(head);
        String strHead = new String(head);
        LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "head:" + strHead);
        JSONObject jo = JSONObject.parseObject(strHead);
        LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),
                "jo::app_id:" + jo.getString("app_id") + " jo::version:" + jo.getString("version"));
        content.readByte();//0

        //?content?tail
        byte[] tail = new byte[content.readableBytes()];
        content.readBytes(tail);
        String sjsonmsg = null;
        if (jo.getString("version").equals("0")) { //?0
            byte[] bjsonmsg = XXTEA.decrypt(tail, key);
            int data_len = bjsonmsg.length;
            for (int i = bjsonmsg.length - 1; i != 0; --i) {
                if (bjsonmsg[i] == 0) {
                    data_len--;
                    continue;
                } else {
                    break;
                }
            }
            try {
                sjsonmsg = new String(bjsonmsg, 0, data_len, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else { //TODO?0, app_id. ???
            LogMgr.error(OuterProxyHttpServerHandler.class.getName(),
                    "?0, ??");
            ctx.close();
            return;
        }
        sjsonmsg = sjsonmsg.substring(sjsonmsg.indexOf('{'), sjsonmsg.indexOf('}') + 1);//?
        LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "sjson:" + sjsonmsg);

        //debug code
        //JSONObject jsonObj = JSONObject.parseObject(sjsonmsg);
        //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "tmp.get:" + jsonObj.getString("model"));

        /* debug code
        //b.getBytes(n+1, tail, 0, b.g-n-1);
        for(int i=0; i< tail.length; ++i) {
           System.out.print(String.format("%x ", tail[i]));
        }
        */

        //debug code
        //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "uri:" + request.getUri());
        //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"method:" + request.getMethod());
        //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"type:" + type);
        LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "json:" + sjsonmsg);

        //
        ProcessServerManager.getInstance().process(ctx.channel(), type, sjsonmsg);
    }
}

From source file:com.stremebase.examples.todomvc.HttpRouter.java

License:Apache License

private static HttpResponse createResponse(HttpRequest req, Router<Integer> router) {
    RouteResult<Integer> routeResult = router.route(req.getMethod(), req.getUri());

    Integer request = routeResult.target();

    String data = "";
    String mimeType = "";

    if (request == CSS) {
        data = Todo.getCss();/*from w w w.j  ava2  s  .c o  m*/
        mimeType = "text/css";
    } else if (request == ICON) {
        mimeType = "image/x-icon";
    } else if (request == GET) {
        data = Todo.get();
        mimeType = "text/html";
    } else if (request == FILTER) {
        data = Todo.filter(routeResult.pathParams().get("filtertype"));
        mimeType = "text/html";
    } else if (req.getMethod().equals(HttpMethod.POST)) {
        HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), req);

        Attribute attribute;

        String item_text = null;
        InterfaceHttpData httpData = decoder.getBodyHttpData("item-text");
        if (httpData != null) {
            attribute = (Attribute) httpData;
            try {
                item_text = attribute.getValue();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String item_id = null;
        httpData = decoder.getBodyHttpData("item-id");
        if (httpData != null) {
            attribute = (Attribute) httpData;
            try {
                item_id = attribute.getValue();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (request == POST) {
            if (item_id == null)
                data = Todo.create(item_text);
            else
                data = Todo.save(Long.valueOf(item_id), item_text);
        } else if (request == DELETE) {
            data = Todo.delete(Long.valueOf(item_id));
        } else if (request == DELETECOMPLETED) {
            data = Todo.clearCompleted();
        } else if (request == TOGGLESTATUS)
            data = Todo.toggleStatus(Long.valueOf(item_id));

        mimeType = "text/html";
        decoder.destroy();
    }

    FullHttpResponse res;

    if (request == NOTFOUND) {
        res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT);
        res.headers().add(HttpHeaders.Names.LOCATION, "/");
        return res;
    }

    if (request == ICON)
        res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                Unpooled.copiedBuffer(Todo.favicon));
    else
        res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                Unpooled.copiedBuffer(data, CharsetUtil.UTF_8));

    res.headers().set(HttpHeaders.Names.CONTENT_TYPE, mimeType);
    res.headers().set(HttpHeaders.Names.CONTENT_LENGTH, res.content().readableBytes());
    if (request == CSS || request == ICON)
        setDateAndCacheHeaders(res);

    return res;
}

From source file:net.mms_projects.copy_it.api.http.pages.android.RegisterGCM.java

License:Open Source License

public FullHttpResponse onPostRequest(final HttpRequest request,
        final HttpPostRequestDecoder postRequestDecoder, final Database database,
        final HeaderVerifier headerVerifier) throws Exception {
    if ((headerVerifier.getConsumerFlags() & Consumer.Flags.GCM) != Consumer.Flags.GCM)
        throw new ErrorException(YOU_SHOULD_NOT_USE_THIS);
    InterfaceHttpData gcm_token = postRequestDecoder.getBodyHttpData(GCM_TOKEN);
    if (gcm_token != null && gcm_token instanceof HttpData) {
        final String gcm_id = ((HttpData) gcm_token).getString();
        if (gcm_id.length() < 256) {
            GCMRunnable gcmRunnable = new GCMRunnable();
            gcmRunnable.addRegistrationId(gcm_id);
            gcmRunnable.setDryRun();//from w  w w . j a v  a  2  s . co  m
            JSONObject output = gcmRunnable.send();
            if (output.optInt(SUCCESS, 0) == 1) {
                PreparedStatement statement = database.getConnection().prepareStatement(INSERT_STATEMENT);
                statement.setInt(1, headerVerifier.getUserId());
                statement.setString(2, gcm_id);
                if (statement.executeUpdate() > 0)
                    database.getConnection().commit();
                JSONObject json = new JSONObject();
                return new DefaultFullHttpResponse(request.getProtocolVersion(), OK,
                        Unpooled.copiedBuffer(json.toString(), CharsetUtil.UTF_8));
            } else {
                String error = output.getJSONArray(RESULTS).getJSONObject(0).getString(ERROR);
                throw new ErrorException(error);
            }
        } else
            throw new ErrorException(GCM_TOKEN_TOO_LONG);
    } else
        throw new ErrorException(MISSING_GCM_TOKEN);
}

From source file:net.mms_projects.copy_it.api.http.pages.android.UnRegisterGCM.java

License:Open Source License

public FullHttpResponse onPostRequest(final HttpRequest request,
        final HttpPostRequestDecoder postRequestDecoder, final Database database,
        final HeaderVerifier headerVerifier) throws Exception {
    if ((headerVerifier.getConsumerFlags() & Consumer.Flags.GCM) != Consumer.Flags.GCM)
        throw new ErrorException(YOU_SHOULD_NOT_USE_THIS);
    InterfaceHttpData gcm_token = postRequestDecoder.getBodyHttpData(GCM_TOKEN);
    if (gcm_token != null && gcm_token instanceof HttpData) {
        final String gcm_id = ((HttpData) gcm_token).getString();
        System.err.println(gcm_id);
        if (gcm_id.length() < 256) {
            PreparedStatement statement = database.getConnection().prepareStatement(INSERT_STATEMENT);
            statement.setInt(1, headerVerifier.getUserId());
            statement.setString(2, gcm_id);
            if (statement.executeUpdate() > 0)
                database.getConnection().commit();
            JSONObject json = new JSONObject();
            return new DefaultFullHttpResponse(request.getProtocolVersion(), OK,
                    Unpooled.copiedBuffer(json.toString(), CharsetUtil.UTF_8));
        } else/*from  w w w .j  a v a 2  s . c  o  m*/
            throw new ErrorException(GCM_TOKEN_TOO_LONG);
    } else
        throw new ErrorException(MISSING_GCM_TOKEN);
}

From source file:net.mms_projects.copy_it.api.http.pages.oauth.Authorize.java

License:Open Source License

public FullHttpResponse onPostRequest(HttpRequest request, HttpPostRequestDecoder postRequestDecoder,
        Database database) throws Exception {
    final QueryStringDecoder querydecoder = new QueryStringDecoder(new URI(request.getUri()));
    Map<String, List<String>> parameters = querydecoder.parameters();
    if (!parameters.containsKey(OAUTH_TOKEN))
        throw new ErrorException(MISSING_OAUTH_TOKEN);
    final String oauth_token = parameters.get(OAUTH_TOKEN).get(0);
    final InterfaceHttpData session_raw = postRequestDecoder.getBodyHttpData(SESSION);
    if (session_raw == null || !(session_raw instanceof HttpData))
        throw new ErrorException(MISSING_SESSION);
    final String session = ((HttpData) session_raw).getString();
    try {/* w w w  .j av  a  2 s  . co  m*/
        PreparedStatement get_email = database.getConnection().prepareStatement(GET_EMAIL_FROM_SESSION);
        get_email.setString(1, session);
        ResultSet email = get_email.executeQuery();
        if (email.first()) {
            final String email_address = email.getString(EMAIL);
            email.close();
            PreparedStatement cleanup_session = database.getConnection().prepareStatement(DELETE_SESSION);
            cleanup_session.setString(1, session);
            cleanup_session.executeUpdate();
            PreparedStatement create_user = database.getConnection().prepareStatement(CREATE_USER);
            create_user.setString(1, email_address);
            create_user.executeUpdate();
            PreparedStatement update = database.getConnection().prepareStatement(UPDATE_USER_ID);
            update.setString(1, email_address);
            update.setString(2, oauth_token);
            if (update.executeUpdate() == 1) {
                database.getConnection().commit();
                PreparedStatement statement = database.getConnection().prepareStatement(SELECT_CALLBACK);
                statement.setString(1, oauth_token);
                ResultSet result = statement.executeQuery();
                if (result.first()) {
                    final String callback = result.getString(CALLBACK_URI);
                    final String verifier = result.getString(VERIFIER);
                    result.close();
                    final StringBuilder output = new StringBuilder();
                    output.append(callback);
                    output.append(CALLBACK_URI_PARAMETER);
                    output.append(verifier);
                    DefaultFullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(),
                            MOVED_PERMANENTLY);
                    HttpHeaders.addHeader(response, HttpHeaders.Names.LOCATION, output.toString());
                    return response;
                } else {
                    result.close();
                    throw new ErrorException(INVALID_TOKEN);
                }
            }
        }
        email.close();
        throw new ErrorException(WE_MADE_A_BOO_BOO);
    } catch (NumberFormatException e) {
        throw new ErrorException(USER_ID_NOT_A_NUMBER);
    }
}

From source file:net.mms_projects.copy_it.api.http.pages.thirdpartyauth.GooglePlusAuth.java

License:Open Source License

public FullHttpResponse onPostRequest(HttpRequest request, HttpPostRequestDecoder postRequestDecoder,
        Database database) throws Exception {
    final InterfaceHttpData code_raw = postRequestDecoder.getBodyHttpData(CODE);
    if (code_raw == null || !(code_raw instanceof HttpData))
        throw new ErrorException(MISSING_CODE_PARAMETER);
    final String code = ((HttpData) code_raw).getString();
    Tokeninfo verified = checkCode(code);
    if (verified.getVerifiedEmail() && verified.getEmail() != null) {
        JSONObject json = new JSONObject();
        json.put(SESSION, generateCookie(verified.getEmail(), database));
        return new DefaultFullHttpResponse(request.getProtocolVersion(), OK,
                Unpooled.copiedBuffer(json.toString(), CharsetUtil.UTF_8));
    } else/*from   w ww.jav a  2  s.  co  m*/
        throw new ErrorException(GOOGLE_AUTH_FAILED);
}

From source file:net.mms_projects.copy_it.api.http.pages.thirdpartyauth.PersonaAuth.java

License:Open Source License

public FullHttpResponse onPostRequest(HttpRequest request, HttpPostRequestDecoder postRequestDecoder,
        Database database) throws Exception {
    final InterfaceHttpData assertion_raw = postRequestDecoder.getBodyHttpData(ASSERTION);
    if (assertion_raw == null || !(assertion_raw instanceof HttpData))
        throw new ErrorException(MISSING_ASSERTION);
    final String assertion = ((HttpData) assertion_raw).getString();
    JSONObject verified = verifyAssertion(assertion);
    if (verified.has(EMAIL) && verified.has(STATUS) && OKAY.equals(verified.getString(STATUS))) {
        JSONObject json = new JSONObject();
        json.put(SESSION, generateCookie(verified.getString(EMAIL), database));
        return new DefaultFullHttpResponse(request.getProtocolVersion(), OK,
                Unpooled.copiedBuffer(json.toString(), CharsetUtil.UTF_8));
    } else//from  ww  w  . j  a v a  2s  . c  o m
        throw new ErrorException(PERSONA_AUTH_FAILED);
}

From source file:net.mms_projects.copy_it.api.http.pages.v1.ClipboardUpdate.java

License:Open Source License

public FullHttpResponse onPostRequest(final HttpRequest request,
        final HttpPostRequestDecoder postRequestDecoder, final Database database,
        final HeaderVerifier headerVerifier) throws Exception {
    if (!headerVerifier.getConsumerScope().canWrite() || !headerVerifier.getUserScope().canWrite())
        throw new ErrorException(NO_WRITE_PERMISSION);
    final InterfaceHttpData data = postRequestDecoder.getBodyHttpData("data");
    if (data == null)
        throw new ErrorException(MISSING_DATA_PARAMETER);
    if (data instanceof HttpData) {
        PreparedStatement statement = database.getConnection().prepareStatement(INSERT_DATA);
        statement.setInt(1, headerVerifier.getUserId());
        statement.setString(2, ((HttpData) data).getString());
        statement.execute();//from  w ww. j  av  a 2 s.  c o m
    } else
        throw new ErrorException(MISSING_DATA_PARAMETER);
    dispatchNotification(database, headerVerifier.getUserId());
    final JSONObject json = new JSONObject();
    return new DefaultFullHttpResponse(request.getProtocolVersion(), OK,
            Unpooled.copiedBuffer(json.toString(), CharsetUtil.UTF_8));
}