Skip to content
This repository has been archived by the owner on May 11, 2021. It is now read-only.

Commit

Permalink
Request filters, view configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
marcingrzejszczak committed May 15, 2015
1 parent 0ec2c3f commit e26967a
Show file tree
Hide file tree
Showing 9 changed files with 195 additions and 181 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
@Aspect
public class CorrelationIdAspect {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

private static final int HTTP_ENTITY_PARAM_INDEX = 2;

@Pointcut("@target(org.springframework.web.bind.annotation.RestController)")
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package com.ofg.infrastructure.web.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;

/**
* Advice on {@link BadParametersException} and {@link Exception} that
* catches uncaught exceptions, logs and present them
*
* @see ControllerAdvice
* @see ExceptionHandler
* @see BadParametersException
* @see BadParameterError
*/
@ControllerAdvice
@Order(Ordered.LOWEST_PRECEDENCE)
public class ControllerExceptionHandler {

private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static final String INTERNAL_ERROR = "internal error";

@ExceptionHandler(BadParametersException.class)
@ResponseBody
public List<BadParameterError> handleBadParametersExceptions(BadParametersException exception, HttpServletResponse response) throws Exception {
response.setStatus(SC_BAD_REQUEST);
return getListOfBindErrors(exception);
}

@ExceptionHandler(Exception.class)
@ResponseBody
public Map<String, String> handleAnyOtherExceptions(Exception exception, HttpServletResponse response) {
response.setStatus(SC_BAD_REQUEST);
log.error("Unexpected exception: ", exception);
Map<String, String> map = new HashMap<>();
map.put("error", INTERNAL_ERROR);
map.put("message", exception.getMessage());
return map;
}

private List<BadParameterError> getListOfBindErrors(BadParametersException exception) throws Exception {
List<BadParameterError> bindErrorList = new ArrayList<>();
for (ObjectError error : exception.getErrors()) {
bindErrorList.add(getBindError(error));
}
return bindErrorList;
}

private BadParameterError getBindError(ObjectError error) throws Exception {
if (error instanceof FieldError) {
return new BadParameterError(((FieldError) error).getField(), error.getDefaultMessage());
}
return new BadParameterError("Unknown field" ,error.getDefaultMessage());
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.ofg.infrastructure.web.logging;

import org.springframework.web.filter.Log4jNestedDiagnosticContextFilter;

/**
* Filter that logs request body. To enable it apart from registering it as a filter
* you have to set DEBUG level of logging. You can also provide the maximum length
* of the printed payload
*
* @see Log4jNestedDiagnosticContextFilter
*/
public class RequestBodyLoggingContextFilter extends Log4jNestedDiagnosticContextFilter {
public RequestBodyLoggingContextFilter(int maxPayloadLength) {
this.setIncludePayload(true);
this.setMaxPayloadLength(maxPayloadLength);
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.ofg.infrastructure.web.logging;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;

/**
* Configuration that registers a bean that will automatically if DEBUG level of logging is set on
* {@link RequestBodyLoggingContextFilter}
* print request body in logs - you can limit its length by setting a property
*
* @see RequestBodyLoggingContextFilter
*/
@Configuration
public class RequestLoggingConfiguration {
@Bean
public Filter requestBodyLoggingContextFilter(@Value("${request.payload.logging.maxlength:2000}") int maxPayloadLength) {
return new RequestBodyLoggingContextFilter(maxPayloadLength);
}

}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package com.ofg.infrastructure.web.view;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import groovy.transform.CompileStatic;
import org.apache.commons.lang.StringUtils;
import org.codehaus.groovy.runtime.StringGroovyMethods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

import static com.ofg.config.BasicProfiles.DEVELOPMENT;
import static com.ofg.config.BasicProfiles.TEST;

/**
* Configures JSON serialization for objects returned by controllers' methods.
* Pretty printing setting is based on active profile:
* - in production environment pretty printing is set to false,
* - in test or development environment pretty printing is set to true.
*/
@CompileStatic
@Configuration
public class ViewConfiguration extends WebMvcConfigurationSupport {
private static final boolean ON = true;
private static final boolean OFF = false;

@Autowired private Environment environment;

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(mappingJackson2HttpMessageConverter());
super.addDefaultHttpMessageConverters(converters);
}

private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setPrettyPrint(prettyPrintingBasedOnProfile());
converter.getObjectMapper().setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
configureJsonJacksonFeatures(converter);
return converter;
}

private boolean prettyPrintingBasedOnProfile() {
return environment.acceptsProfiles(DEVELOPMENT, TEST);
}

private void configureJsonJacksonFeatures(MappingJackson2HttpMessageConverter converter) {
configureParserFeatures("json.jackson.parser.on", converter, ON);
configureParserFeatures("json.jackson.parser.off", converter, OFF);
configureGeneratorFeatures("json.jackson.generator.on", converter, ON);
configureGeneratorFeatures("json.jackson.generator.off", converter, OFF);
}

private void configureParserFeatures(String jsonFeaturesConfigProperty, MappingJackson2HttpMessageConverter converter, boolean featuresState) {
String jsonJacksonFeatures = environment.getProperty(jsonFeaturesConfigProperty, String.class, "").trim();
if (StringUtils.isNotBlank(jsonJacksonFeatures)) {
for (String it : jsonJacksonFeatures.split(",")) {
String featureName = it.trim();
converter.getObjectMapper().configure(JsonParser.Feature.valueOf(featureName), featuresState);
}

}

}

private void configureGeneratorFeatures(String jsonFeaturesConfigProperty, MappingJackson2HttpMessageConverter converter, boolean featuresState) {
String jsonJacksonFeatures = environment.getProperty(jsonFeaturesConfigProperty, String.class, "").trim();
if (StringGroovyMethods.asBoolean(jsonJacksonFeatures)) {
for (String it : jsonJacksonFeatures.split(",")) {
String featureName = it.trim();
converter.getObjectMapper().configure(JsonGenerator.Feature.valueOf(featureName), featuresState);
}

}

}
}

0 comments on commit e26967a

Please sign in to comment.