io.vertx.ext.web.impl.Utils Java Examples

The following examples show how to use io.vertx.ext.web.impl.Utils. 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: OpenAPI3RequestValidationHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private void handleContent(Parameter parameter) {
  Content contents = parameter.getContent();
  ParameterLocation location = resolveLocation(parameter.getIn());
  List<MediaType> jsonsContents = OpenApi3Utils.extractTypesFromMediaTypesMap(contents, Utils::isJsonContentType);
  if (jsonsContents.size() == 1) {
    this.addRule(ParameterValidationRuleImpl.ParameterValidationRuleFactory
      .createValidationRuleWithCustomTypeValidator(parameter.getName(), JsonTypeValidator.JsonTypeValidatorFactory
        .createJsonTypeValidator(OpenApi3Utils.generateSanitizedJsonSchemaNode(jsonsContents.get(0).getSchema(), this.spec)),
        !OpenApi3Utils.isRequiredParam(parameter), OpenApi3Utils.resolveAllowEmptyValue(parameter), location), location);
  } else if (contents.size() > 1 && !jsonsContents.isEmpty()) {
    // Mount anyOf
    List<ParameterTypeValidator> validators =
      jsonsContents.stream().map(e -> JsonTypeValidator.JsonTypeValidatorFactory
        .createJsonTypeValidator(OpenApi3Utils.generateSanitizedJsonSchemaNode(e.getSchema(), this.spec))).collect(Collectors.toList());
    validators.add(CONTENT_TYPE_VALIDATOR);
    AnyOfTypeValidator validator = new AnyOfTypeValidator(validators);
    this.addRule(ParameterValidationRuleImpl.ParameterValidationRuleFactory
      .createValidationRuleWithCustomTypeValidator(parameter.getName(), validator, !OpenApi3Utils.isRequiredParam(parameter), OpenApi3Utils.resolveAllowEmptyValue(parameter)
        , location), location);
  } else {
    this.addRule(ParameterValidationRuleImpl.ParameterValidationRuleFactory
      .createValidationRuleWithCustomTypeValidator(parameter.getName(), CONTENT_TYPE_VALIDATOR, !OpenApi3Utils.isRequiredParam(parameter), 
              OpenApi3Utils.resolveAllowEmptyValue(parameter), location), location);
  }
}
 
Example #2
Source File: GraphiQLHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext rc) {
  if (!options.isEnabled()) {
    rc.next();
    return;
  }
  String filename = Utils.pathOffset(rc.normalizedPath(), rc);
  if (filename.isEmpty()) {
    rc.response().setStatusCode(301).putHeader(HttpHeaders.LOCATION, rc.currentRoute().getPath()).end();
    return;
  }
  if ("/".equals(filename) || "/index.html".equals(filename)) {
    String resource = rc.vertx().fileSystem()
      .readFileBlocking(WEBROOT + "/index.html")
      .toString(UTF_8)
      .replace("__VERTX_GRAPHIQL_CONFIG__", replacement(rc));
    rc.response()
      .putHeader(HttpHeaders.CACHE_CONTROL, "no-cache")
      .putHeader(HttpHeaders.CONTENT_TYPE, "text/html;charset=utf8")
      .end(resource);
  } else {
    staticHandler.handle(rc);
  }
}
 
Example #3
Source File: RoutingContext.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
/**
 * Check if the request is fresh, aka
 * Last-Modified and/or the ETag
 * still match.
 *
 * @return true if content is fresh according to the cache.
 */
default boolean isFresh() {
  final HttpMethod method = request().method();

  // GET or HEAD for weak freshness validation only
  if (method != HttpMethod.GET && method != HttpMethod.HEAD) {
    return false;
  }

  final int s = response().getStatusCode();
  // 2xx or 304 as per rfc2616 14.26
  if ((s >= 200 && s < 300) || 304 == s) {
    return Utils.fresh(this);
  }

  return false;
}
 
Example #4
Source File: StaticHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private void testDirectoryListingHtmlCustomTemplate(String dirTemplateFile) throws Exception {
  stat.setDirectoryListing(true);


  String directoryTemplate = Utils.readResourceToBuffer(dirTemplateFile).toString();

  String parentLink = "<a href=\"/\">..</a>";
  String files = "<ul id=\"files\"><li><a href=\"/somedir2/foo2.json\" title=\"foo2.json\">foo2.json</a></li>" +
    "<li><a href=\"/somedir2/somepage.html\" title=\"somepage.html\">somepage.html</a></li>" +
    "<li><a href=\"/somedir2/somepage2.html\" title=\"somepage2.html\">somepage2.html</a></li></ul>";

  String expected = directoryTemplate.replace("{directory}", "/somedir2/").replace("{parent}", parentLink).replace("{files}", files);

  testRequest(HttpMethod.GET, "/somedir2/", req -> req.putHeader("accept", "text/html"), resp -> resp.bodyHandler(buff -> {
    assertEquals("text/html", resp.headers().get("content-type"));
    String sBuff = buff.toString();
    assertEquals(expected, sBuff);
    testComplete();
  }), 200, "OK", null);
  await();
}
 
Example #5
Source File: StaticHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheFilesFileDeleted() throws Exception {
  File webroot = new File("target/.vertx/webroot"), pageFile = new File(webroot, "deleted.html");
  if (!pageFile.exists()) {
    webroot.mkdirs();
    pageFile.createNewFile();
  }
  String page = '/' + pageFile.getName();

  stat.setFilesReadOnly(false);
  stat.setWebRoot(webroot.getPath());
  stat.setCacheEntryTimeout(3600 * 1000);

  long modified = Utils.secondsFactor(pageFile.lastModified());
  testRequest(HttpMethod.GET, page, req -> req.putHeader("if-modified-since", Utils.formatRFC1123DateTime(modified)), null, 304, "Not Modified", null);
  pageFile.delete();
  testRequest(HttpMethod.GET, page, 404, "Not Found");
  testRequest(HttpMethod.GET, page, req -> req.putHeader("if-modified-since", Utils.formatRFC1123DateTime(modified)), null, 404, "Not Found", null);

}
 
Example #6
Source File: StaticHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
/**
 * Create all required header so content can be cache by Caching servers or Browsers
 *
 * @param request base HttpServerRequest
 * @param props   file properties
 */
private void writeCacheHeaders(HttpServerRequest request, FileProps props) {

  MultiMap headers = request.response().headers();

  if (cache.enabled()) {
    // We use cache-control and last-modified
    // We *do not use* etags and expires (since they do the same thing - redundant)
    Utils.addToMapIfAbsent(headers, HttpHeaders.CACHE_CONTROL, "public, max-age=" + maxAgeSeconds);
    Utils.addToMapIfAbsent(headers, HttpHeaders.LAST_MODIFIED, Utils.formatRFC1123DateTime(props.lastModifiedTime()));
    // We send the vary header (for intermediate caches)
    // (assumes that most will turn on compression when using static handler)
    if (sendVaryHeader && request.headers().contains(HttpHeaders.ACCEPT_ENCODING)) {
      Utils.addToMapIfAbsent(headers, "Vary", "accept-encoding");
    }
  }
  // date header is mandatory
  headers.set("date", Utils.formatRFC1123DateTime(System.currentTimeMillis()));
}
 
Example #7
Source File: InterceptableRoutingContextImplTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test
public void testOthers() {
    Assert.assertEquals(mountPoint, contextToTest.mountPoint());
    Assert.assertEquals(Utils.normalizePath(mountPoint), contextToTest.normalisedPath());
    Assert.assertEquals(null, contextToTest.currentRoute());
    Assert.assertEquals(-1, contextToTest.statusCode());
    Assert.assertEquals(null, contextToTest.failure());
    Assert.assertEquals(myVertx, contextToTest.vertx());
    Assert.assertEquals(false, contextToTest.failed());

    Session sess = new SessionImpl();
    contextToTest.setSession(sess);
    Assert.assertEquals(sess, contextToTest.session());
}
 
Example #8
Source File: OpenAPI3RequestValidationHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private void parseRequestBody(RequestBody requestBody) {
  if (requestBody != null && requestBody.getContent() != null) {
    for (Map.Entry<String, ? extends MediaType> mediaType : requestBody.getContent().entrySet()) {
      if (Utils.isJsonContentType(mediaType.getKey()) && mediaType.getValue().getSchema() != null) {
        this.setEntireBodyValidator(JsonTypeValidator.JsonTypeValidatorFactory
          .createJsonTypeValidator(OpenApi3Utils.generateSanitizedJsonSchemaNode(mediaType.getValue().getSchema(), this.spec)));
      } else if (mediaType.getKey().equals("application/x-www-form-urlencoded") && mediaType.getValue().getSchema()
        != null) {
        for (Map.Entry<String, ? extends Schema> paramSchema : ((Map<String, Schema>) mediaType.getValue().getSchema().getProperties())
          .entrySet()) {
          this.addFormParamRule(ParameterValidationRuleImpl.ParameterValidationRuleFactory
            .createValidationRuleWithCustomTypeValidator(paramSchema.getKey(), this
              .resolveSchemaTypeValidatorFormEncoded(paramSchema.getValue()), !OpenApi3Utils.isRequiredParam
              (mediaType.getValue().getSchema(), paramSchema.getKey()), false, ParameterLocation.BODY_FORM));
        }
      } else if (mediaType.getKey().equals("multipart/form-data") && mediaType.getValue().getSchema() != null &&
        mediaType.getValue().getSchema().getType().equals("object")) {
        for (Map.Entry<String, ? extends Schema> multipartProperty : ((Map<String, Schema>) mediaType.getValue().getSchema().getProperties())
          .entrySet()) {
          Encoding encodingProperty = null;
          if (mediaType.getValue().getEncoding() != null)
            encodingProperty = mediaType.getValue().getEncoding().get(multipartProperty.getKey());
          String contentTypeRegex = null;
          if (encodingProperty != null && encodingProperty.getContentType() != null)
            contentTypeRegex = OpenApi3Utils.resolveContentTypeRegex(encodingProperty.getContentType());

          handleMultimapParameter(multipartProperty.getKey(), contentTypeRegex, multipartProperty.getValue(),
            mediaType.getValue().getSchema());
        }
      } else {
        this.addBodyFileRule(mediaType.getKey());
      }
    }
    this.bodyRequired = safeBoolean.apply(requestBody.getRequired());
  }
}
 
Example #9
Source File: FaviconHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private void testFaviconPath(FaviconHandler favicon, long maxAgeSeconds) throws Exception {
  router.route().handler(favicon);
  router.route().handler(rc -> rc.response().end());
  Buffer icon = Utils.readResourceToBuffer("favicon.ico");
  testRequestBuffer(HttpMethod.GET, "/favicon.ico", null, resp -> {
    assertEquals("image/x-icon", resp.headers().get("content-type"));
    assertEquals(icon.length(), Integer.valueOf(resp.headers().get("content-length")).intValue());
    assertEquals("public, max-age=" + maxAgeSeconds, resp.headers().get("cache-control"));
  }, 200, "OK", icon);
}
 
Example #10
Source File: CookieHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testCookieFields() throws Exception {
  Cookie cookie = Cookie.cookie("foo", "bar");
  assertEquals("foo", cookie.getName());
  assertEquals("bar", cookie.getValue());
  assertEquals("foo=bar", cookie.encode());
  assertNull(cookie.getPath());
  cookie.setPath("/somepath");
  assertEquals("/somepath", cookie.getPath());
  assertEquals("foo=bar; Path=/somepath", cookie.encode());
  assertNull(cookie.getDomain());
  cookie.setDomain("foo.com");
  assertEquals("foo.com", cookie.getDomain());
  assertEquals("foo=bar; Path=/somepath; Domain=foo.com", cookie.encode());
  long maxAge = 30 * 60;
  cookie.setMaxAge(maxAge);


  long now = System.currentTimeMillis();
  String encoded = cookie.encode();
  int startPos = encoded.indexOf("Expires=");
  int endPos = encoded.indexOf(';', startPos);
  String expiresDate = encoded.substring(startPos + 8, endPos);
  Date d = new Date(Utils.parseRFC1123DateTime(expiresDate));
  assertTrue(d.getTime() - now >= maxAge);

  cookie.setMaxAge(Long.MIN_VALUE);
  cookie.setSecure(true);
  assertEquals("foo=bar; Path=/somepath; Domain=foo.com; Secure", cookie.encode());
  cookie.setHttpOnly(true);
  assertEquals("foo=bar; Path=/somepath; Domain=foo.com; Secure; HTTPOnly", cookie.encode());
}
 
Example #11
Source File: StaticHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private long toDateTime(String header) {
  try {
    return  Utils.parseRFC1123DateTime(header);
  } catch (Exception e) {
    fail(e.getMessage());
    return -1;
  }
}
 
Example #12
Source File: TemplateTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public void render(Map<String, Object> context, String templateFileName, Handler<AsyncResult<Buffer>> handler) {
  if (fail) {
    handler.handle(Future.failedFuture(new Exception("eek")));
  } else {
    String templ = Utils.readFileToString(vertx, templateFileName);
    String rendered = templ.replace("{foo}", (String) context.get("foo"));
    rendered = rendered.replace("{bar}", (String) context.get("bar"));
    handler.handle(Future.succeededFuture(Buffer.buffer(rendered)));
  }
}
 
Example #13
Source File: UserHolder.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public int readFromBuffer(int pos, Buffer buffer) {
  byte b = buffer.getByte(pos++);
  if (b == (byte)1) {
    int len = buffer.getInt(pos);
    pos += 4;
    byte[] bytes = buffer.getBytes(pos, pos + len);
    pos += len;
    String className = new String(bytes, StandardCharsets.UTF_8);
    try {
      Class<?> clazz = Utils.getClassLoader().loadClass(className);
      if (!ClusterSerializable.class.isAssignableFrom(clazz)) {
        throw new ClassCastException(className + " is not ClusterSerializable");
      }
      ClusterSerializable obj = (ClusterSerializable) clazz.getDeclaredConstructor().newInstance();
      pos = obj.readFromBuffer(pos, buffer);
      synchronized (this) {
        user = (User) obj;
        context = null;
      }
    } catch (Exception e) {
      throw new VertxException(e);
    }
  } else {
    synchronized (this) {
      user = null;
      context = null;
    }
  }
  return pos;
}
 
Example #14
Source File: TemplateHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
  String file = Utils.pathOffset(context.normalizedPath(), context);
  if (file.endsWith("/") && null != indexTemplate) {
    file += indexTemplate;
  }
  // files are always normalized (start with /)
  // however if there's no base strip / to avoid making the path absolute
  if (templateDirectory == null || "".equals(templateDirectory)) {
    // strip the leading slash from the filename
    file = file.substring(1);
  }
  // put the locale if present and not on the context yet into the context.
  if (!context.data().containsKey("lang")) {
    for (LanguageHeader acceptableLocale : context.acceptableLanguages()) {
      try {
        Locale.forLanguageTag(acceptableLocale.value());
      } catch (RuntimeException e) {
        // we couldn't parse the locale so it's not valid or unknown
        continue;
      }
      context.data().put("lang", acceptableLocale.value());
      break;
    }
  }
  // render using the engine
  engine.render(new JsonObject(context.data()), templateDirectory + file, res -> {
    if (res.succeeded()) {
      context.response().putHeader(HttpHeaders.CONTENT_TYPE, contentType).end(res.result());
    } else {
      context.fail(res.cause());
    }
  });
}
 
Example #15
Source File: RoutingContext.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
/**
 * Set the Last-Modified date using a Instant.
 *
 * @param instant the last modified instant
 */
@Fluent
@GenIgnore(PERMITTED_TYPE)
default RoutingContext lastModified(Instant instant) {
  response().putHeader(HttpHeaders.LAST_MODIFIED, Utils.formatRFC1123DateTime(instant.toEpochMilli()));
  return this;
}
 
Example #16
Source File: FreeMarkerTemplateHander.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
	String file = Utils.pathOffset(context.normalisedPath(), context);
	if (file != null && file.startsWith("/")) {
		file = file.substring(1);
	}
	render(new JsonObject(context.data()), file, res -> {
		if (res.succeeded()) {
			context.response().putHeader(HttpHeaders.CONTENT_TYPE, contentType).end(res.result());
		} else {
			context.fail(res.cause());
		}
	});

}
 
Example #17
Source File: StaticHandlerImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
private String getFile(String path, RoutingContext context) {
  String file = webRoot + Utils.pathOffset(path, context);
  if (log.isTraceEnabled()) log.trace("File to serve is " + file);
  return file;
}
 
Example #18
Source File: SharedDataSessionImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
private int readDataFromBuffer(int pos, Buffer buffer) {
  try {
    int entries = buffer.getInt(pos);
    pos += 4;
    if (entries > 0) {
      final Map<String, Object> data = new ConcurrentHashMap<>(entries);

      for (int i = 0; i < entries; i++) {
        int keylen = buffer.getInt(pos);
        pos += 4;
        byte[] keyBytes = buffer.getBytes(pos, pos + keylen);
        pos += keylen;
        String key = new String(keyBytes, UTF8);
        byte type = buffer.getByte(pos++);
        Object val;
        switch (type) {
          case TYPE_LONG:
            val = buffer.getLong(pos);
            pos += 8;
            break;
          case TYPE_INT:
            val = buffer.getInt(pos);
            pos += 4;
            break;
          case TYPE_SHORT:
            val = buffer.getShort(pos);
            pos += 2;
            break;
          case TYPE_BYTE:
            val = buffer.getByte(pos);
            pos++;
            break;
          case TYPE_FLOAT:
            val = buffer.getFloat(pos);
            pos += 4;
            break;
          case TYPE_DOUBLE:
            val = buffer.getDouble(pos);
            pos += 8;
            break;
          case TYPE_CHAR:
            short s = buffer.getShort(pos);
            pos += 2;
            val = (char) s;
            break;
          case TYPE_BOOLEAN:
            byte b = buffer.getByte(pos);
            pos++;
            val = b == 1;
            break;
          case TYPE_STRING:
            int len = buffer.getInt(pos);
            pos += 4;
            byte[] bytes = buffer.getBytes(pos, pos + len);
            val = new String(bytes, UTF8);
            pos += len;
            break;
          case TYPE_BUFFER:
            len = buffer.getInt(pos);
            pos += 4;
            bytes = buffer.getBytes(pos, pos + len);
            val = Buffer.buffer(bytes);
            pos += len;
            break;
          case TYPE_BYTES:
            len = buffer.getInt(pos);
            pos += 4;
            val = buffer.getBytes(pos, pos + len);
            pos += len;
            break;
          case TYPE_CLUSTER_SERIALIZABLE:
            int classNameLen = buffer.getInt(pos);
            pos += 4;
            byte[] classNameBytes = buffer.getBytes(pos, pos + classNameLen);
            pos += classNameLen;
            String className = new String(classNameBytes, UTF8);
            Class<?> clazz = Utils.getClassLoader().loadClass(className);
            if (!ClusterSerializable.class.isAssignableFrom(clazz)) {
              throw new ClassCastException(new String(classNameBytes) + " is not assignable from ClusterSerializable");
            }
            ClusterSerializable obj = (ClusterSerializable) clazz.getDeclaredConstructor().newInstance();
            pos = obj.readFromBuffer(pos, buffer);
            val = obj;
            break;
          default:
            throw new IllegalStateException("Invalid serialized type: " + type);
        }
        data.put(key, val);
      }
      setData(data);
    }
    return pos;
  } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
    throw new VertxException(e);
  }
}
 
Example #19
Source File: StaticHandlerImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
private void sendStatic(RoutingContext context, String path) {

    String file = null;

    if (!includeHidden) {
      file = getFile(path, context);
      int idx = file.lastIndexOf('/');
      String name = file.substring(idx + 1);
      if (name.length() > 0 && name.charAt(0) == '.') {
        // skip
        context.next();
        return;
      }
    }

    // Look in cache
    final CacheEntry entry = cache.get(path);

    if (entry != null) {
      if ((filesReadOnly || !entry.isOutOfDate())) {
        // a cache entry can mean 2 things:
        // 1. a miss
        // 2. a hit

        // a miss signals that we should continue the chain
        if (entry.isMissing()) {
          context.next();
          return;
        }

        // a hit needs to be verified for freshness
        final long lastModified = Utils.secondsFactor(entry.props.lastModifiedTime());

        if (Utils.fresh(context, lastModified)) {
          context.response()
            .setStatusCode(NOT_MODIFIED.code())
            .end();
          return;
        }
      }
    }

    final boolean dirty = cache.enabled() && entry != null;
    final String sfile = file == null ? getFile(path, context) : file;

    // verify if the file exists
    context.vertx()
      .fileSystem()
      .exists(sfile, exists -> {
        if (exists.failed()) {
          context.fail(exists.cause());
          return;
        }

        // file does not exist, continue...
        if (!exists.result()) {
          if (cache.enabled()) {
            cache.put(path, null);
          }
          context.next();
          return;
        }

        // Need to read the props from the filesystem
        getFileProps(context, sfile, res -> {
          if (res.succeeded()) {
            FileProps fprops = res.result();
            if (fprops == null) {
              // File does not exist
              if (dirty) {
                cache.remove(path);
              }
              context.next();
            } else if (fprops.isDirectory()) {
              if (dirty) {
                cache.remove(path);
              }
              sendDirectory(context, path, sfile);
            } else {
              if (cache.enabled()) {
                cache.put(path, fprops);

                if (Utils.fresh(context, Utils.secondsFactor(fprops.lastModifiedTime()))) {
                  context.response().setStatusCode(NOT_MODIFIED.code()).end();
                  return;
                }
              }
              sendFile(context, sfile, fprops);
            }
          } else {
            context.fail(res.cause());
          }
        });
      });
  }
 
Example #20
Source File: StaticHandlerTest.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Test
public void testCacheGetNew() throws Exception {
  testCacheReturnFromCache((lastModified, req) -> req.putHeader("if-modified-since", Utils.formatRFC1123DateTime(toDateTime(lastModified) - 1)), 200, "OK", "<html><body>Other page</body></html>");
}
 
Example #21
Source File: StaticHandlerImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
private String directoryTemplate(Vertx vertx) {
  if (directoryTemplate == null) {
    directoryTemplate = Utils.readFileToString(vertx, directoryTemplateResource);
  }
  return directoryTemplate;
}
 
Example #22
Source File: ErrorHandlerImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public ErrorHandlerImpl(String errorTemplateName, boolean displayExceptionDetails) {
  Objects.requireNonNull(errorTemplateName);
  this.displayExceptionDetails = displayExceptionDetails;
  this.errorTemplate = Utils.readResourceToBuffer(errorTemplateName).toString();
}
 
Example #23
Source File: JsonBodyProcessorGenerator.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public boolean canGenerate(String mediaTypeName, JsonObject mediaTypeObject) {
  return Utils.isJsonContentType(mediaTypeName);
}
 
Example #24
Source File: BaseValidationHandler.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
  try {
    RequestParametersImpl parsedParameters = new RequestParametersImpl();

    parsedParameters.setPathParameters(validatePathParams(routingContext));
    parsedParameters.setQueryParameters(validateQueryParams(routingContext));
    parsedParameters.setHeaderParameters(validateHeaderParams(routingContext));
    parsedParameters.setCookieParameters(validateCookieParams(routingContext));

    //Run custom validators
    for (CustomValidator customValidator : customValidators) {
      customValidator.validate(routingContext);
    }

    String contentType = routingContext.request().getHeader(HttpHeaders.CONTENT_TYPE);
    if (contentType != null && contentType.length() != 0) {
      boolean isMultipart = contentType.contains("multipart/form-data");

      if (multipartFileRules.size() != 0 && !isMultipart) {
        throw ValidationException.ValidationExceptionFactory.generateWrongContentTypeExpected(contentType,
          "multipart/form-data");
      }
      if (contentType.contains("application/x-www-form-urlencoded")) {
        parsedParameters.setFormParameters(validateFormParams(routingContext));
      } else if (isMultipart) {
        parsedParameters.setFormParameters(validateFormParams(routingContext));
        validateFileUpload(routingContext);
      } else if (Utils.isJsonContentType(contentType) || Utils.isXMLContentType(contentType)) {
        parsedParameters.setBody(validateEntireBody(routingContext));
      } else if (bodyRequired && !checkContentType(contentType)) {
        throw ValidationException.ValidationExceptionFactory.generateWrongContentTypeExpected(contentType, null);
      } // If content type is valid or body is not required, do nothing!
    } else if (bodyRequired) {
      throw ValidationException.ValidationExceptionFactory.generateWrongContentTypeExpected(contentType, null);
    }

    if (routingContext.data().containsKey("parsedParameters")) {
      ((RequestParametersImpl)routingContext.get("parsedParameters")).merge(parsedParameters);
    } else {
      routingContext.put("parsedParameters", parsedParameters);
    }
    routingContext.next();

  } catch (ValidationException e) {
    routingContext.fail(400, e);
  }
}
 
Example #25
Source File: JsonBodyProcessorImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public boolean canProcess(String contentType) {
  return Utils.isJsonContentType(contentType);
}