List of usage examples for io.vertx.core.json JsonObject getBoolean
public Boolean getBoolean(String key, Boolean def)
From source file:io.gravitee.resource.oauth2.am.OAuth2AMResource.java
License:Apache License
@Override public void introspect(String accessToken, Handler<OAuth2Response> responseHandler) { HttpClient httpClient = httpClients.computeIfAbsent(Vertx.currentContext(), context -> vertx.createHttpClient(httpClientOptions)); logger.debug("Introspect access token by requesting {}", introspectionEndpointURI); HttpClientRequest request = httpClient.post(introspectionEndpointURI); request.headers().add(HttpHeaders.AUTHORIZATION, introspectionEndpointAuthorization); request.headers().add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); request.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED); request.handler(response -> response.bodyHandler(buffer -> { logger.debug("AM Introspection endpoint returns a response with a {} status code", response.statusCode());//from www .j a v a 2s . com if (response.statusCode() == HttpStatusCode.OK_200) { // Introspection Response for AM v2 always returns HTTP 200 // with an "active" boolean indicator of whether or not the presented token is currently active. if (configuration().getVersion() == OAuth2ResourceConfiguration.Version.V2_X) { // retrieve active indicator JsonObject jsonObject = buffer.toJsonObject(); boolean active = jsonObject.getBoolean(INTROSPECTION_ACTIVE_INDICATOR, false); responseHandler.handle(new OAuth2Response(active, (active) ? buffer.toString() : "{\"error\": \"Invalid Access Token\"}")); } else { responseHandler.handle(new OAuth2Response(true, buffer.toString())); } } else { responseHandler.handle(new OAuth2Response(false, buffer.toString())); } })); request.exceptionHandler(event -> { logger.error("An error occurs while checking access_token", event); responseHandler.handle(new OAuth2Response(false, event.getMessage())); }); request.end("token=" + accessToken); }
From source file:io.knotx.knot.templating.HandlebarsKnotConfiguration.java
License:Apache License
public HandlebarsKnotConfiguration(JsonObject config) { this.address = config.getString("address"); this.templateDebug = config.getBoolean("templateDebug", false); }
From source file:io.knotx.server.KnotxServerConfiguration.java
License:Apache License
public KnotxServerConfiguration(JsonObject config) { httpPort = config.getInteger("httpPort"); splitterAddress = config.getJsonObject("splitter").getString("address"); assemblerAddress = config.getJsonObject("assembler").getString("address"); displayExceptionDetails = config.getBoolean("displayExceptionDetails", false); engineRouting = Maps.newEnumMap(HttpMethod.class); config.getJsonObject("routing").stream().forEach(this::parseMethodRouting); repositoryAddressMapping = Maps.newHashMap(); config.getJsonArray("repositories").stream().map(item -> (JsonObject) item) .forEach(object -> repositoryAddressMapping.put(object.getString("path"), new RepositoryEntry(object.getString("address"), object.getBoolean("doProcessing", true)))); allowedResponseHeaders = config.getJsonArray("allowedResponseHeaders").stream() .map(item -> ((String) item).toLowerCase()).collect(Collectors.toSet()); }
From source file:io.nitor.api.backend.NitorBackend.java
License:Apache License
private void setupStaticFiles(JsonObject service, ServiceRouterBuilder routerBuilder) { int cacheTimeout = service.getInteger("cacheTimeout", (int) MINUTES.toSeconds(30)); routerBuilder.route(GET, service.getString("route"), StaticHandler.create().setFilesReadOnly(service.getBoolean("readOnly", true)) .setAllowRootFileSystemAccess(true).setWebRoot(service.getString("dir", ".")) .setCachingEnabled(cacheTimeout > 0).setCacheEntryTimeout(cacheTimeout), null);/*from w w w. j a v a 2 s . c o m*/ String staticPathConfig = service.getString("staticPaths"); if (staticPathConfig != null) { Pattern staticPaths = Pattern.compile(staticPathConfig); String routePrefix = service.getString("route"); String cleanRoute = cleanRoute(routePrefix); routerBuilder.route(GET, routePrefix, ctx -> { String normalised = ctx.normalisedPath().substring(1); if (!staticPaths.matcher(normalised).matches()) { ctx.reroute(cleanRoute + "/index.html"); } else { ctx.next(); } }, null); } }
From source file:io.nitor.api.backend.proxy.SetupProxy.java
License:Apache License
public static void setupProxy(Vertx vertx, ServiceRouterBuilder routerBuilder, JsonObject proxyConf, HttpServerOptions serverOptions, boolean isOrigReqHttps) { boolean ssl = proxyConf.getBoolean("ssl", false); HttpClient client = vertx.createHttpClient(new HttpClientOptions() .setConnectTimeout((int) SECONDS.toMillis(proxyConf.getInteger("connectTimeout", 10))) .setIdleTimeout((int) SECONDS.toSeconds(proxyConf.getInteger("idleTimeout", 15))) .setMaxPoolSize(proxyConf.getInteger("maxPoolSize", 30)) .setPipelining(proxyConf.getInteger("pipelineDepth", 0) > 1) .setPipeliningLimit(proxyConf.getInteger("pipelineDepth", 1)).setMaxWaitQueueSize(100) .setUsePooledBuffers(true).setProtocolVersion(HTTP_1_1).setTryUseCompression(false).setSsl(ssl)); String prefix = proxyConf.getString("path", ""); if (prefix.endsWith("/")) { prefix = prefix.substring(0, prefix.length() - 1); }/*from w ww . j a v a2 s .c o m*/ String route = proxyConf.getString("route", ""); if (route.endsWith("*")) { route = route.substring(0, route.length() - 1); } if (route.endsWith("/")) { route = route.substring(0, route.length() - 1); } final String proxyRoute = route; final Proxy.Target proxyTarget = new Proxy.Target(proxyConf.getString("host"), proxyConf.getInteger("port"), prefix, proxyConf.getString("hostHeader")); logger.info("Proxying {} to {}://{}:{}/{}", route, ssl ? "https" : "http", proxyTarget.socketHost, proxyTarget.socketPort, proxyTarget.uri); Proxy proxy = new Proxy(client, (routingContext, targetHandler) -> { String suffix = routingContext.request().uri().substring(proxyRoute.length()); targetHandler.handle(proxyTarget.withSuffix(suffix)); }, serverOptions.getIdleTimeout(), proxyConf.getInteger("clientReceiveTimeout", 300), isOrigReqHttps, SimpleLogProxyTracer::new, new DefaultPumpStarter()); if (proxyConf.getJsonObject("addHeaders") != null) { final Map<String, String> addHeaders = new HashMap<>(); for (Map.Entry<String, Object> entry : proxyConf.getJsonObject("addHeaders")) { addHeaders.put(entry.getKey(), entry.getValue().toString()); } proxy.addHeaders(addHeaders); } routerBuilder.route(proxyConf.getString("route"), proxy::handle, routingContext -> { if (routingContext.failed()) { Throwable error = routingContext.failure(); logger.warn("General failure handler", error); String statusMsg = ""; int statusCode = BAD_GATEWAY.code(); if (error instanceof ProxyException) { ProxyException ex = (ProxyException) error; statusCode = ex.statusCode; if (ex.getCause() != null) { statusMsg = ex.getCause().getMessage(); } else if (ex.reason == RejectReason.noHostHeader) { statusMsg = "Exhausted resources while trying to extract Host header from the request"; } } if (!routingContext.response().headWritten() && !routingContext.response().ended()) { routingContext.response().setStatusCode(statusCode); routingContext.response().headers().set("content-type", "text/plain;charset=UTF-8"); routingContext.response().end(statusMsg); } } else { routingContext.next(); } }); }
From source file:io.nitor.api.backend.tls.SetupHttpServerOptions.java
License:Apache License
public static HttpServerOptions createHttpServerOptions(JsonObject config) { JsonObject tls = config.getJsonObject("tls"); HttpServerOptions httpOptions = new HttpServerOptions() // basic TCP/HTTP options .setReuseAddress(true).setCompressionSupported(false) // otherwise it automatically compresses based on response headers even if pre-compressed with e.g. proxy .setUsePooledBuffers(true).setCompressionLevel(2) .setIdleTimeout(config.getInteger("idleTimeout", (int) MINUTES.toSeconds(10))); if (!config.getBoolean("http2", true)) { httpOptions.setAlpnVersions(asList(HTTP_1_1)); }//from ww w . j a va 2s.c om if (tls != null) { httpOptions.setSsl(true) // server side certificate .setPemKeyCertOptions(new PemKeyCertOptions().setKeyPath(tls.getString("serverKey")) .setCertPath(tls.getString("serverCert"))) // TLS tuning .addEnabledSecureTransportProtocol("TLSv1.2").addEnabledSecureTransportProtocol("TLSv1.3"); JsonObject clientAuth = config.getJsonObject("clientAuth"); if (httpOptions.isSsl() && clientAuth != null && clientAuth.getString("clientChain") != null) { // client side certificate httpOptions.setClientAuth(REQUEST) .setTrustOptions(new PemTrustOptions().addCertPath(clientAuth.getString("clientChain"))); } if (TRUE.equals(config.getBoolean("useNativeOpenSsl"))) { httpOptions.setUseAlpn(true).setSslEngineOptions(new OpenSSLEngineOptions()); cipherSuites.stream().map(SetupHttpServerOptions::javaCipherNameToOpenSSLName) .forEach(httpOptions::addEnabledCipherSuite); } else { httpOptions.setUseAlpn(DynamicAgent.enableJettyAlpn()) .setJdkSslEngineOptions(new JdkSSLEngineOptions()); cipherSuites.forEach(httpOptions::addEnabledCipherSuite); } } return httpOptions; }
From source file:net.kuujo.vertigo.network.impl.BasePortConfigImpl.java
License:Apache License
@Override @SuppressWarnings("unchecked") public void update(JsonObject port) { if (this.name == null) { this.name = port.getString(PORT_NAME); }// ww w. j a v a2 s. co m String type = port.getString(PORT_TYPE); if (type != null) { this.type = resolver.resolve(type); } else { this.type = Object.class; } String codec = port.getString(PORT_CODEC); if (codec != null) { try { this.codec = (Class<? extends MessageCodec>) Class.forName(codec); } catch (ClassNotFoundException e) { throw new VertigoException(e); } } if (port.containsKey(PORT_PERSISTENT)) { this.persistent = port.getBoolean(PORT_PERSISTENT, false); } }
From source file:org.apache.servicecomb.config.client.MemberDiscovery.java
License:Apache License
public void refreshMembers(JsonObject members) { List<String> newServerAddresses = new ArrayList<>(); members.getJsonArray("instances").forEach(m -> { JsonObject instance = (JsonObject) m; if ("UP".equals(instance.getString("status", "UP"))) { String endpoint = instance.getJsonArray("endpoints").getString(0); String scheme = instance.getBoolean("isHttps", false) ? "https" : "http"; newServerAddresses.add(scheme + SCHEMA_SEPRATOR + endpoint.substring(endpoint.indexOf(SCHEMA_SEPRATOR) + SCHEMA_SEPRATOR.length())); }/*from w w w . ja va 2 s . c o m*/ }); synchronized (lock) { this.configServerAddresses.clear(); this.configServerAddresses.addAll(newServerAddresses); Collections.shuffle(this.configServerAddresses); } LOGGER.info("New config center members: {}", this.configServerAddresses); }
From source file:org.eclipse.hono.service.registration.BaseRegistrationService.java
License:Open Source License
private boolean isDeviceEnabled(final JsonObject registrationData) { return registrationData.getBoolean(FIELD_ENABLED, Boolean.TRUE); }
From source file:org.eclipse.hono.util.RequestResponseApiConstants.java
License:Open Source License
/** * Build a Proton message as a reply for an endpoint from the json payload that e.g. is received from the vert.x eventbus * from the implementing service.//from ww w .j a v a 2 s .c o m * * @param endpoint The endpoint the reply message will be built for. * @param payload The json payload received. * @return Message The built Proton message. */ public static final Message getAmqpReply(final String endpoint, final JsonObject payload) { final String tenantId = payload.getString(FIELD_TENANT_ID); final String deviceId = payload.getString(FIELD_DEVICE_ID); final String status = payload.getString(MessageHelper.APP_PROPERTY_STATUS); final JsonObject correlationIdJson = payload.getJsonObject(MessageHelper.SYS_PROPERTY_CORRELATION_ID); final Object correlationId = MessageHelper.decodeIdFromJson(correlationIdJson); final boolean isApplCorrelationId = payload.getBoolean(MessageHelper.ANNOTATION_X_OPT_APP_CORRELATION_ID, false); return getAmqpReply(endpoint, status, correlationId, tenantId, deviceId, isApplCorrelationId, payload.getJsonObject(CredentialsConstants.FIELD_PAYLOAD)); }