<commit_before>/*
 * Copyright (c) 2016 Open Baton (http://openbaton.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.openbaton.nfvo.api.interceptors;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.kjetland.jackson.jsonSchema.JsonSchemaGenerator;
import com.networknt.schema.ValidationMessage;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openbaton.catalogue.mano.descriptor.NetworkServiceDescriptor;
import org.openbaton.catalogue.mano.descriptor.VNFDependency;
import org.openbaton.catalogue.mano.descriptor.VirtualLinkDescriptor;
import org.openbaton.exceptions.BadRequestException;
import org.openbaton.nfvo.api.configuration.CustomHttpServletRequestWrapper;
import org.openbaton.nfvo.common.utils.schema.SchemaValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Service
public class SchemaValidatorInterceptor extends HandlerInterceptorAdapter {

  private Logger log = LoggerFactory.getLogger(this.getClass());
  @Autowired private Gson gson;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {

    String requestURL = request.getRequestURL().toString();
    if (request.getRequestURI().equalsIgnoreCase("/error")) {
      return true;
    }
    CustomHttpServletRequestWrapper wrapper = new CustomHttpServletRequestWrapper(request);
    String requestBody = wrapper.getBody();
    String classSchema = null;
    Class<?> parameterClass = null;
    if (handler instanceof org.springframework.web.method.HandlerMethod) {
      org.springframework.web.method.HandlerMethod handlerMethod =
          (org.springframework.web.method.HandlerMethod) handler;

      Annotation[][] annotations = handlerMethod.getMethod().getParameterAnnotations();
      for (int i = 0; i < annotations.length; i++) {
        Annotation[] methodParameters = annotations[i];
        for (Annotation a : methodParameters) {
          if (a instanceof RequestBody) {
            parameterClass = handlerMethod.getMethod().getParameterTypes()[i];
            if (!parameterClass.getName().equals("com.google.gson.JsonObject")) {
              classSchema = getJsonSchemaFromClass(parameterClass);
            }
          }
        }
      }
    }

    if (classSchema != null) {
      log.trace("Request Body is : " + requestBody);
      log.trace("Request url is : " + requestURL);
      Set<ValidationMessage> validationMessages;
      try {
        if (parameterClass
            .getCanonicalName()
            .equals(NetworkServiceDescriptor.class.getCanonicalName())) {
          NetworkServiceDescriptor networkServiceDescriptor =
              gson.fromJson(requestBody, NetworkServiceDescriptor.class);
          if (networkServiceDescriptor
                  .getVnfd()<commit_msg>fix schema validation for primitive<commit_after>/*
 * Copyright (c) 2016 Open Baton (http://openbaton.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.openbaton.nfvo.api.interceptors;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.kjetland.jackson.jsonSchema.JsonSchemaGenerator;
import com.networknt.schema.ValidationMessage;

import org.openbaton.catalogue.mano.descriptor.NetworkServiceDescriptor;
import org.openbaton.catalogue.mano.descriptor.VNFDependency;
import org.openbaton.catalogue.mano.descriptor.VirtualLinkDescriptor;
import org.openbaton.exceptions.BadRequestException;
import org.openbaton.nfvo.api.configuration.CustomHttpServletRequestWrapper;
import org.openbaton.nfvo.common.utils.schema.SchemaValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class SchemaValidatorInterceptor extends HandlerInterceptorAdapter {

  private Logger log = LoggerFactory.getLogger(this.getClass());
  @Autowired private Gson gson;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {

    String requestURL = request.getRequestURL().toString();
    if (request.getRequestURI().equalsIgnoreCase("/error")) {
      return true;
    }
    CustomHttpServletRequestWrapper wrapper = new CustomHttpServletRequestWrapper(request);
    String requestBody = wrapper.getBody();
    String classSchema = null;
    Class<?> parameterClass = null;
    if (handler instanceof org.springframework.web.method.HandlerMethod) {
      org.springframework.web.method.HandlerMethod handlerMethod =
          (org.springframework.web.method.HandlerMethod) handler;

      Annotation[][] annotations = handlerMethod.getMethod().getParameterAnnotations();
      for (int i = 0; i < annotations.length; i++) {
        Annotation[] methodParameters = annotations[i];
        for (Annotation a : methodParameters) {
          if (a instanceof RequestBody) {
            parameterClass = handlerMethod.getMethod().getParameterTypes()[i];
            if (!parameterClass.getCanonicalName().equals(JsonObject.class.getCanonicalName())
                && !parameterClass.isPrimitive()) {
              classSchema = getJsonSchemaFromClass(parameterClass);
            }
          }
        }
      }
    }

    if (classSchema != null) {
      log.trace("Request Body is : " + requestBody);
      log.trace("Request url is : " + requestURL);
      Set<ValidationMessage> validationMessages;
      try {
        if (parameterClass
            .getCanonicalName()
            .equals(NetworkServiceDescriptor.class.getCanonicalName())) {
          NetworkServiceDescriptor networkServiceDescriptor =
              gson.fromJson(requestBody, NetworkServiceDescriptor.class);
          if (networkServiceDescriptor
                  .getVnfd()
{'fraction_non_alphanumeric': 0.09308544505284605, 'fraction_numerical': 0.0028014771424933146, 'mean_word_length': 4.057308435286542, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '21301', 'n_tokens_mistral': 2044, 'n_tokens_neox': 2007, 'n_words': 486}