How to override ResourceHttpRequestHandler to implement a customized resource handler? - model-view-controller

When I use spring mvc, I use <mvc:resources /> to map the location of the static resources to handler, and now I want to add some new functions to handler resource, is there anyone who can tell me how to override the ResourceHttpRequestHandler?
(Based on the following doc, the <mvc:resources /> use ResourceHttpRequestHandler to handle resources.)
Thanks in advance!

I haven't tried this but you could try extending the ResourceHttpRequestHandler and use a BeanFactoryPostProcessor to replace ResourceHttpRequestHandler class with your custom class . A similar solution is given here
Sample...
public class ResourceHttpRequestHandlerReplacer implements BeanFactoryPostProcessor {
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory)
throws BeansException {
String[] names = factory.getBeanNamesForType(ResourceHttpRequestHandler.class);
for (String name: names) {
BeanDefinition bd = factory.getBeanDefinition(name);
bd.setBeanClassName("org.myProject.CustomResourceHttpRequestHandler");
}
}
}

Related

Camel - How to change destination(to) when processing a file(processor)

I have a spring boot application and with camel I read a file using FTP, I process the file and move that file to another location, my problem is that I need to change the destination depending of the file name. I read that I can use "toD" and use property placeholder to change the destination dynamically but I don't know how to set that value from the processor or is even possible to do that?,
Here is my main class:
#Component
public class Controlador extends RouteBuilder {
#Autowired
Procesador objProcesador;
#Override
public void configure() throws Exception {
from("ftp://user#ip:21?password=mypassword&passiveMode=true&delete=true").streamCaching().convertBodyTo(InputStream.class).process(objProcesador).to("file:C:\\Users\\juan.gaytan\\Desktop\\prueba2");
}
}
And here is my Processor class:
#Service
public class Procesador implements Processor {
#Override
public void process(Exchange exchange) throws Exception {
}
}
Thanks in advance.
You could use Simple as explained here.
An example would be to set the destination in exchange header as
exchange.getOut().setHeader("uri", destination);
and use in route as below
<toD uri="${header.uri}"/>

Spring 4 Annotation based equivalent of static resource mapping

I just converted an XML configured Spring MVC project to being annotation based but I cannot seem to figure out what annotation to use (and where to place it) for static resource mappings. The mappings in my project's older XML based configuration were:
<mvc:resources mapping = "/css/**" location = "/css/"/>
<mvc:resources mapping = "/images/**" location = "/images/"/>
<mvc:resources mapping = "/*.html" location = "/"/>
Any help appreciated.
#Configuration
#EnableWebMvc
public class WebAppConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
}
}

Spring security - Access to a controller method based on an attribute

I'm configuring Spring Security across all my controllers.
I want some method executions to start only when "my system is enabled". This information is accessible from all over the controllers via a specific static method (I can make it non-static).
My point is that I want to avoid making an explicit check in java code at the beginning of every method.
How can I get there via Spring Security?
One approach is to use a handler interceptor.
Here is general idea:
(1) Configure url patterns which you want to block:
<util:list id="sysEnableCheckUrlPatterns" value-type="java.lang.String">
<beans:value>/module1/**</beans:value>
<beans:value>/module2/**</beans:value>
</util:list>
(2) Write an interceptor:
public class SysEnableCheckInterceptor extends HandlerInterceptorAdapter {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
/*
If system enabled then return true. Otherwise return false (and optionally write something in response)
*/
}
}
(3) Configure that interceptor. In 3.1 you can do it as follows:
#Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
#Resource(name="sysEnableCheckUrlPatterns")
/* or use #Autowired or #Inject if you like */
private String[] sysEnableCheckUrlPatterns;
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SysEnableCheckInterceptor()).addPathPatterns(sysEnableCheckUrlPatterns);
}
}
You can use SPEL (Spring Expression Language) in a security annotation.
See http://static.springsource.org/spring-security/site/docs/3.0.x/reference/el-access.html

How do I dynamically create dependency implementations as they are referenced in Spring?

The situation here is that I have an interface that has dynamic implementations. These implementations need to be instantiated at runtime and used by injecting the interface:
public interface Configuration {
void doStuff();
}
public interface ExampleConfiguration extends Configuration {
void doStuff();
}
ExampleConfiguration has an implementation generated dynamically. I.e, there is no ExampleConfigurationImpl class. This is proving difficult to integrate into Spring because I want to have these generated implementations injected automatically:
#Autowired
private ExampleConfiguration config;
I went down the road of adding a BeanPostProcessor but it looks like unresolved dependencies don't go through there (as I would expect).
Essentially, is there a way to contribute a factory that will be called (with contextual information such as a DependencyDescriptor instance) in an attempt to resolve a missing dependency? There will be multiple interfaces extending the Configuration interface.
Spring version is 3.0.3.
Have you tried a FactoryBean?
public class ExampleConfigurationFactoryBean implements FactoryBean<ExampleConfiguration> {
#Override
public ExampleConfiguration getObject() throws Exception {
return //...magic here
}
#Override
public Class<?> getObjectType() {
return ExampleConfiguration.class;
}
#Override
public boolean isSingleton() {
return true;
}
}
I don't know how you actually create these dynamic beans (I suspect some dynamic proxy being involved), but insert your logic in magic here placeholder. Should work. You use the FactoryBean as if it had a target type in your XML:
<bean id="exampleConfigurationFactoryBean" class="ExampleConfigurationFactoryBean"/>
<bean id="someBean">
<!-- exampleConfiguration is of ExampleConfiguration type -->
<property name="exampleConfiguration" ref="exampleConfigurationFactoryBean"/>
</bean>
Spring will call getObject() when requested.
I assume you've got some way to actually manufacture the instances? Well, all you need to do is to make that factory into a bean itself and add the right annotations:
#org.springframework.context.annotation.Configuration
public class ConfigBean {
#org.springframework.context.annotation.Bean
public ExampleConfiguration getObject() throws Exception {
return //...magic here
}
}
You use the usual Spring techniques for hooking to any configuration you need. (I assume you're using <context:component-scan> and <context:annotation-config>…)

How to access Spring RequestContext from a Freemarker TemplateDirectiveModel

I'm using Spring MVC with Freemarker as view technologie. I have a TemplateDirectiveModel object which needs to access Spring's RequestContext within the execute method. Currently I do it like this:
public class MyDirective implements TemplateDirectiveModel
{
public void execute(Environment env, Map params, TemplateModel[] loopVars,
TemplateDirectiveBody body) throws TemplateException, IOException
{
StringModel model = (StringModel) env.getGlobalVariable("springMacroRequestContext");
RequestContext requestContext = (RequestContext) model.getWrappedObject();
}
}
But I can't believe that this is the right way to do it. I have the feeling I missed something important. Maybe there are special classes and annotations for handling Freemarker direcives in Spring? Maybe I can let Spring inject something into the directive class with which I can access Springs request scope?
You could subclass FreeMarkerConfigurer, overriding its postProcessConfiguration(Configuration config)method.
Your implementation would just put a request-aware dependency in the configuration, as a shared variable for example (as preconised by the FM documentation).
Should do the trick, Spring-style...
There is an easier way to do this. If you are already using spring's FreeMarkerConfigurer, you can hand it a map of variables:
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"
p:templateLoaderPath="/some_path_here">
<property name="freemarkerVariables">
<map>
<entry key='macroName' value-ref="templateModelRef" />
</map>
</property>
</bean>
<bean id="templateModelRef" class="...class..extends TemplateModel">
<property name="someResource" value-ref="resourceRef"/>
</bean>
Now at least in a class that extends TemplateDirectiveModel's execute method you have access to that injected property.
public class MyDirective extends TemplateDirectiveModel {
private MyResource someResource;
#Override
public void execute(Environment env, Map params, TemplateModel[] loopVars,TemplateDirectiveBody body) throws TemplateException, IOException {
StringModel sharedVariable = (StringModel)env.getConfiguration().getSharedVariable("beanName");
MyClass sweetness = (MyClass)sharedVariable.getWrappedObject();
}
}
Now in your .ftl you can use:
<#macroName />
and it will have spring dependencies auto injected.

Resources