001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *     http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.gbif.ws.server.interceptor;
015
016import org.gbif.api.annotation.Trim;
017import org.gbif.api.model.collections.Collection;
018import org.gbif.api.model.registry.Dataset;
019
020import java.io.IOException;
021import java.lang.reflect.Type;
022
023import org.apache.commons.beanutils.DynaClass;
024import org.apache.commons.beanutils.DynaProperty;
025import org.apache.commons.beanutils.WrapDynaBean;
026import org.apache.commons.lang3.ObjectUtils;
027import org.apache.commons.lang3.RegExUtils;
028import org.apache.commons.lang3.StringUtils;
029import org.slf4j.Logger;
030import org.slf4j.LoggerFactory;
031import org.springframework.core.MethodParameter;
032import org.springframework.http.HttpInputMessage;
033import org.springframework.http.converter.HttpMessageConverter;
034import org.springframework.web.bind.annotation.ControllerAdvice;
035import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
036
037/**
038 * An interceptor that will trim all possible strings of a bean.
039 * All top level string properties are handled, as are those of nested objects that are in the GBIF registry model
040 * package.
041 * This will recurse only 5 levels deep, to guard against potential circular looping.
042 */
043@SuppressWarnings("NullableProblems")
044@ControllerAdvice
045public class StringTrimInterceptor implements RequestBodyAdvice {
046
047  private static final Logger LOG = LoggerFactory.getLogger(StringTrimInterceptor.class);
048
049  // only goes 5 levels deep to stop potential circular loops
050  private static final int MAX_RECURSION = 5;
051  private static final String REGEX_INVISIBLE_CONTROL_CHARS = "\\p{C}";
052
053  @Override
054  public boolean supports(
055      MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
056    return methodParameter.getMethodAnnotation(Trim.class) != null
057        || methodParameter.getParameterAnnotation(Trim.class) != null;
058  }
059
060  @Override
061  public HttpInputMessage beforeBodyRead(
062      HttpInputMessage httpInputMessage,
063      MethodParameter methodParameter,
064      Type type,
065      Class<? extends HttpMessageConverter<?>> aClass)
066      throws IOException {
067    return httpInputMessage;
068  }
069
070  @Override
071  public Object afterBodyRead(
072      Object o,
073      HttpInputMessage httpInputMessage,
074      MethodParameter methodParameter,
075      Type type,
076      Class<? extends HttpMessageConverter<?>> aClass) {
077    trimStringsOf(o, removeControlChars(methodParameter));
078    return o;
079  }
080
081  @Override
082  public Object handleEmptyBody(
083      Object o,
084      HttpInputMessage httpInputMessage,
085      MethodParameter methodParameter,
086      Type type,
087      Class<? extends HttpMessageConverter<?>> aClass) {
088    return o;
089  }
090
091  void trimStringsOf(Object target, boolean removeControlChars) {
092    trimStringsOf(target, 0, removeControlChars);
093  }
094
095  private void trimStringsOf(Object target, int level, boolean removeControlChars) {
096    if (target != null && level <= MAX_RECURSION) {
097      LOG.debug("Trimming class: {}", target.getClass());
098
099      WrapDynaBean wrapped = new WrapDynaBean(target);
100      DynaClass dynaClass = wrapped.getDynaClass();
101      for (DynaProperty dynaProp : dynaClass.getDynaProperties()) {
102        if (String.class.isAssignableFrom(dynaProp.getType())) {
103          String prop = dynaProp.getName();
104          String orig = (String) wrapped.get(prop);
105          if (orig != null) {
106            String trimmed = StringUtils.trimToNull(orig);
107
108            if (removeControlChars) {
109              trimmed = RegExUtils.removeAll(trimmed, REGEX_INVISIBLE_CONTROL_CHARS);
110            }
111
112            if (ObjectUtils.notEqual(orig, trimmed)) {
113              LOG.debug("Overriding value of [{}] from [{}] to [{}]", prop, orig, trimmed);
114              wrapped.set(prop, trimmed);
115            }
116          }
117        } else {
118          try {
119            // trim everything in the registry model package (assume that Dataset resides in the
120            // correct package here)
121            Object property = wrapped.get(dynaProp.getName());
122            if (property != null
123                && (Dataset.class.getPackage() == property.getClass().getPackage()
124                    || Collection.class.getPackage() == property.getClass().getPackage())) {
125              trimStringsOf(property, level + 1, removeControlChars);
126            }
127
128          } catch (IllegalArgumentException e) {
129            // expected for non accessible properties
130          }
131        }
132      }
133    }
134  }
135
136  private boolean removeControlChars(MethodParameter methodParameter) {
137    if (methodParameter.getMethodAnnotation(Trim.class) != null) {
138      return methodParameter.getMethodAnnotation(Trim.class).removeControlChars();
139    }
140
141    if (methodParameter.getParameterAnnotation(Trim.class) != null) {
142      return methodParameter.getParameterAnnotation(Trim.class).removeControlChars();
143    }
144
145    return false;
146  }
147}