Java Code Examples for io.vertx.core.json.JsonArray#contains()

The following examples show how to use io.vertx.core.json.JsonArray#contains() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Config.java    From nubes with Apache License 2.0 6 votes vote down vote up
private void createTemplateEngines() {
  JsonArray templates = json.getJsonArray("templates", new JsonArray());
  if (templates.contains("hbs")) {
    this.templateEngines.put("hbs", HandlebarsTemplateEngine.create());
  }
  if (templates.contains("jade")) {
    this.templateEngines.put("jade", JadeTemplateEngine.create());
  }
  if (templates.contains("mvel")) {
    this.templateEngines.put("templ", MVELTemplateEngine.create());
  }
  if (templates.contains("thymeleaf")) {
    this.templateEngines.put("html", ThymeleafTemplateEngine.create());
  }

}
 
Example 2
Source File: ConsulBackendService.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
private ServiceOptions recordToServiceOptions(Record record, String uuid) {
  ServiceOptions serviceOptions = new ServiceOptions();
  serviceOptions.setName(record.getName());
  JsonArray tags = new JsonArray();
  if (record.getMetadata() != null) {
    tags.addAll(record.getMetadata().getJsonArray("tags", new JsonArray()));
    //only put CheckOptions to newly registered services
    if (record.getRegistration() == null) {
      serviceOptions.setCheckOptions(new CheckOptions(record.getMetadata().getJsonObject("checkoptions", new JsonObject())));
      record.getMetadata().remove("checkoptions");
    }
    record.getMetadata().remove("tags");
    //add metadata object to the tags, so it can be retrieved
    tags.add("metadata:" + record.getMetadata().encode());
  }
  if (record.getRegistration() != null) {
    serviceOptions.setId(record.getRegistration());
  } else {
    serviceOptions.setId(uuid);
  }
  //add the record type to the tags
  if (!tags.contains(record.getType()) && record.getType() != null) {
    tags.add(record.getType());
  }
  // only put address and port if this is an HTTP endpoint, to be sure that's an IP address, so we can use DNS queries
  if (record.getLocation() != null) {
    if (record.getLocation().containsKey("host")) {
      serviceOptions.setAddress(record.getLocation().getString("host"));
    }
    if (record.getLocation().containsKey("port")) {
      serviceOptions.setPort(record.getLocation().getInteger("port"));
    }
    //add location object to the tags, so it can be retrieved
    tags.add("location:" + record.getLocation().encode());
  }
  serviceOptions.setTags(tags.stream().map(String::valueOf).collect(Collectors.toList()));
  return serviceOptions;
}
 
Example 3
Source File: RestVerticle.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
/**
 * check accept and content-type headers if no - set the request asa not valid and return error to user
 */
private void checkAcceptContentType(JsonArray produces, JsonArray consumes, RoutingContext rc, boolean[] validRequest) {
  /*
   * NOTE that the content type and accept headers will accept a partial match - for example: if the raml indicates a text/plain and an
   * application/json content-type and only one is passed - it will accept it
   */
  // check allowed content types in the raml for this resource + method
  HttpServerRequest request = rc.request();
  if (consumes != null && validRequest[0]) {
    // get the content type passed in the request
    // if this was left out by the client they must add for request to return
    // clean up simple stuff from the clients header - trim the string and remove ';' in case
    // it was put there as a suffix
    String contentType = StringUtils.defaultString(request.getHeader("Content-type")).replaceFirst(";.*", "").trim();
    if (!consumes.contains(removeBoundry(contentType))) {
      endRequestWithError(rc, 400, true, messages.getMessage("en", MessageConsts.ContentTypeError, consumes, contentType),
        validRequest);
    }
  }

  // type of data expected to be returned by the server
  if (produces != null && validRequest[0]) {
    String accept = StringUtils.defaultString(request.getHeader("Accept"));
    if (acceptCheck(produces, accept) == null) {
      // use contains because multiple values may be passed here
      // for example json/application; text/plain mismatch of content type found
      endRequestWithError(rc, 400, true, messages.getMessage("en", MessageConsts.AcceptHeaderError, produces, accept),
        validRequest);
    }
  }
}
 
Example 4
Source File: ClientGenerator.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
public void generateMethodMeta(String methodName, JsonObject params, String url,
    String httpVerb, JsonArray contentType, JsonArray accepts){

  /* Adding method to the Class which is public and returns void */

  JMethod jmCreate = method(JMod.PUBLIC, void.class, methodName);
  JBlock body = jmCreate.body();

  /* create the query parameter string builder */
  JVar queryParams = body.decl(jcodeModel._ref(StringBuilder.class), "queryParams",
          JExpr._new(jcodeModel.ref(StringBuilder.class)).arg("?"));


  ////////////////////////---- Handle place holders in the url  ----//////////////////
  /* create request */
  /* Handle place holders in the URL
    * replace {varName} with "+varName+" so that it will be replaced
    * in the url at runtime with the correct values */
  Matcher m = Pattern.compile("\\{.*?\\}").matcher(url);
  while(m.find()){
    String varName = m.group().replace("{","").replace("}", "");
    url = url.replace("{"+varName+"}", "\"+"+varName+"+\"");
  }

  url = "\""+url.substring(1)+"\"+queryParams.toString()";

  /* Adding java doc for method */
  jmCreate.javadoc().add("Service endpoint " + url);


  /* iterate on function params and add the relevant ones
   * --> functionSpecificQueryParamsPrimitives is populated by query parameters that are primitives
   * --> functionSpecificHeaderParams (used later on) is populated by header params
   * --> functionSpecificQueryParamsEnums is populated by query parameters that are enums */
  Iterator<Entry<String, Object>> paramList = params.iterator();

  boolean [] bodyContentExists = new boolean[]{false};
  paramList.forEachRemaining(entry -> {
    String valueName = ((JsonObject) entry.getValue()).getString("value");
    String valueType = ((JsonObject) entry.getValue()).getString("type");
    String paramType = ((JsonObject) entry.getValue()).getString("param_type");
    if(handleParams(jmCreate, queryParams, paramType, valueType, valueName)){
      bodyContentExists[0] = true;
    }
  });

  //////////////////////////////////////////////////////////////////////////////////////

  /* create the http client request object */
  body.directStatement("io.vertx.core.http.HttpClientRequest request = httpClient."+
      httpVerb.substring(httpVerb.lastIndexOf('.')+1).toLowerCase()+"Abs(okapiUrl+"+url+");");
  body.directStatement("request.handler(responseHandler);");

  /* add headers to request */
  functionSpecificHeaderParams.forEach(body::directStatement);
  //reset for next method usage
  functionSpecificHeaderParams = new ArrayList<>();

  /* add content and accept headers if relevant */
  if(contentType != null){
    String cType = contentType.toString().replace("\"", "").replace("[", "").replace("]", "");
    if(contentType.contains("multipart/form-data")){
      body.directStatement("request.putHeader(\"Content-type\", \""+cType+"; boundary=--BOUNDARY\");");
    }
    else{
      body.directStatement("request.putHeader(\"Content-type\", \""+cType+"\");");
    }
  }
  if(accepts != null){
    String aType = accepts.toString().replace("\"", "").replace("[", "").replace("]", "");
    //replace any/any with */* to allow declaring accpet */* which causes compilation issues
    //when declared in raml. so declare any/any in raml instead and replaced here
    aType = aType.replaceAll("any/any", "");
    body.directStatement("request.putHeader(\"Accept\", \""+aType+"\");");
  }

  /* push tenant id into x-okapi-tenant and authorization headers for now */
  JConditional ifClause = body._if(tenantId.ne(JExpr._null()));
  ifClause._then().directStatement("request.putHeader(\"X-Okapi-Token\", token);");
  ifClause._then().directStatement("request.putHeader(\""+OKAPI_HEADER_TENANT+"\", tenantId);");

  JConditional ifClause2 = body._if(this.okapiUrl.ne(JExpr._null()));
  ifClause2._then().directStatement("request.putHeader(\"X-Okapi-Url\", okapiUrl);");

  /* add response handler to each function */
  JClass handler = jcodeModel.ref(Handler.class).narrow(HttpClientResponse.class);
  jmCreate.param(handler, "responseHandler");

  /* if we need to pass data in the body */
  if(bodyContentExists[0]){
    body.directStatement("request.putHeader(\"Content-Length\", buffer.length()+\"\");");
    body.directStatement("request.setChunked(true);");
    body.directStatement("request.write(buffer);");
  }

  body.directStatement("request.end();");
}