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:org.jocean.aliyun.oss.internal.SignUtils.java

License:Apache License

public static String buildCanonicalString(final String method, final String resourcePath,
        final HttpRequest request, String expires) {

    final StringBuilder canonicalString = new StringBuilder();
    canonicalString.append(method + NEW_LINE);

    final Iterable<Map.Entry<String, String>> headers = request.headers();
    final TreeMap<String, String> headersToSign = new TreeMap<String, String>();

    if (headers != null) {
        for (Entry<String, String> header : headers) {
            if (header.getKey() == null) {
                continue;
            }/*from w  ww  .  ja v a2  s  . c  o m*/

            final String lowerKey = header.getKey().toLowerCase();
            if (lowerKey.equals(HttpHeaders.CONTENT_TYPE.toLowerCase())
                    || lowerKey.equals(HttpHeaders.CONTENT_MD5.toLowerCase())
                    || lowerKey.equals(HttpHeaders.DATE.toLowerCase())
                    || lowerKey.startsWith(OSSHeaders.OSS_PREFIX)) {
                headersToSign.put(lowerKey, header.getValue().trim());
            }
        }
    }

    if (!headersToSign.containsKey(HttpHeaders.CONTENT_TYPE.toLowerCase())) {
        headersToSign.put(HttpHeaders.CONTENT_TYPE.toLowerCase(), "");
    }
    if (!headersToSign.containsKey(HttpHeaders.CONTENT_MD5.toLowerCase())) {
        headersToSign.put(HttpHeaders.CONTENT_MD5.toLowerCase(), "");
    }

    // Append all headers to sign to canonical string
    for (Map.Entry<String, String> entry : headersToSign.entrySet()) {
        final String key = entry.getKey();
        final Object value = entry.getValue();

        if (key.startsWith(OSSHeaders.OSS_PREFIX)) {
            canonicalString.append(key).append(':').append(value);
        } else {
            canonicalString.append(value);
        }

        canonicalString.append(NEW_LINE);
    }

    // Append canonical resource to canonical string
    final QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
    canonicalString.append(buildCanonicalizedResource(resourcePath, decoder.parameters()));

    return canonicalString.toString();
}

From source file:org.jpos.qrest.participant.Router.java

License:Open Source License

@Override
public String select(long id, Serializable context) {
    Context ctx = (Context) context;
    FullHttpRequest request = ctx.get(REQUEST);
    ctx.log("Method: " + request.method().name());
    ctx.log("Routes: " + routes);
    List<Route<String>> routesByMethod = routes.get(request.method().name());
    QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
    if (!decoder.parameters().isEmpty())
        ctx.put(QUERYPARAMS, decoder.parameters());

    if (routesByMethod != null) {
        Optional<Route<String>> route = routesByMethod.stream().filter(r -> r.matches(decoder.uri()))
                .findFirst();//from   w  ww  . j a v  a 2 s .  c  o m
        String path = URI.create(decoder.uri()).getPath();
        if (route.isPresent()) {
            Map m = route.get().parameters(path);
            if (m != null)
                ctx.put(PATHPARAMS, m);
            return route.get().apply(route.get(), path);
        }
    }
    return null;
}

From source file:org.pidome.server.system.network.http.HttpRequestHandler.java

/**
 * Process the request made for http2//from   w ww  .ja  v  a2 s . c o  m
 *
 * @param chc The channel context.
 * @param request The url request.
 * @param writer The output writer of type HttpRequestWriterInterface.
 * @param streamId The stream Id in case of http2, when http1 leave null.
 */
protected static void processManagement(ChannelHandlerContext chc, FullHttpRequest request,
        HttpRequestWriterInterface writer, String streamId) {
    String plainIp = getPlainIp(chc.channel().remoteAddress());
    String localIp = getPlainIp(chc.channel().localAddress());
    int localPort = getPort(chc.channel().localAddress());
    try {
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
        String fileRequest = queryStringDecoder.path();

        if (fileRequest.equals("/")) {
            fileRequest = "/index.html";
        } else if (fileRequest.endsWith("/")) {
            fileRequest = fileRequest + "index.html";
        }

        String nakedfile = fileRequest.substring(1, fileRequest.lastIndexOf("."));
        String fileType = fileRequest.substring(fileRequest.lastIndexOf(".") + 1);

        String loginError = "";
        RemoteClientInterface client = null;
        RemoteClient remoteClient = null;

        WebRenderInterface renderClass = null;

        try {
            Set<Cookie> cookie = cookieParser(request);
            Map<RemoteClientInterface, RemoteClient> clientSet = getAuthorizedClient(request, plainIp,
                    (cookie.isEmpty() ? "" : ((Cookie) cookie.toArray()[0]).getValue()), fileRequest);
            client = clientSet.keySet().iterator().next();
            remoteClient = clientSet.get(client);
        } catch (Exception ex) {
            if (ex instanceof HttpClientNotAuthorizedException) {
                LOG.error("Not authorized at {}", plainIp, request.uri());
                loginError = "Not authorized or bad username/password";
            } else if (ex instanceof HttpClientLoggedInOnOtherLocationException) {
                LOG.error("Not authorized at {} (Logged in on other location: {}!)", plainIp, ex.getMessage());
                loginError = "Client seems to be already logged in on another location";
            } else {
                LOG.error("Not authorized at: {} (Cookie problem? ({}))", ex, ex.getMessage(), ex);
                loginError = "Problem getting authentication data, refer to log file";
            }
            if (!request.uri().equals("/jsonrpc.json")) {
                fileType = "xhtml";
                nakedfile = "login";
                fileRequest = "/login.xhtml";
            }
        }

        if (!fileType.isEmpty()) {
            switch (fileType) {
            case "xhtml":
            case "json":
            case "upload":
            case "xml":
            case "/":
                if (request.uri().startsWith("/jsonrpc.json")) {
                    renderClass = getJSONRPCRenderer(request);
                } else if (request.uri().startsWith("/xmlapi/")) {
                    /// This is a temp solution until the xml output has been transfered to the json rpc api.
                    Class classToLoad = Class.forName(
                            HttpServer.getXMLClassesRoot() + nakedfile.replace("xmlapi/", ".Webclient_"));
                    renderClass = (WebRenderInterface) classToLoad.getConstructor().newInstance();
                } else {
                    Class classToLoad = Class
                            .forName(HttpServer.getDocumentClassRoot() + nakedfile.replace("/", ".Webclient_"));
                    renderClass = (WebRenderInterface) classToLoad.getConstructor().newInstance();
                }
                renderClass.setHostData(localIp, localPort, plainIp);
                renderClass.setRequestData(queryStringDecoder.parameters());
                Map<String, String> postData = new HashMap<>();
                Map<String, byte[]> fileMap = new HashMap<>();
                if (request.method().equals(HttpMethod.POST)) {
                    HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(
                            new DefaultHttpDataFactory(false), request);
                    decoder.setDiscardThreshold(0);
                    if (request instanceof HttpContent) {
                        HttpContent chunk = (HttpContent) request;
                        decoder.offer(chunk);
                        try {
                            while (decoder.hasNext()) {
                                InterfaceHttpData data = decoder.next();
                                if (data != null) {
                                    if (data.getHttpDataType()
                                            .equals(InterfaceHttpData.HttpDataType.Attribute)) {
                                        postData.put(data.getName(), ((HttpData) data).getString());
                                    } else if (data.getHttpDataType()
                                            .equals(InterfaceHttpData.HttpDataType.FileUpload)) {
                                        FileUpload fileUpload = (FileUpload) data;
                                        fileMap.put(fileUpload.getFilename(), fileUpload.get());
                                    }
                                }
                            }
                        } catch (HttpPostRequestDecoder.EndOfDataDecoderException e1) {

                        }
                        if (chunk instanceof LastHttpContent) {
                            decoder.destroy();
                            decoder = null;
                        }
                    }
                }
                renderClass.setPostData(postData);
                renderClass.setFileData(fileMap);
                renderClass.setLoginData(client, remoteClient, loginError);
                renderClass.collect();
                renderClass.setTemplate(fileRequest);

                ByteArrayOutputStream outputWriter = new ByteArrayOutputStream();
                renderClass.setOutputStream(outputWriter);

                String output = renderClass.render();
                outputWriter.close();
                writer.writeResponse(chc, HttpResponseStatus.OK, output.getBytes(), fileType, streamId, false);
                break;
            default:
                sendStaticFile(chc, writer, fileRequest, queryStringDecoder, streamId);
                break;
            }
        }
    } catch (ClassNotFoundException | Webservice404Exception ex) {
        LOG.warn("404 error: {} - {} (by {})", ex.getMessage(), ex, plainIp);
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw);) {
            ex.printStackTrace(pw);
            writer.writeResponse(chc, HttpResponseStatus.NOT_FOUND, return404Error().getBytes(), "html",
                    streamId, false);
        } catch (IOException exWriters) {
            LOG.error("Problem outputting 404 error: {}", exWriters.getMessage(), exWriters);
        }
    } catch (Exception ex) {
        LOG.error("500 error: {}", ex.getLocalizedMessage(), ex);
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw);) {
            ex.printStackTrace(pw);
            String errorOutput = sw.toString() + "\n\n" + getRandQuote();
            writer.writeResponse(chc, HttpResponseStatus.INTERNAL_SERVER_ERROR,
                    (errorOutput + "<br/><br/><p>" + getRandQuote() + "</p>").getBytes(), "", streamId, false);
        } catch (IOException exWriters) {
            LOG.error("Problem outputting 500 error: {}", exWriters.getMessage(), exWriters);
        }
    }
}

From source file:org.pidome.server.system.network.http.HttpRequestHandler.java

/**
 * Sends a static file to the channel handler context.
 * @param chc The channel handler context
 * @param writer The output writer as resource.
 * @param fileName The filename requested
 * @param decoder The query string decoder.
 * @param streamId The stream id in case of http 2
 * @throws Webservice404Exception when the file is not found.
 * @throws IOException When output fails.
 *///ww  w .j av a 2  s  . c o m
private static void sendStaticFile(ChannelHandlerContext chc, HttpRequestWriterInterface writer,
        String fileName, QueryStringDecoder decoder, String streamId)
        throws Webservice404Exception, IOException {
    File file;
    boolean floorPlan = false;
    if (fileName.startsWith("/floorplan/")) {
        floorPlan = true;
        file = new File("resources", fileName);
    } else {
        file = new File(HttpServer.getDocumentRoot(), fileName);
    }
    String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
    ByteArrayOutputStream outputByteArray = new ByteArrayOutputStream();
    switch (fileType) {
    case "html":
        if (!decoder.parameters().containsKey("requesttype") && HttpServer.getHttpHeader() != null) {
            outputByteArray.write(Files.readAllBytes(new File(HttpServer.getHttpHeader()).toPath()));
        }
        outputByteArray.write(Files.readAllBytes(file.toPath()));
        if (!decoder.parameters().containsKey("requesttype") && HttpServer.getHttpFooter() != null) {
            outputByteArray.write(Files.readAllBytes(new File(HttpServer.getHttpFooter()).toPath()));
        }
        break;
    default:
        outputByteArray.write(Files.readAllBytes(file.toPath()));
        break;
    }
    if (file.exists() && !file.isDirectory()) {
        writer.writeResponse(chc, HttpResponseStatus.OK, outputByteArray.toByteArray(), fileType, streamId,
                !floorPlan);
    } else {
        writer.writeResponse(chc, HttpResponseStatus.NOT_FOUND, return404Error().getBytes(), "html", streamId);
    }
    outputByteArray.close();
}

From source file:org.ratpackframework.http.internal.DefaultRequest.java

License:Apache License

public MultiValueMap<String, String> getQueryParams() {
    if (queryParams == null) {
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(getUri());
        queryParams = new ImmutableDelegatingMultiValueMap<>(queryStringDecoder.parameters());
    }//w  w w .j  a v a  2  s .c  om
    return queryParams;
}

From source file:org.ratpackframework.http.internal.DefaultRequest.java

License:Apache License

public MultiValueMap<String, String> getForm() {
    if (form == null) {
        QueryStringDecoder formDecoder = new QueryStringDecoder(getText(), false);
        form = new ImmutableDelegatingMultiValueMap<>(formDecoder.parameters());
    }//from   w w  w .  j  a va2s .  c om
    return form;
}

From source file:org.restexpress.Request.java

License:Apache License

/**
 * Returns the body as a Map of name/value pairs from a url-form-encoded form submission.
 * The values returned are URL-decoded depending on the value of shouldDecode.
 * /*www. j  a  v  a 2s  .c o m*/
 * @param shouldDecode true if the returned values should be URL-decoded
 * @return
 */
public Map<String, List<String>> getBodyFromUrlFormEncoded(boolean shouldDecode) {
    if (shouldDecode) {
        QueryStringDecoder qsd = new QueryStringDecoder(getBody().toString(ContentType.CHARSET),
                ContentType.CHARSET, false);
        return qsd.parameters();
    }

    QueryStringParser qsp = new QueryStringParser(getBody().toString(ContentType.CHARSET), false);
    return qsp.getParameters();
}

From source file:org.restnext.core.http.RequestImpl.java

License:Apache License

/**
 * Create a new instance./*from  w  w  w. jav  a  2 s  .  c  o m*/
 *
 * @param context netty channel handler context
 * @param request netty full http request
 */
public RequestImpl(final ChannelHandlerContext context, final FullHttpRequest request) {
    Objects.requireNonNull(request, "request");
    Objects.requireNonNull(context, "context");

    this.charset = HttpUtil.getCharset(request, StandardCharsets.UTF_8);
    this.version = HttpVersion.HTTP_1_0.equals(request.protocolVersion()) ? Version.HTTP_1_0 : Version.HTTP_1_1;
    this.method = Method.valueOf(request.method().name());
    this.uri = URI.create(normalize(request.uri()));
    this.baseUri = createBaseUri(context, request);
    this.keepAlive = HttpUtil.isKeepAlive(request);

    // copy the inbound netty request headers.
    this.headers = new MultivaluedHashMap<>();
    for (Map.Entry<String, String> entry : request.headers()) {
        this.headers.add(entry.getKey().toLowerCase(), entry.getValue());
    }

    this.parameters = new MultivaluedHashMap<>();
    // decode the inbound netty request uri parameters.
    QueryStringDecoder queryDecoder = new QueryStringDecoder(request.uri(), charset);
    for (Map.Entry<String, List<String>> entry : queryDecoder.parameters().entrySet()) {
        this.parameters.addAll(entry.getKey(), entry.getValue());
    }

    // decode the inbound netty request body parameters.
    if (Method.POST.equals(method)) {
        CharSequence charSequence = HttpUtil.getMimeType(request);
        AsciiString mimeType = charSequence != null ? AsciiString.of(charSequence) : AsciiString.EMPTY_STRING;
        boolean isFormData = mimeType.contains(HttpHeaderValues.FORM_DATA);

        if (isFormData) {
            // decode the inbound netty request body multipart/form-data parameters.
            HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(), request,
                    charset);
            try {
                for (InterfaceHttpData data : decoder.getBodyHttpDatas()) {
                    InterfaceHttpData.HttpDataType type = data.getHttpDataType();
                    switch (type) {
                    case Attribute: {
                        try {
                            Attribute attribute = (Attribute) data;
                            this.parameters.add(attribute.getName(), attribute.getValue());
                        } catch (IOException ignore) {
                            LOGGER.warn("Could not get attribute value");
                        }
                        break;
                    }
                    case FileUpload:
                        break;
                    case InternalAttribute:
                        break;
                    default: //nop
                    }
                }
            } finally {
                decoder.destroy();
            }
        } else {
            // decode the inbound netty request body raw | form-url-encoded | octet-stream parameters.
            this.content = request.content().hasArray() ? request.content().array()
                    : request.content().toString(charset).getBytes();
        }
    }
}

From source file:org.traccar.protocol.OpenGtsProtocolDecoder.java

License:Apache License

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    FullHttpRequest request = (FullHttpRequest) msg;
    QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
    Map<String, List<String>> params = decoder.parameters();

    Position position = new Position(getProtocolName());

    for (Map.Entry<String, List<String>> entry : params.entrySet()) {
        String value = entry.getValue().get(0);
        switch (entry.getKey()) {
        case "id":
            DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, value);
            if (deviceSession == null) {
                sendResponse(channel, HttpResponseStatus.BAD_REQUEST);
                return null;
            }//from w  w w .  j ava2 s .c om
            position.setDeviceId(deviceSession.getDeviceId());
            break;
        case "gprmc":
            Parser parser = new Parser(PATTERN, value);
            if (!parser.matches()) {
                sendResponse(channel, HttpResponseStatus.BAD_REQUEST);
                return null;
            }

            DateBuilder dateBuilder = new DateBuilder().setTime(parser.nextInt(), parser.nextInt(),
                    parser.nextInt());

            position.setValid(parser.next().equals("A"));
            position.setLatitude(parser.nextCoordinate());
            position.setLongitude(parser.nextCoordinate());
            position.setSpeed(parser.nextDouble());
            position.setCourse(parser.nextDouble(0));

            dateBuilder.setDateReverse(parser.nextInt(), parser.nextInt(), parser.nextInt());
            position.setTime(dateBuilder.getDate());
            break;
        case "alt":
            position.setAltitude(Double.parseDouble(value));
            break;
        case "batt":
            position.set(Position.KEY_BATTERY_LEVEL, Double.parseDouble(value));
            break;
        default:
            break;
        }
    }

    if (position.getDeviceId() != 0) {
        sendResponse(channel, HttpResponseStatus.OK);
        return position;
    } else {
        sendResponse(channel, HttpResponseStatus.BAD_REQUEST);
        return null;
    }
}

From source file:org.traccar.protocol.OsmAndProtocolDecoder.java

License:Apache License

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    FullHttpRequest request = (FullHttpRequest) msg;
    QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
    Map<String, List<String>> params = decoder.parameters();
    if (params.isEmpty()) {
        decoder = new QueryStringDecoder(request.content().toString(StandardCharsets.US_ASCII), false);
        params = decoder.parameters();//from www . ja v  a2  s  . c o  m
    }

    Position position = new Position(getProtocolName());
    position.setValid(true);

    Network network = new Network();

    for (Map.Entry<String, List<String>> entry : params.entrySet()) {
        for (String value : entry.getValue()) {
            switch (entry.getKey()) {
            case "id":
            case "deviceid":
                DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, value);
                if (deviceSession == null) {
                    sendResponse(channel, HttpResponseStatus.BAD_REQUEST);
                    return null;
                }
                position.setDeviceId(deviceSession.getDeviceId());
                break;
            case "valid":
                position.setValid(Boolean.parseBoolean(value) || "1".equals(value));
                break;
            case "timestamp":
                try {
                    long timestamp = Long.parseLong(value);
                    if (timestamp < Integer.MAX_VALUE) {
                        timestamp *= 1000;
                    }
                    position.setTime(new Date(timestamp));
                } catch (NumberFormatException error) {
                    if (value.contains("T")) {
                        position.setTime(DateUtil.parseDate(value));
                    } else {
                        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        position.setTime(dateFormat.parse(value));
                    }
                }
                break;
            case "lat":
                position.setLatitude(Double.parseDouble(value));
                break;
            case "lon":
                position.setLongitude(Double.parseDouble(value));
                break;
            case "location":
                String[] location = value.split(",");
                position.setLatitude(Double.parseDouble(location[0]));
                position.setLongitude(Double.parseDouble(location[1]));
                break;
            case "cell":
                String[] cell = value.split(",");
                if (cell.length > 4) {
                    network.addCellTower(CellTower.from(Integer.parseInt(cell[0]), Integer.parseInt(cell[1]),
                            Integer.parseInt(cell[2]), Integer.parseInt(cell[3]), Integer.parseInt(cell[4])));
                } else {
                    network.addCellTower(CellTower.from(Integer.parseInt(cell[0]), Integer.parseInt(cell[1]),
                            Integer.parseInt(cell[2]), Integer.parseInt(cell[3])));
                }
                break;
            case "wifi":
                String[] wifi = value.split(",");
                network.addWifiAccessPoint(
                        WifiAccessPoint.from(wifi[0].replace('-', ':'), Integer.parseInt(wifi[1])));
                break;
            case "speed":
                position.setSpeed(convertSpeed(Double.parseDouble(value), "kn"));
                break;
            case "bearing":
            case "heading":
                position.setCourse(Double.parseDouble(value));
                break;
            case "altitude":
                position.setAltitude(Double.parseDouble(value));
                break;
            case "accuracy":
                position.setAccuracy(Double.parseDouble(value));
                break;
            case "hdop":
                position.set(Position.KEY_HDOP, Double.parseDouble(value));
                break;
            case "batt":
                position.set(Position.KEY_BATTERY_LEVEL, Double.parseDouble(value));
                break;
            case "driverUniqueId":
                position.set(Position.KEY_DRIVER_UNIQUE_ID, value);
                break;
            default:
                try {
                    position.set(entry.getKey(), Double.parseDouble(value));
                } catch (NumberFormatException e) {
                    switch (value) {
                    case "true":
                        position.set(entry.getKey(), true);
                        break;
                    case "false":
                        position.set(entry.getKey(), false);
                        break;
                    default:
                        position.set(entry.getKey(), value);
                        break;
                    }
                }
                break;
            }
        }
    }

    if (position.getFixTime() == null) {
        position.setTime(new Date());
    }

    if (network.getCellTowers() != null || network.getWifiAccessPoints() != null) {
        position.setNetwork(network);
    }

    if (position.getLatitude() == 0 && position.getLongitude() == 0) {
        getLastLocation(position, position.getDeviceTime());
    }

    if (position.getDeviceId() != 0) {
        sendResponse(channel, HttpResponseStatus.OK);
        return position;
    } else {
        sendResponse(channel, HttpResponseStatus.BAD_REQUEST);
        return null;
    }
}