Example usage for io.netty.handler.codec.http QueryStringDecoder parameters

List of usage examples for io.netty.handler.codec.http QueryStringDecoder parameters

Introduction

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

Prototype

public Map<String, List<String>> parameters() 

Source Link

Document

Returns the decoded key-value parameter pairs of the URI.

Usage

From source file:io.vertx.core.http.impl.HttpUtils.java

License:Open Source License

static MultiMap params(String uri) {
    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri);
    Map<String, List<String>> prms = queryStringDecoder.parameters();
    MultiMap params = new CaseInsensitiveHeaders();
    if (!prms.isEmpty()) {
        for (Map.Entry<String, List<String>> entry : prms.entrySet()) {
            params.add(entry.getKey(), entry.getValue());
        }//  w w  w  . j  ava 2 s. c  om
    }
    return params;
}

From source file:io.vertx.ext.shell.term.impl.SockJSTtyConnection.java

License:Open Source License

private static Vector getInitialSize(SockJSSocket socket) {
    QueryStringDecoder decoder = new QueryStringDecoder(socket.uri());
    Map<String, List<String>> params = decoder.parameters();
    try {//from  w  w  w .  jav  a2 s . co m
        int cols = getParamValue(params, "cols", 80);
        int rows = getParamValue(params, "rows", 24);
        return new Vector(cols, rows);
    } catch (Exception e) {
        return new Vector(80, 24);
    }
}

From source file:io.vertx.ext.web.client.impl.HttpRequestImpl.java

License:Open Source License

@Override
public MultiMap queryParams() {
    if (params == null) {
        params = new CaseInsensitiveHeaders();
    }/* w  ww .  j  av  a  2 s .c om*/
    if (params.isEmpty()) {
        int idx = uri.indexOf('?');
        if (idx >= 0) {
            QueryStringDecoder dec = new QueryStringDecoder(uri);
            dec.parameters().forEach((name, value) -> params.add(name, value));
            uri = uri.substring(0, idx);
        }
    }
    return params;
}

From source file:me.zhuoran.amoeba.netty.server.http.AmoebaHttpRequest.java

License:Apache License

public AmoebaHttpRequest(HttpRequest request, String channelId) {
    if (request != null && channelId != null) {
        this.httpRequest = request;
        this.uri = request.getUri();
        this.method = request.getMethod().toString();
        if (this.getMethod().equals("GET")) {
            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
            this.params = queryStringDecoder.parameters();
        }//from  w  w  w .  j av  a  2s  .c om

    } else {
        throw new IllegalArgumentException();
    }
}

From source file:net.holmes.core.service.http.HttpFileRequestDecoder.java

License:Open Source License

/**
 * {@inheritDoc}/* w  w  w  . j  a  v  a2 s  . c om*/
 */
@Override
protected void decode(ChannelHandlerContext context, FullHttpRequest request, List<Object> out) {
    HttpFileRequest fileRequest = null;
    if (request.getMethod().equals(GET)) {
        QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
        if (decoder.path().startsWith(HTTP_CONTENT_REQUEST_PATH.toString())
                && decoder.parameters().get(HTTP_CONTENT_ID.toString()) != null) {
            // Request for a content file is valid if content is found in media index
            AbstractNode node = mediaManager
                    .getNode(decoder.parameters().get(HTTP_CONTENT_ID.toString()).get(0));
            if (node instanceof ContentNode) {
                ContentNode contentNode = (ContentNode) node;
                fileRequest = new HttpFileRequest(request, new File(contentNode.getPath()),
                        contentNode.getMimeType(), false);
            }
        } else {
            // Request for UI static file is valid if requested file name has a correct mime type
            String fileName = getFileName(decoder);
            MimeType mimeType = mimeTypeManager.getMimeType(fileName);
            if (mimeType != null) {
                fileRequest = new HttpFileRequest(request, new File(uiDirectory, fileName), mimeType, true);
            }
        }
    }

    if (fileRequest != null) {
        // Add file request to message list
        out.add(fileRequest);
    } else {
        // Forward request to pipeline
        request.retain();
        out.add(request);
    }
}

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

License:Open Source License

public FullHttpResponse onGetRequest(HttpRequest request, 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);
    PreparedStatement get_app = database.getConnection().prepareStatement(SELECT_APPLICATION);
    get_app.setString(1, parameters.get(OAUTH_TOKEN).get(0));
    ResultSet result = get_app.executeQuery();
    if (result.first()) {
        Map<String, String> vars = new HashMap<String, String>();
        vars.put(APPLICATION, result.getString(APPLICATION));
        result.close();/*from  www .  ja  v a 2s .com*/
        return new DefaultFullHttpResponse(request.getProtocolVersion(), OK,
                Unpooled.copiedBuffer(
                        TEMPLATE_MATCHER.replace(
                                LanguageHeader.fromRequest(request).getPageInLocale(AUTHORIZE_DOT_HTML), vars),
                        CharsetUtil.UTF_8));
    }
    result.close();
    throw new ErrorException(INVALID_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 {//from   w w  w  . j a v a 2s .  c  o  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.oauth.HeaderVerifier.java

License:Open Source License

/**
 * Constructor for check OAuth headers, most of the things that can be checked will be checked right away.
 * @param request The netty HttpRequest to get the headers from
 * @param uri The URI for this request "new URI(request.getUri())"
 * @param flags These flags are only related to the signin, otherwise you may omit them
 * @throws OAuthException Thrown if one of the checks failed
 *//*  w ww  . j a  v  a2  s. c o m*/
public HeaderVerifier(final HttpRequest request, final URI uri, final int flags) throws OAuthException {
    if (!request.headers().contains(AUTHORIZATION))
        throw new OAuthException(ErrorMessages.NO_AUTH_HEADER);
    auth_header = request.headers().get(AUTHORIZATION);
    if (!auth_header.startsWith(OAUTH))
        throw new OAuthException(ErrorMessages.NO_REALM_PRESENT);
    String[] split = auth_header.substring(6).split(COMMA_REGEX);
    oauth_params = new LinkedHashMap<String, String>();
    for (int i = 0; i < split.length; i++) {
        String[] split_header = split[i].split(EQUALS_REGEX, 2);
        if (split_header.length == 2) {
            if (split_header[0].equals(REALM))
                continue;
            else if (!split[i].startsWith(OAUTH_))
                throw new OAuthException(ErrorMessages.INVALID_FIELD_IN_AUTHHEADER);
            oauth_params.put(split_header[0], split_header[1].replaceAll(STRIP_QUOTES_REGEX, EMPTY));
        }
    }
    if (!oauth_params.containsKey(OAuthParameters.OAUTH_CONSUMER_KEY))
        error(ErrorMessages.MISSING_CONSUMER_KEY);
    if (!oauth_params.containsKey(OAuthParameters.OAUTH_NONCE))
        error(ErrorMessages.MISSING_NONCE);
    else if (oauth_params.get(OAuthParameters.OAUTH_NONCE).length() > 8)
        error(ErrorMessages.NONCE_TOO_LONG);
    if (!oauth_params.containsKey(OAuthParameters.OAUTH_TIMESTAMP))
        error(ErrorMessages.MISSING_TIMESTAMP);
    else {
        try {
            final long timestamp = Integer.valueOf(oauth_params.get(OAuthParameters.OAUTH_TIMESTAMP))
                    .longValue();
            final long now = (System.currentTimeMillis() / 1000);
            if (timestamp < (now - 300) || (now + 300) < timestamp)
                error(ErrorMessages.TIMESTAMP_OUT_OF_BOUNDS);
        } catch (NumberFormatException e) {
            error(ErrorMessages.INVALID_TIMESTAMP);
        }
    }
    if (!oauth_params.containsKey(OAuthParameters.OAUTH_SIGNATURE_METHOD))
        error(ErrorMessages.MISSING_SIGNATURE_METHOD);
    else if (!oauth_params.get(OAuthParameters.OAUTH_SIGNATURE_METHOD).equals(VALID_SIGNATURE_METHOD))
        error(ErrorMessages.INVALID_SIGNATURE_METHOD);
    if (!oauth_params.containsKey(OAuthParameters.OAUTH_VERSION))
        error(ErrorMessages.MISSING_VERSION);
    else if (!oauth_params.get(OAuthParameters.OAUTH_VERSION).equals(VALID_OAUTH_VERSION))
        error(ErrorMessages.INVALID_VERSION);
    if (((flags & Flags.MAY_MISS_TOKEN) != Flags.MAY_MISS_TOKEN)
            && !oauth_params.containsKey(OAuthParameters.OAUTH_TOKEN))
        error(ErrorMessages.MISSING_TOKEN);
    if (((flags & Flags.REQUIRES_VERIFIER) == Flags.REQUIRES_VERIFIER)
            && !oauth_params.containsKey(OAuthParameters.OAUTH_VERIFIER))
        error(ErrorMessages.MISSING_VERIFIER);
    if (!oauth_params.containsKey(OAuthParameters.OAUTH_SIGNATURE))
        error(ErrorMessages.MISSING_SIGNATURE);
    final QueryStringDecoder querydecoder = new QueryStringDecoder(request.getUri());
    final Map<String, List<String>> parameters = querydecoder.parameters();
    final Set<String> keyset = parameters.keySet();
    final Iterator<String> iter = keyset.iterator();
    while (iter.hasNext()) {
        if (iter.next().startsWith(OAUTH_))
            error(ErrorMessages.INVALID_PARAMETER);
    }
    if (exception != null)
        throw exception;
    this.request = request;
    this.uri = uri;
    this.flags = flags;
}

From source file:net.mms_projects.copy_it.api.oauth.HeaderVerifier.java

License:Open Source License

/**
 * Create method for the raw signature base for post requests
 * @see net.mms_projects.copy_it.api.oauth.HeaderVerifier#checkSignature(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder, boolean)
 *//*from   ww w.  ja v  a2  s. co m*/
private String createRaw(HttpPostRequestDecoder post, boolean https)
        throws UnsupportedEncodingException, URISyntaxException {
    final StringBuilder rawbuilder = new StringBuilder();
    rawbuilder.append(request.getMethod().toString());
    rawbuilder.append('&');
    rawbuilder.append(HTTP);
    if (https)
        rawbuilder.append('s');
    rawbuilder.append(COLON_SLASH_SLASH);
    rawbuilder.append(URLEncoder.encode(request.headers().get(HOST), UTF_8));
    rawbuilder.append(URLEncoder.encode(uri.getPath(), UTF_8));
    rawbuilder.append('&');
    if (uri.getQuery() == null && request.getMethod() == HttpMethod.GET) {
        String[] loop_through = OAuthParameters.KEYS;
        if ((flags & Flags.REQUIRES_VERIFIER) == Flags.REQUIRES_VERIFIER)
            loop_through = OAuthParameters.VERIFIER_KEYS;
        for (int i = 0; i < loop_through.length; i++) {
            rawbuilder.append(loop_through[i]);
            rawbuilder.append(EQUALS);
            rawbuilder.append(URLEncoder.encode(oauth_params.get(loop_through[i]), UTF_8));
            if (i != (loop_through.length - 1))
                rawbuilder.append(AND);
        }
    } else {
        final List<String> keys = new ArrayList<String>();
        final Map<String, String> parameters = new HashMap<String, String>();
        if (request.getMethod() == HttpMethod.GET) {
            final QueryStringDecoder querydecoder = new QueryStringDecoder(uri);
            final Map<String, List<String>> get_parameters = querydecoder.parameters();
            final Set<String> keyset = parameters.keySet();
            final Iterator<String> iter = keyset.iterator();
            while (iter.hasNext()) {
                final String key = iter.next();
                keys.add(key);
                parameters.put(key, get_parameters.get(key).get(0));
            }
        } else if (request.getMethod() == HttpMethod.POST) {
            final List<InterfaceHttpData> post_parameters = post.getBodyHttpDatas();
            final Iterator<InterfaceHttpData> iter = post_parameters.iterator();
            while (iter.hasNext()) {
                final InterfaceHttpData data = iter.next();
                try {
                    final HttpData httpData = (HttpData) data;
                    parameters.put(httpData.getName(),
                            URLEncoder.encode(httpData.getString(), UTF_8).replace(PLUS, PLUS_ENCODED));
                    keys.add(httpData.getName());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        for (int i = 0; i < OAuthParameters.KEYS.length; i++)
            keys.add(OAuthParameters.KEYS[i]);
        if ((flags & Flags.REQUIRES_VERIFIER) == Flags.REQUIRES_VERIFIER)
            keys.add(OAuthParameters.OAUTH_VERIFIER);
        Collections.sort(keys);
        final int length = keys.size();
        for (int i = 0; i < length; i++) {
            final String key = keys.get(i);
            rawbuilder.append(key);
            rawbuilder.append(EQUALS);
            if (key.startsWith(OAUTH_))
                rawbuilder.append(URLEncoder.encode(oauth_params.get(key), UTF_8));
            else
                rawbuilder.append(URLEncoder.encode(parameters.get(key), UTF_8));
            if (i != (length - 1))
                rawbuilder.append(AND);
        }
    }
    System.err.println(rawbuilder.toString());
    return rawbuilder.toString();
}

From source file:netty.HttpServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        if (is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }/*from   w  w  w . j a v a  2  s  .  c  o  m*/

        QueryStringDecoder decoderQuery = new QueryStringDecoder(req.getUri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        String command = decoderQuery.path().substring(1);
        if (command.equals("favicon.ico")) {
            return;
        }
        String result = logicService.handleCommand(command, uriAttributes);
        // String result = command;
        ByteBuf buf = copiedBuffer(result, CharsetUtil.UTF_8);

        boolean keepAlive = isKeepAlive(req); // TODO important
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buf);
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}