List of usage examples for io.vertx.core.json JsonObject encodePrettily
public String encodePrettily()
From source file:io.gravitee.gateway.services.sync.handler.SyncHandler.java
License:Apache License
@Override public void handle(RoutingContext ctx) { HttpServerResponse response = ctx.response(); JsonObject object = new JsonObject().put("counter", syncManager.getCounter()).put("lastRefreshAt", syncManager.getLastRefreshAt()); response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); response.setChunked(true);/*w w w.j a va 2 s. co m*/ response.write(object.encodePrettily()); response.setStatusCode(HttpStatusCode.OK_200); response.end(); }
From source file:io.openshift.booster.Errors.java
License:Apache License
public static void error(RoutingContext ctx, int status, String cause) { JsonObject error = new JsonObject().put("error", cause).put("code", status).put("path", ctx.request().path());/* w w w. j ava 2s. c o m*/ ctx.response().putHeader("Content-Type", "application/json").setStatusCode(status) .end(error.encodePrettily()); }
From source file:io.silverware.microservices.providers.cdi.internal.RestInterface.java
License:Apache License
@SuppressWarnings("checkstyle:JavadocMethod") public void callMethod(final RoutingContext routingContext) { final String microserviceName = routingContext.request().getParam("microservice"); final String methodName = routingContext.request().getParam("method"); final Bean bean = gatewayRegistry.get(microserviceName); routingContext.request().bodyHandler(buffer -> { final JsonObject mainJsonObject = new JsonObject(buffer.toString()); try {/*from w w w. j a va2 s. com*/ final Class<?> beanClass = bean.getBeanClass(); List<Method> methods = Arrays.asList(beanClass.getDeclaredMethods()).stream() .filter(method -> method.getName().equals(methodName) && method.getParameterCount() == mainJsonObject.size()) .collect(Collectors.toList()); if (methods.size() == 0) { throw new IllegalStateException( String.format("No such method %s with compatible parameters.", methodName)); } if (methods.size() > 1) { throw new IllegalStateException("Overridden methods are not supported yet."); } final Method m = methods.get(0); final Parameter[] methodParams = m.getParameters(); final Object[] paramValues = new Object[methodParams.length]; final ConvertUtilsBean convert = new ConvertUtilsBean(); for (int i = 0; i < methodParams.length; i++) { final Parameter methodParameter = methodParams[i]; final String paramName = getParamName(methodParameter, m, beanClass); final Object jsonObject = mainJsonObject.getValue(paramName); paramValues[i] = convert.convert(jsonObject, methodParameter.getType()); } @SuppressWarnings("unchecked") Set<Object> services = context.lookupLocalMicroservice( new MicroserviceMetaData(microserviceName, beanClass, bean.getQualifiers())); JsonObject response = new JsonObject(); try { Object result = m.invoke(services.iterator().next(), paramValues); response.put("result", Json.encodePrettily(result)); response.put("resultPlain", JsonWriter.objectToJson(result)); } catch (Exception e) { response.put("exception", e.toString()); response.put("stackTrace", stackTraceAsString(e)); log.warn("Could not call method: ", e); } routingContext.response().end(response.encodePrettily()); } catch (Exception e) { log.warn(String.format("Unable to call method %s#%s: ", microserviceName, methodName), e); routingContext.response().setStatusCode(503).end("Resource not available."); } }); }
From source file:io.silverware.microservices.providers.cdi.internal.RestInterface.java
License:Apache License
@SuppressWarnings({ "unchecked", "checkstyle:JavadocMethod" }) public void callNoParamMethod(final RoutingContext routingContext) { String microserviceName = routingContext.request().getParam("microservice"); String methodName = routingContext.request().getParam("method"); Bean bean = gatewayRegistry.get(microserviceName); try {/* ww w . j a v a 2 s .c o m*/ Method m = bean.getBeanClass().getDeclaredMethod(methodName); Set<Object> services = context.lookupLocalMicroservice( new MicroserviceMetaData(microserviceName, bean.getBeanClass(), bean.getQualifiers())); JsonObject response = new JsonObject(); try { Object result = m.invoke(services.iterator().next()); response.put("result", Json.encodePrettily(result)); } catch (Exception e) { response.put("exception", e.toString()); response.put("stackTrace", stackTraceAsString(e)); log.warn("Could not call method: ", e); } routingContext.response().end(response.encodePrettily()); } catch (Exception e) { log.warn(String.format("Unable to call method %s#%s: ", microserviceName, methodName), e); routingContext.response().setStatusCode(503).end("Resource not available."); } }
From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java
License:Open Source License
private void doGetStatus(final RoutingContext ctx) { JsonObject result = new JsonObject(getHonoMessagingClient().getConnectionStatus()); result.put("active profiles", activeProfiles); result.put("senders", getHonoMessagingClient().getSenderStatus()); adaptStatusResource(result);//from www . j a v a 2s . co m ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_JSON).end(result.encodePrettily()); }
From source file:org.eclipse.hono.service.auth.device.UsernamePasswordCredentials.java
License:Open Source License
/** * Matches the credentials against a given secret. * <p>/* ww w . j a v a2 s .c o m*/ * The secret is expected to be of type <em>hashed-password</em> as defined by * <a href="https://www.eclipse.org/hono/api/Credentials-API/">Hono's Credentials API</a>. * * @param candidateSecret The secret to match against. * @return {@code true} if the credentials match the secret. */ @Override public boolean matchesCredentials(final JsonObject candidateSecret) { try { final String pwdHash = candidateSecret.getString(CredentialsConstants.FIELD_SECRETS_PWD_HASH); if (pwdHash == null) { LOG.debug("candidate hashed-password secret does not contain a pwd hash"); return false; } final byte[] hashedPasswordOnRecord = Base64.getDecoder().decode(pwdHash); byte[] salt = null; final String encodedSalt = candidateSecret.getString(CredentialsConstants.FIELD_SECRETS_SALT); // the salt is optional so decodedSalt may stay null if salt was not found if (encodedSalt != null) { salt = Base64.getDecoder().decode(encodedSalt); } final String hashFunction = candidateSecret.getString(CredentialsConstants.FIELD_SECRETS_HASH_FUNCTION, CredentialsConstants.DEFAULT_HASH_FUNCTION); return checkPassword(hashFunction, salt, hashedPasswordOnRecord); } catch (final IllegalArgumentException e) { if (LOG.isDebugEnabled()) { LOG.debug("cannot decode malformed Base64 encoded property", e); } return false; } catch (final ClassCastException e) { // one or more of the properties are not of expected type if (LOG.isDebugEnabled()) { LOG.debug( "cannot process malformed candidate hashed-password secret returned by Credentials service [{}]", candidateSecret.encodePrettily()); } return false; } }
From source file:org.eclipse.hono.service.http.HttpUtils.java
License:Open Source License
/** * Writes a JSON object to an HTTP response body. * <p>/*w ww .j a v a 2 s .c om*/ * This method also sets the <em>content-type</em> and <em>content-length</em> * headers of the HTTP response accordingly but does not end the response. * * @param response The HTTP response. * @param body The JSON object to serialize to the response body (may be {@code null}). * @throws NullPointerException if response is {@code null}. */ public static void setResponseBody(final HttpServerResponse response, final JsonObject body) { Objects.requireNonNull(response); if (body != null) { final Buffer buffer = Buffer.buffer(); buffer.appendBytes(body.encodePrettily().getBytes(StandardCharsets.UTF_8)); response.putHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_JSON_UFT8) .putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(buffer.length())).write(buffer); } }
From source file:org.eclipse.hono.vertx.example.base.HonoConsumerBase.java
License:Open Source License
/** * Handler method for a <em>device ready for command</em> notification (by an explicit event or contained implicit in * another message).// w ww .j a va 2s . c o m * <p> * The code creates a simple command in JSON * * @param notification The notification containing the tenantId, deviceId and the Instant (that * defines until when this notification is valid). See {@link TimeUntilDisconnectNotification}. */ private void handleCommandReadinessNotification(final TimeUntilDisconnectNotification notification) { System.out.println(String.format("Device is ready to receive a command : <%s>.", notification.toString())); final String tenantId = notification.getTenantId(); final String deviceId = notification.getDeviceId(); honoClient.getOrCreateCommandClient(tenantId, deviceId).map(commandClient -> { final JsonObject jsonCmd = new JsonObject().put("brightness", (int) (Math.random() * 100)); final Buffer commandBuffer = Buffer.buffer(jsonCmd.encodePrettily()); // let the commandClient timeout when the notification expires commandClient.setRequestTimeout(notification.getMillisecondsUntilExpiry()); // send the command upstream to the device sendCommandToAdapter(commandClient, commandBuffer); return commandClient; }).otherwise(t -> { System.err.println(String.format("Could not create command client : %s", t.getMessage())); return null; }); }
From source file:org.entcore.auth.controllers.SamlController.java
License:Open Source License
@Override protected void afterDropSession(JsonObject event, final HttpServerRequest request, UserInfos user, final String c) { request.headers().remove("Cookie"); event.put("action", "generate-slo-request"); event.put("IDP", (String) user.getOtherProperties().get("federatedIDP")); if (log.isDebugEnabled()) { log.debug("Session metadata : " + event.encodePrettily()); }//from ww w .j ava 2 s . c om String nameID = event.getString("NameID"); if (nameID != null && !nameID.isEmpty()) { if (softSlo) { Matcher academyMatcher = NAME_QUALIFIER_PATTERN.matcher(nameID); if (academyMatcher.find()) { String nameQualifier = academyMatcher.group(1); JsonObject confSoftSlo = config.getJsonObject("soft-slo-redirect"); if (confSoftSlo != null) { String redirectIDP = confSoftSlo.getString(nameQualifier); if (redirectIDP != null) { redirect(request, redirectIDP, ""); } else { log.error("Error loading soft-slo-redirect for IDP : " + nameQualifier); redirect(request, LOGIN_PAGE); } } else { log.error("Error loading soft-slo-redirect properties."); redirect(request, LOGIN_PAGE); } } } else { // normal slo vertx.eventBus().send("saml", event, handlerToAsyncHandler(new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> event) { if (log.isDebugEnabled()) { log.debug("slo request : " + event.body().encodePrettily()); } String slo = event.body().getString("slo"); try { if (c != null && !c.isEmpty()) { slo = c + URLEncoder.encode(slo, "UTF-8"); } else { slo = URLEncoder.encode(slo, "UTF-8"); } } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); } AuthController.logoutCallback(request, slo, config, eb); } })); } } else { AuthController.logoutCallback(request, null, config, eb); } }
From source file:org.entcore.workspace.service.WorkspaceService.java
License:Open Source License
private void addAfterUpload(final JsonObject uploaded, final JsonObject doc, String name, String application, final List<String> thumbs, final String mongoCollection, final Handler<Message<JsonObject>> handler) { doc.put("name", getOrElse(name, uploaded.getJsonObject("metadata").getString("filename"), false)); doc.put("metadata", uploaded.getJsonObject("metadata")); doc.put("file", uploaded.getString("_id")); doc.put("application", getOrElse(application, WORKSPACE_NAME)); // TODO check if application name is valid log.debug(doc.encodePrettily()); mongo.save(mongoCollection, doc, new Handler<Message<JsonObject>>() { @Override/*from w w w . ja va2s .c om*/ public void handle(final Message<JsonObject> res) { if ("ok".equals(res.body().getString("status"))) { incrementStorage(doc); createRevision(res.body().getString("_id"), uploaded.getString("_id"), doc.getString("name"), doc.getString("owner"), doc.getString("owner"), doc.getString("ownerName"), doc.getJsonObject("metadata")); createThumbnailIfNeeded(mongoCollection, uploaded, res.body().getString("_id"), null, thumbs, new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> event) { if (handler != null) { handler.handle(res); } } }); } else if (handler != null) { handler.handle(res); } } }); }