Combining Spring MVC 3.2 with Coda Hales metrics - java

i am trying to combine a Spring Web Application (completed Annotation Based configuration, no xml configuration) with metrics 3.0.
I am running the application inside a jetty.
This is my current configuration for the default DispatcherServlet:
public class WebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
return new Filter[] { characterEncodingFilter };
}
}
This is the WebConfig:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.rebuy.silo.amqpredelivery")
#EnableJpaRepositories(basePackages = "com.rebuy.silo.amqpredelivery.domain")
#EnableAspectJAutoProxy
#EnableTransactionManagement
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter();
jacksonConverter.setObjectMapper(objectMapper());
converters.add(jacksonConverter);
super.configureMessageConverters(converters);
}
#Bean
public ObjectMapper objectMapper() {
SimpleDateFormat format = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ssXXX");
format.setTimeZone(TimeZone.getTimeZone("GMT+1"));
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(format);
return mapper;
}
}
I want to add these two Servlets:
https://github.com/codahale/metrics/blob/master/metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java
https://github.com/codahale/metrics/blob/master/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java
What is the best way to do this? I think there should be some spring magic to make this extremly easy to do! But I was not able to find it :(
Thanks in advance
Björn

You can follow this codebase https://github.com/spiritedtechie/metrics-examples.
Or use this library called metrics-spring http://ryantenney.github.io/metrics-spring/

If you are using Spring and Metrics you should also be using #RyanTenney's Metrics-Spring module. It will simplify your Java config and make your Metrics usage much cleaner.
Take a look at the code behind the MetricsServlet and HealthCheckServlet. In my opinion its easier to just write your own Spring Controller to do the same thing than to figure out how to embed and wrap those old servlets.
Its easy!
Create a metrics specific config:
#Configuration
#EnableMetrics
public class MetricsConfig extends MetricsConfigurerAdapter {
#Override
public void configureReporters(MetricRegistry metricRegistry) {
registerReporter(ConsoleReporter
.forRegistry(metricRegistry)
.build()).start(5, TimeUnit.MINUTES);
}
}
And include it from your existing config by adding:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.rebuy.silo.amqpredelivery")
#EnableJpaRepositories(basePackages = "com.rebuy.silo.amqpredelivery.domain")
#EnableAspectJAutoProxy
#EnableTransactionManagement
#Import({MetricsConfig.class})
public class WebConfig extends WebMvcConfigurerAdapter {
...
The above config changes make it trivial to inject a MetricRegistry in any Spring component. All the MetricsServlet does is send the registry in response to the request. That is really easy to accomplish in a simple controller. For example:
#Controller
public class AdminMetricsController
{
#Autowired
MetricRegistry metricRegistry;
#RequestMapping(value = "/admin/metrics/", produces = {APPLICATION_JSON_VALUE})
public #ResponseBody MetricRegistry getMetrics(final HttpServletResponse response)
{
response.setHeader("Cache-Control", "must-revalidate,no-cache,no-store");
return metricRegistry;
}
}
A HealthCheckRegistry can be injected in a similar way and another method added which would respond to /admin/health/ or whatever url you wanted.

Take a look at the following answer. It explains how to register a Servlet via JavaConfig:
Spring JavaConfig: Add mapping for custom Servlet

Related

Spring 5 Java Config Set Default Profile

In my older Spring 4 web-app, I used an applicationContext.xml file, and my default spring profile was as follows;
<beans profile="default">
<context:property-placeholder location="file:/opt/myapp/myapp-ws.properties" />
</beans>
And now I am using Spring 5 Framework, but NOT Spring Boot 2.x, and I want to do this in my Java Config class.
My main configuration class looks like this;
#Configuration
#ComponentScan(basePackages = "com.tomholmes.myapp")
#EnableWebMvc
public class MyAppConfig
{
}
And I have the AppInitializer as follows;
public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
private static final Log logger = LogFactory.getLog(ApplicationInitializer.class);
#Override
protected Class<?>[] getRootConfigClasses()
{
return new Class[]
{ MyAppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses()
{
return new Class[]{};
}
#Override
protected String[] getServletMappings()
{
return new String[]
{ "/api/*" };
}
}
I've been doing some research on the Net since there is a lot of information on this, but a lot of it conflates Spring Boot,and I just want a Spring 5 without Spring Boot solution. I'll keep looking, I am sure this is a simple issue.
Thanks!
I believe something like this might do the trick:
#Configuration
public class PropertiesConfig {
#Bean
public PropertyPlaceholderConfigurer properties() {
final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
final List<Resource> resources = new ArrayList<>();
resources.add(new FileSystemResource("/etc/app/application-{profile_1}.properties"));
resources.add(new FileSystemResource("/etc/app/application-{profile_2}.properties"));
ppc.setLocations(resourceLst.toArray(new Resource[]{}));
return ppc;
}
Please note, that this is just the suggestion, this code is not tested.
Profile specific application properties should be resolved automatically by current active profile.
I haven't tested this, but a #Configuration class with both #Profile and #PropertySource should work:
#Configuration
#Profile("default")
#PropertySource("file:/opt/myapp/myapp-ws.properties")
public class MyappWebservicePropertyConfig {
}

JavaConfig Spring Web Flow returns 404 not found (JSP)

I have been trying out the Java Configuration feature of Spring Web Flow 2.4 by modifying an existing project from xml configuration to JavaConfig. The XML version works, but JavaConfig doesn't. Every time I try to start the flow with URL http://localhost:8080/sia_p219_ch08_spring_web_flow_order_pizza_customer_flow_complete/pizza , it returns 404. There are no exceptions. The console show no "no request mapping found for..." message. The webpage shows The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
The project is hosted on github, the working XML version is here.
I think the problem is the request URL doesn't call the pizza flow (/WEB-INF/flows/pizza/pizza-flow.xml).
Here are some code snippets:
WebAppInitializer:
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
#Override
// map DispatcherServlet to /
protected String[] getServletMappings() {
return new String[] { "/" };
}
RootConfig:
#Configuration
#Import({WebFlowConfig.class})
public class RootConfig {}
WebFlowConfig:
#Configuration
#ComponentScan({"pizza"})
public class WebFlowConfig extends AbstractFlowConfiguration {
static{
System.out.println("WebFlowConfig loaded");
}
#Autowired
private WebConfig webMvcConfig;
#Bean
public FlowDefinitionRegistry flowRegistry() {
return
getFlowDefinitionRegistryBuilder(flowBuilderServices())
.setBasePath("/WEB-INF/flows")
.addFlowLocationPattern("/**/*-flow.xml")
.build();
}
#Bean
public FlowExecutor flowExecutor(){
return getFlowExecutorBuilder(flowRegistry()).build();
}
#Bean
public FlowBuilderServices flowBuilderServices() {
return getFlowBuilderServicesBuilder()
.setViewFactoryCreator(mvcViewFactoryCreator())
.setDevelopmentMode(true)
.build();
}
#Bean
public MvcViewFactoryCreator mvcViewFactoryCreator() {
MvcViewFactoryCreator factoryCreator = new MvcViewFactoryCreator();
factoryCreator.setViewResolvers(Collections.singletonList(this.webMvcConfig.viewResolver()));
factoryCreator.setUseSpringBeanBinding(true);
return factoryCreator;
}
}
WebConfig
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
static{
System.out.println("WebConfig loaded");
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/flows/");
resolver.setSuffix(".jsp");
return resolver;
}
// configure static content handling
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
The flow definition files and JSPs are fine and you can see them on github if you want.
Thanks a lot, any help is greatly appreciated.
What I've found so far that the configuration definitely lacks this part of configuration in WebFlowConfig (take a look at the documentation page for integration with Spring MVC for details):
#Bean
#Autowired
public FlowHandlerAdapter flowHandlerAdapter(FlowExecutor flowExecutor) {
FlowHandlerAdapter flowHandlerAdapter = new FlowHandlerAdapter();
flowHandlerAdapter.setFlowExecutor(flowExecutor);
return flowHandlerAdapter;
}
#Bean
#Autowired
public FlowHandlerMapping flowHandlerMapping(FlowDefinitionRegistry flowDefinitionRegistry) {
FlowHandlerMapping flowHandlerMapping = new FlowHandlerMapping();
flowHandlerMapping.setFlowRegistry(flowDefinitionRegistry);
flowHandlerMapping.setOrder(0);
return flowHandlerMapping;
}
Also remove mvcViewFactoryCreator definition and setViewFactoryCreator call from the flowBuilderServices bean definition as well. It works for me.

Spring Boot, CXF Spring MVC. Not exposing web service on JBoss

I've been googling for the last 2 days and still can't figure out why it wont expose the SOAP web service. It works when I run it locally using Tomcat and Spring Boot. In the jboss-deployment-structure, jpa, javaee-api and webservices has been excluded. Also, there are no exceptions in sysout or logs. Only the message specified further down (HTTP 405). Even checked through TRACE logs.
JBoss Version: 6.4.4 (or 6.4.0)
Spring Boot: 1.3.0
CXF: 3.0.4
Spring MVC: From Spring Boot parent
I get this message:
HTTP Status 405 - Request method 'POST' not supported.
When debugging, I placed a breakpoint in class: DispatcherServlet, which then in getHandlerAdapter returned HttpRequestHandlerAdapter. Further along, it calls the HttpRequestHandlerAdapter.handle which again calls handleRequest on a WebContentGenerator. This only supports GET or HEAD requests.
Any ideas?
Code:
#Configuration
public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {
ApplicationConfig.class
};
}
#Override
protected String[] getServletMappings() {
return new String[] {
"/*"
};
}
}
#Configuration
public class ApplicationServletInitializer extends SpringBootServletInitializer {
}
#Configuration
#EnableAutoConfiguration
#Import({
RepositoryConfig.class,
WebConfig.class,
WsProviderConfig.class
})
public class ApplicationConfig {
}
#Configuration
#EnableConfigurationProperties
public class WebConfig {
#Bean
public SelftestController selftestController() {
return new SelftestController();
}
}
#Configuration
public class WsProviderConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(WsProviderConfig.class);
#Autowired
private ApplicationContext context;
#Bean
ServletRegistrationBean messageDispatcherServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean(new CXFServlet(), "/soap/*");
bean.setLoadOnStartup(1);
return bean;
}
#Bean(name = Bus.DEFAULT_BUS_ID)
Bus bus() {
SpringBus bus = new SpringBus();
bus.getFeatures().addAll(Arrays.asList(new WSAddressingFeature(), new LoggingFeature()));
return bus;
}
#Bean
PlayerServiceV1 defaultPlayerService() {
return new DefaultPlayerService();
}
#PostConstruct
void publishWebServices() {
LOGGER.info("Publishing WebServices");
DefaultPlayerService defaultPlayerService = context.getBean(DefaultPlayerService.class);
Bus bus = context.getBean(Bus.DEFAULT_BUS_ID, Bus.class);
EndpointImpl endpoint = new EndpointImpl(bus, defaultPlayerService);
endpoint.publish("/test/players");
}
}

Spring boot MVC does not use the specified custom StringHttpMessageConverter

In the class responsible for app config is this code:
#Bean
public HttpMessageConverter<String> createStringHttpMessageConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter
(Charset.forName("UTF-8"));
return converter;
}
I checked in debugger that it is actually executed and also tried alternative with StringHttpMessageConverter as the return type.
However when I debug WebMvcConfig.extendMessageConverters() I see that the StringHttpMessageConverter with the default charset is used instead of my converter with UTF-8 charset.
Why does not Spring Boot use the specified StringHttpMessageConverter ?
I know the workaround might be to change the converters list according to my needs in WebMvcConfig.extendMessageConverters() but I would like to do it the right way
With Spring Boot try to register array of HttpMessageConverters:
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.*;
#Configuration
public class MyConfiguration {
#Bean
public HttpMessageConverters customConverters() {
HttpMessageConverter<?> additional = ...
HttpMessageConverter<?> another = ...
return new HttpMessageConverters(additional, another);
}
}
Or if you are not using Spring Boot's auto-configuration, you can use standard Spring WebMvcConfigurer for registering converters:
#Configuration
#EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
.indentOutput(true)
.dateFormat(new SimpleDateFormat("yyyy-MM-dd"))
.modulesToInstall(new ParameterNamesModule());
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
converters.add(new MappingJackson2XmlHttpMessageConverter(builder.xml().build()));
}
}
You need 2 steps to support utf-8 StringHttpMessageConverter;
First add StringHttpMessageConverter;Second specify charset in produces,code is below;
#RestController
#RequestMapping(value = "/plain")
public class PlainController {
#RequestMapping(value = "/test", method = RequestMethod.GET,
produces = {"text/plain;charset=UTF-8"})
public Response<String> test() {
return new Response<String>("success");
}
}
#Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastConverter;
StringHttpMessageConverter stringHttpMessageConverter =
new StringHttpMessageConverter(Charset.forName("UTF-8"));
return new HttpMessageConverters(converter, stringHttpMessageConverter);
}

How to get DispatcherServeletInitializer functionality in Spring Boot

We are looking to migrate our project to Spring Boot. However it is unclear how to replicate the functionality of AbstractAnnotationConfigDispatcherServletInitializer in Spring Boot?
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
#Override
protected Class<?>[] getRootConfigClasses()
{
return new Class<?>[]{AppConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses()
{
return new Class<?>[]{WebappConfig.class};
}
#Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setAsyncSupported(true);
}
#Override
protected String[] getServletMappings()
{
return new String[]{"/"};
}
#Override
protected Filter[] getServletFilters()
{
DelegatingFilterProxy shiroFilter = new DelegatingFilterProxy("shiroFilter");
shiroFilter.setTargetFilterLifecycle(true);
CompositeFilter compositeFilter = new CompositeFilter();
compositeFilter.setFilters(ImmutableList.of(new CorsFilter(),shiroFilter));
return new Filter[]{compositeFilter};
}
}
The AppConfig and WebappConfig parent/child relationship can be handled by SpringApplicationBuilder, although you might also consider a flat hierarchy.
Assuming that you are going the whole hog, and running an embedded servlet container you can register Filters and Servlets directly as beans.
You can also use ServletRegistrationBean and FilterRegistrationBean if you need to set things such as setAsyncSupported. The final option is to add a bean that implements org.springframework.boot.context.embedded.ServletContextInitializer then do the registration yourself.
Something like this might get you a bit further:
#Bean
public ServletRegistrationBean dispatcherServlet() {
ServletRegistrationBean registration = new ServletRegistrationBean(
new DispatcherServlet(), "/");
registration.setAsyncSupported(true);
return registration;
}
#Bean
public Filter compositeFilter() {
CompositeFilter compositeFilter = new CompositeFilter();
compositeFilter.setFilters(ImmutableList.of(new CorsFilter(), shiroFilter));
return compositeFilter
}
Also, take a look at this section in the reference manual http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-embedded-container
Well there is nothing special like just mark your AppInitializer with Boot annotations:
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
...
}
I haven't tried it, but just combined the documentation:
Normally all the code from an existing WebApplicationInitializer can be moved into a SpringBootServletInitializer. If your existing application has more than one ApplicationContext (e.g. if it uses AbstractDispatcherServletInitializer) then you might be able to squash all your context sources into a single SpringApplication.
And SpringBootServletInitializer JavaDocs:
If your application is more complicated consider using one of the
other WebApplicationInitializers.

Categories

Resources