Example usage for io.vertx.core.http HttpServerRequest getParam

List of usage examples for io.vertx.core.http HttpServerRequest getParam

Introduction

In this page you can find the example usage for io.vertx.core.http HttpServerRequest getParam.

Prototype

@Nullable
default String getParam(String paramName) 

Source Link

Document

Return the first param value with the specified name

Usage

From source file:com.glencoesoftware.omero.ms.thumbnail.ThumbnailMicroserviceVerticle.java

License:Open Source License

/**
 * Render thumbnail event handler. Responds with a <code>image/jpeg</code>
 * body on success based on the <code>longestSide</code> and
 * <code>imageId</code> encoded in the URL or HTTP 404 if the {@link Image}
 * does not exist or the user does not have permissions to access it.
 * @param event Current routing context.
 *///  w w  w .  j  a  v  a2 s  .  c  o m
private void renderThumbnail(RoutingContext event) {
    final HttpServerRequest request = event.request();
    final HttpServerResponse response = event.response();
    final Map<String, Object> data = new HashMap<String, Object>();
    data.put("longestSide",
            Optional.ofNullable(request.getParam("longestSide")).map(Integer::parseInt).orElse(96));
    data.put("imageId", Long.parseLong(request.getParam("imageId")));
    data.put("omeroSessionKey", event.get("omero.session_key"));
    data.put("renderingDefId",
            Optional.ofNullable(request.getParam("rdefId")).map(Long::parseLong).orElse(null));

    vertx.eventBus().<byte[]>send(ThumbnailVerticle.RENDER_THUMBNAIL_EVENT, Json.encode(data), result -> {
        try {
            if (result.failed()) {
                Throwable t = result.cause();
                int statusCode = 404;
                if (t instanceof ReplyException) {
                    statusCode = ((ReplyException) t).failureCode();
                }
                response.setStatusCode(statusCode);
                return;
            }
            byte[] thumbnail = result.result().body();
            response.headers().set("Content-Type", "image/jpeg");
            response.headers().set("Content-Length", String.valueOf(thumbnail.length));
            response.write(Buffer.buffer(thumbnail));
        } finally {
            response.end();
            log.debug("Response ended");
        }
    });
}

From source file:com.glencoesoftware.omero.ms.thumbnail.ThumbnailMicroserviceVerticle.java

License:Open Source License

/**
 * Get thumbnails event handler. Responds with a JSON dictionary of Base64
 * encoded <code>image/jpeg</code> thumbnails keyed by {@link Image}
 * identifier. Each dictionary value is prefixed with
 * <code>data:image/jpeg;base64,</code> so that it can be used with
 * <a href="http://caniuse.com/#feat=datauri">data URIs</a>.
 * @param event Current routing context.
 *//*from  w  w  w . jav a 2s  .c  o  m*/
private void getThumbnails(RoutingContext event) {
    final HttpServerRequest request = event.request();
    final HttpServerResponse response = event.response();
    final Map<String, Object> data = new HashMap<String, Object>();
    final String callback = request.getParam("callback");
    data.put("longestSide",
            Optional.ofNullable(request.getParam("longestSide")).map(Integer::parseInt).orElse(96));
    data.put("imageIds",
            request.params().getAll("id").stream().map(Long::parseLong).collect(Collectors.toList()).toArray());
    data.put("omeroSessionKey", event.get("omero.session_key"));

    vertx.eventBus().<String>send(ThumbnailVerticle.GET_THUMBNAILS_EVENT, Json.encode(data), result -> {
        try {
            if (result.failed()) {
                Throwable t = result.cause();
                int statusCode = 404;
                if (t instanceof ReplyException) {
                    statusCode = ((ReplyException) t).failureCode();
                }
                response.setStatusCode(statusCode);
                return;
            }
            String json = result.result().body();
            String contentType = "application/json";
            if (callback != null) {
                json = String.format("%s(%s);", callback, json);
                contentType = "application/javascript";
            }
            response.headers().set("Content-Type", contentType);
            response.headers().set("Content-Length", String.valueOf(json.length()));
            response.write(json);
        } finally {
            response.end();
            log.debug("Response ended");
        }
    });
}

From source file:de.braintags.netrelay.model.RegisterClaim.java

License:Open Source License

/**
 * Creates an instance, where all needed information of the request to register are stored
 * /*from   ww w  . j av  a2  s.  c  om*/
 * @param request
 */
public RegisterClaim(String email, String password, HttpServerRequest request) {
    super(email, request);
    this.password = password;
    destinationUrl = request.getParam(RegisterController.REG_CONFIRM_SUCCESS_URL_PROP);
}

From source file:gribbit.model.DataModel.java

License:Open Source License

/**
 * Bind formModelInstance data object from an HTTP request. The name of each field in formModelInstance object
 * is looked up in the POST parameters. If the named value is found, it is trimmed (unless annotated with
 * NoTrim), and integers etc. are parsed as needed before the value is stored in the field. Fields marked with
 * Required constraint have to not only not be null, but also not be empty after trimming. Note that any
 * constraint such as MinLength also implies Required. (NormalizeSpacing is a data transformation annotation,
 * not a constraint, so it will only be applied if a value is provided.)
 * //  w  w  w .  j a  v a  2 s . c o  m
 * @param request
 *            The HTTP request
 * @param formModel
 *            The form model to bind
 * @throws AppException
 *             if any of the constraint annotations are not specified
 */
public void bindFromPost(HttpServerRequest request) throws ResponseException {

    // Match field names against POST param names, and set values of fields whenever there is a match
    // HashSet<String> unusedPostParams = new HashSet<String>(request.getPostParamNames());
    for (Field field : getClass().getFields()) {
        String fieldName = field.getName();
        // unusedPostParams.remove(fieldName);

        if (FieldChecker.fieldIsPrivate(field, /* checkGet = */false, /* checkSet = */true)) {
            // Ignore attempts to set fields annotated with @Private or @OnlySend,
            // or where the field is a DBModel id field

            // Log.warning("Attempt to bind POST param \"" + field.getName() + "\" to field marked @"
            //         + Private.class.getName() + " or @" + OnlySend.class.getName()
            //         + " (or an id field of a subclass of " + DBModel.class.getName() + ") in class "
            //         + this.getClass().getName() + "; ignoring");

        } else {
            Class<?> fieldType = field.getType();

            try {
                // For each field in class, look up field name in POST parameters and then
                // URL query parameters
                String postParamValForField = request.getParam(fieldName);
                if (postParamValForField == null) {

                    // TODO
                    // FileUpload postFileUploadForField = request.getPostFileUploadParam(fieldName);
                    // if (postFileUploadForField != null) {

                    //                            // There was a file uploaded
                    //                            if (fieldType == FileUpload.class) {
                    //                                // Save the FileUpload object in the field. This doesn't actually read the
                    //                                // file contents (loading the file into RAM could kill the server). The
                    //                                // request handler must read the file before responding, or increment the
                    //                                // reference count if they want to keep the file after the request has been
                    //                                // sent, because the file will otherwise be released.
                    //                                field.set(this, postFileUploadForField);
                    //                            }

                    // } else {

                    // There is a field in formModelInstance DataModel that is not in the
                    // POST request
                    if (FieldChecker.fieldIsRequired(field)) {
                        throw new BadRequestException("Field " + getClass().getName() + "." + fieldName
                                + " required, but not sent in POST request");
                    }
                    // }

                } else {
                    // Try binding POST request param to correspondingly-named field in
                    // the formModelInstance DataModel

                    if (fieldType == String.class) {
                        field.set(this, postParamValForField);

                    } else if (fieldType == Integer.class) {
                        field.set(this, new Integer(postParamValForField));

                    } else if (fieldType == Integer.TYPE) {
                        field.setInt(this, Integer.parseInt(postParamValForField));

                    } else if (fieldType == Long.class) {
                        field.set(this, new Long(postParamValForField));

                    } else if (fieldType == Long.TYPE) {
                        field.setLong(this, Long.parseLong(postParamValForField));

                    } else if (fieldType == Short.class) {
                        field.set(this, new Short(postParamValForField));

                    } else if (fieldType == Short.TYPE) {
                        field.setShort(this, Short.parseShort(postParamValForField));

                    } else if (fieldType == Float.class) {
                        field.set(this, new Float(postParamValForField));

                    } else if (fieldType == Float.TYPE) {
                        field.setFloat(this, Float.parseFloat(postParamValForField));

                    } else if (fieldType == Double.class) {
                        field.set(this, new Double(postParamValForField));

                    } else if (fieldType == Double.TYPE) {
                        field.setDouble(this, Double.parseDouble(postParamValForField));

                    } else if (fieldType == Boolean.class || fieldType == Boolean.TYPE) {
                        // Boolean fields are bound from checkbox form inputs

                        String lower = postParamValForField.toLowerCase();
                        boolean checkboxVal = lower.equals("yes") || lower.equals("on") || lower.equals("1")
                                || lower.equals("true");
                        if (fieldType == Boolean.class) {
                            field.set(this, new Boolean(checkboxVal));
                        } else if (fieldType == Boolean.TYPE) {
                            field.setBoolean(this, checkboxVal);
                        }

                    } else if (fieldType == Character.class || fieldType == Character.TYPE) {
                        // Character fields are bound from text, but limited to a length of 1

                        if (postParamValForField.length() > 1) {
                            throw new BadRequestException("Field " + getClass().getName() + "." + fieldName
                                    + " requires a single character, got " + postParamValForField.length()
                                    + " characters");
                        } else if (postParamValForField.length() == 1) {
                            char c = postParamValForField.charAt(0);
                            if (fieldType == Character.class) {
                                field.set(this, new Character((char) c));
                            } else if (fieldType == Character.TYPE) {
                                field.setChar(this, (char) c);
                            }
                        }

                    } else if (fieldType == LocalDate.class) {
                        // Dates must be in format yyyy-MM-dd
                        field.set(this, LocalDate.parse(postParamValForField));

                    } else if (fieldType.isEnum()) {
                        // Enum-typed fields are bound from radio button inputs

                        // If the field is an enum, try looking up the submitted form value as
                        // one of the enum constants.
                        try {
                            @SuppressWarnings({ "unchecked", "rawtypes" })
                            Enum<?> enumVal = Enum.valueOf((Class<Enum>) fieldType, postParamValForField);
                            field.set(this, enumVal);
                        } catch (IllegalArgumentException e) {
                            throw new BadRequestException("Illegal value " + postParamValForField
                                    + " for field " + getClass().getName() + "." + fieldName);
                        }

                    } else {
                        throw new InternalServerErrorException(
                                "Unsupported field type " + fieldType.getSimpleName() + " for field "
                                        + getClass().getName() + "." + fieldName);
                    }
                }

            } catch (NumberFormatException | DateTimeParseException e) {
                throw new BadRequestException("Could not parse value " + getClass().getName() + "." + fieldName
                        + " from the request");

            } catch (IllegalArgumentException | IllegalAccessException e) {
                throw new InternalServerErrorException("Could not set field " + getClass().getName() + "."
                        + fieldName + " to the value passed in the request", e);
            }
        }
    }

    // Check that the values in the fields satisfy the constraints
    try {
        GribbitServer.siteResources.checkFieldValuesAgainstConstraintAnnotations(this);
    } catch (Exception e) {
        throw new BadRequestException("Form values do not satisfy constraints: " + e.getMessage());
    }

    //        for (String unusedParam : unusedPostParams) {
    //            if (!unusedParam.equals(CSRF.CSRF_PARAM_NAME)) {
    //                Log.warning("POST param \"" + unusedParam + "\" is not a public field in DataModel "
    //                        + this.getClass().getName() + ", ignoring");
    //            }
    //        }
}

From source file:hu.elte.ik.robotika.futar.vertx.backend.verticle.HTTPVerticle.java

private void handleRobotPositionData(RoutingContext context) {
    HttpServerRequest req = context.request();
    String data = req.getParam("data");
    System.out.println("Data from robot:");
    Stream.of(data.split("_")).forEach(System.out::println);
    System.out.println("\n");
    context.response().end();//  ww  w  .  ja va 2s .  co  m
}

From source file:io.apiman.gateway.platforms.vertx3.http.HttpApiFactory.java

License:Apache License

private static String parseApiKey(HttpServerRequest req) {
    String headerKey = req.headers().get("X-API-Key");
    if (headerKey == null || headerKey.trim().length() == 0) {
        headerKey = req.getParam("apikey");
    }//from  w w  w.j a  va2 s .  c  om
    return headerKey;
}

From source file:io.gravitee.am.gateway.handler.vertx.auth.handler.impl.OAuth2ClientAuthHandlerImpl.java

License:Apache License

private String buildRedirectUri(HttpServerRequest request) throws URISyntaxException {
    return UriBuilderRequest.resolveProxyRequest(new io.vertx.reactivex.core.http.HttpServerRequest(request),
            request.uri(),/*w  ww  .j  av a  2 s  .  c  o m*/
            // append provider query param to avoid redirect mismatch exception
            Collections.singletonMap("provider", request.getParam(PROVIDER_PARAMETER)), true, true);
}

From source file:io.gravitee.am.gateway.handler.vertx.auth.handler.impl.RedirectAuthHandlerImpl.java

License:Apache License

@Override
public void parseCredentials(RoutingContext context, Handler<AsyncResult<JsonObject>> handler) {
    Session session = context.session();
    if (session != null) {
        try {/*  www .ja va  2 s.  c  o  m*/
            // Save current request in session - we'll get redirected back here after successful login
            HttpServerRequest request = context.request();
            session.put(returnURLParam,
                    UriBuilderRequest
                            .resolveProxyRequest(new io.vertx.reactivex.core.http.HttpServerRequest(request),
                                    request.path(),
                                    request.params().entries().stream()
                                            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)),
                                    true, false));

            // Now redirect to the login url
            String uri = UriBuilderRequest.resolveProxyRequest(
                    new io.vertx.reactivex.core.http.HttpServerRequest(request), loginRedirectURL,
                    Collections.singletonMap(OAuth2Constants.CLIENT_ID,
                            request.getParam(OAuth2Constants.CLIENT_ID)),
                    false, false);

            handler.handle(Future.failedFuture(new HttpStatusException(302, uri)));
        } catch (Exception e) {
            logger.warn("Failed to decode login redirect url", e);
            handler.handle(Future.failedFuture(new HttpStatusException(302, loginRedirectURL)));
        }
    } else {
        handler.handle(Future.failedFuture("No session - did you forget to include a SessionHandler?"));
    }
}

From source file:io.nonobot.core.handlers.GitHubVerticle.java

License:Apache License

@Override
public void start() throws Exception {
    super.start();
    Router router = Router.router(vertx);
    bot.webRouter().mountSubRouter("/github", router);
    router.post().handler(ctx -> {//from w  w  w .  j a  v a 2s  . com
        HttpServerRequest req = ctx.request();
        String event = req.getHeader("X-Github-Event");
        if (!"push".equals(event)) {
            req.response().setStatusCode(400).end("X-Github-Event " + event + " not handled");
            return;
        }
        String contentType = req.getHeader("Content-Type");
        if (!"application/json".equals(contentType)) {
            req.response().setStatusCode(400).end("Content-Type " + contentType + " not handled");
            return;
        }
        req.bodyHandler(body -> {
            JsonObject json = body.toJsonObject();
            req.response().end();
            String chatId = req.getParam("chat");
            JsonArray commits = json.getJsonArray("commits");
            if (chatId != null && commits != null && commits.size() > 0) {
                String commitWord = commits.size() > 1 ? "commits" : "commit";
                bot.chatRouter().sendMessage(new SendOptions().setChatId(chatId),
                        "Got " + commits.size() + " new " + commitWord + " from "
                                + json.getJsonObject("pusher").getString("name") + " on "
                                + json.getJsonObject("repository").getString("full_name"));
                for (int index = 0; index < commits.size(); index++) {
                    JsonObject commit = commits.getJsonObject(index);
                    bot.chatRouter().sendMessage(new SendOptions().setChatId(chatId),
                            "  * " + commit.getString("message") + " " + commit.getString("url"));
                }
            }
        });
    });
}

From source file:org.apache.servicecomb.demo.edge.service.encrypt.EncryptEdgeDispatcher.java

License:Apache License

private CompletableFuture<String> queryUserId(HttpServerRequest httpServerRequest) {
    String serviceToken = httpServerRequest.getParam("serviceToken");
    if (serviceToken == null) {
        // no need to query userId
        return CompletableFuture.completedFuture(null);
    }//from www  .ja v  a  2 s .  c o m

    CompletableFuture<String> future = new CompletableFuture<>();
    encrypt.queryUserId(serviceToken).whenComplete((userId, e) -> {
        if (e != null) {
            // treat as success, just userId is null
            LOGGER.error("Failed to query userId, serviceToken={}.", serviceToken, e);
        }

        future.complete(userId);
    });

    return future;
}