Restlet: can't locate static files through Directory - spring

Serving static files through Restlet is proving harder than it feels like it ought to be. I suspect some deep issue to do with context initialization, but I could be wrong. Basically, I have yet to be able to get any actual content served through a Directory although all the routing and all classic restlets are working just fine.
The core problem looks like it shows in log messages:
WARNING: No client dispatcher is available on the context. Can't get the target URI: war:///
I've tried a bunch of different base URLs, and none of them seem to make a difference. And when I debug, sure enough getClientDispatcher() is returning null.
When I modified the Spring initialization (wrongly) to use the original context rather than a child context, I didn't get this warning, and directory listings showed, but it also displayed about seven SEVERE messages about that being a security risk.
My Spring XML looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<bean id="trackerComponent" class="org.restlet.ext.spring.SpringComponent">
<property name="defaultTarget" ref="trackerApplication" />
</bean>
<bean id="trackerComponentChildContext" class="org.restlet.Context">
<lookup-method name="createChildContext" bean="trackerComponent.context" />
</bean>
<bean id="trackerApplication" class="ca.uhnresearch.pughlab.tracker.application.TrackerApplication">
<property name="root" ref="router" />
</bean>
<!-- Define the router -->
<bean name="router" class="org.restlet.ext.spring.SpringRouter">
<constructor-arg ref="trackerComponentChildContext" />
<property name="attachments">
<map>
<entry key="/" value-ref="staticsDirectory" />
</map>
</property>
</bean>
<bean id="staticsDirectory" class="ca.uhnresearch.pughlab.tracker.resource.SpringDirectory">
<constructor-arg ref="router" />
<constructor-arg value="war:///" />
<property name="listingAllowed" value="true" />
</bean>
...
My class SpringDirectory is just a wrapper to provide a Context from a parent Router, like the other Spring helpers, and it seems to work just fine: the same context is passed along -- and none of the child contexts have a getClientDispatcher() that works.
In case it's needed, here's some of the relevant sections of web.xml. I'm not entirely sure why I needed to add the FILE to allow client access (I want to serve through the web container after all) but I did try with a file: URL too, and that didn't make any difference that I could see, except that I had to add extra settings in unusual places.
<servlet>
<servlet-name>tracker</servlet-name>
<servlet-class>org.restlet.ext.spring.SpringServerServlet</servlet-class>
<init-param>
<param-name>org.restlet.clients</param-name>
<param-value>HTTP HTTPS FILE</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>tracker</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
I'd be really grateful for advice on this -- I've actually spent more time trying to get an index.html displayed than I have on all the Restlets combined, so any thoughts or pointers will be very welcome.
UPDATE
Thierry's response has been helpful, but I still have some issues and still can't serve static files. The only variation from this is that I don't have a test.CustomSpringServerServlet -- and it's not entirely clear I need one, as the additional init-param seems to be accepted by the default.
When running with a Jetty JAR file (mvn jetty:run-war) I now get a stack backtrace:
WARNING: Exception or error caught in status service
java.lang.NoSuchMethodError: org.restlet.Context.getClientDispatcher()Lorg/restlet/Restlet;
at ca.uhnresearch.pughlab.tracker.restlets.DirectoryFactoryBean$1.getContext(DirectoryFactoryBean.java:16)
at org.restlet.Restlet.handle(Restlet.java:220)
at org.restlet.resource.Finder.handle(Finder.java:449)
at org.restlet.resource.Directory.handle(Directory.java:245)
at org.restlet.routing.Filter.doHandle(Filter.java:156)
...
This stack backtrace could easily be a consequence of my updates -- I'm now using Restlets 2.3.1 and Spring 3.1.4, as it's very similar to the previous warning.
Strangely enough, I don't get this from mvn jetty:run, which paradoxically is now serving directory listings at the top level, but still refuses to serve any files. So that confirms the WAR protocol is able to access something. The war:// protocol isn't highly documented so I'm kind of guessing it's just going to serve from the war contents, and it certainly isn't yet able to do that.
I'd still like the file:// protocol to work -- to be honest, any serving of any static files would be fantastic, I am getting beyond caring. However, trying that still results in errors:
WARNING: The protocol used by this request is not declared in the list of client connectors. (FILE). In case you are using an instance of the Component class, check its "clients" property.
Which I don't really understand, as it is in the clients list in the web.xml and there's nowhere else that makes sense I can put it.
This is proving hard enough that I feel maybe I should throw together a Github repo for people to play with.

Edit: I completely updated my answer to describe how to fix your problem
I investigated more deeper you problem and I can reproduce it. In fact, it's a problem when configuring the directory itself in Spring. In fact, it's located at the context which is responsible to bring the client dispatcher.
Here are more details. In fact, the client protocol WAR is automatically registered when the Restlet component is created within the default or Spring servlet. See the method ServerServlet#init(Component). So the corresponding client dispatcher is set within the context of the component.
So you need to pass this context in the constructor of the Directory when instantiating it. I reworked the Spring configuration to show how to fix your problem:
public class DirectoryFactoryBean implements FactoryBean<Directory> {
private Component component;
#Override
public Directory getObject() throws Exception {
Directory directory = new Directory(component.getContext(), "war:///") {
#Override
public Context getContext() {
// Display if the client dispatcher is correctly set!
System.out.println(">> getContext().getClientDispatcher() = "+super.getContext().getClientDispatcher());
return super.getContext();
}
};
directory.setListingAllowed(true);
return directory;
}
#Override
public Class<?> getObjectType() {
return Directory.class;
}
#Override
public boolean isSingleton() {
return true;
}
public Component getComponent() {
return component;
}
public void setComponent(Component component) {
this.component = component;
}
}
Here is the content of the class ``:
public class CustomSpringServerServlet extends SpringServerServlet {
#Override
protected void init(Application application) {
super.init(application);
}
#Override
protected void init(Component component) {
super.init(component);
ClientList list = component.getClients();
for (Client client : list) {
System.out.println(">> client = "+client);
}
}
}
Here is the configuration in the web.xml file:
<web-app>
<context-param>
<param-name>org.restlet.application</param-name>
<param-value>org.restlet.tutorial.MyApplication</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>tracker</servlet-name>
<servlet-class>test.CustomSpringServerServlet</servlet-class>
<init-param>
<param-name>org.restlet.component</param-name>
<param-value>myComponent</param-value>
</init-param>
<init-param>
<param-name>org.restlet.clients</param-name>
<param-value>HTTP HTTPS FILE</param-value>
</init-param>
</servlet>
</web-app>
Here is the corresponding Spring configuration:
<bean id="myComponent" class="org.restlet.ext.spring.SpringComponent">
<property name="defaultTarget" ref="router" />
</bean>
<bean name="router" class="org.restlet.ext.spring.SpringRouter">
<property name="attachments">
<map>
<entry key="/dir" value-ref="staticsDirectory" />
</map>
</property>
</bean>
<bean id="staticsDirectory" class="test.DirectoryFactoryBean">
<property name="component" ref="myComponent" />
</bean>
Hope it helps,
Thierry

Related

How to change a requested url in spring mvc, before going to controller

I am developing a web app using Spring mvc. I have page which displays all projects in DB. If i click on any of the projects listed, it will display some other additional details of that particular project. This is done by using #PathVariable.
#RequestMapping(value={"/project/{name}"})
public String viewProject(HttpServletRequest request,#PathVariable("name")
String projectName, ModelMap model){
.......
.......
}
Above is my request mapping code. My url will be http://localhost:8083/releaseDashboard/project/CSOB.html (csob is my project name and releaseDashboard is my app name). Till this my app works fine. When i click on the home button from this page, my request is mapped to the above controller method and my url becomes localhost:8083/releaseDashboard/project/home.html. But the expected url is localhost:8083/releaseDashboard/home.html
Can anyone please help me? I read that we can use Interceptor or Filters to change the requested url. But i couldnt see any code snippet for that.
UPDATE
Web.xml
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
spring-servlet.xml
<context:component-scan base-package="com.suntec.reldashboard.controller" />
<context:component-scan base-package="com.suntec.reldashboard.service" />
<context:component-scan base-package="com.suntec.reldashboard.dao" />
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
Your config in web.xml in the context of Spring MVC is incorrect.
Edit it as <url-pattern>/</url-pattern>. By this, all the requests to your project will pass through the 'dispatcher servlet'.
(You can also use like this <url-pattern>something-here</url-pattern>. Then your base url should have an extra 'something-here').
Now you can access the resource,
#RequestMapping(value={"/project/{name}"})
public String viewProject(HttpServletRequest request,#PathVariable("name")
String projectName, ModelMap model){
.......
.......
return "hello";
}
by the URL http://localhost:8083/releaseDashboard/project/CSOB. Then projectName will be CSOB.
You must have a 'jsp' file under /WEB-INF/jsp/ having the name hello.jsp. In that jsp file, you can access model values.
You must not use .html/.jsp within the URL, when using Spring MVC. All the resource is bounded to a VIEW, using view resolver. That is how this must be implemented. That's for it is 'MVC' and 'view-resolving'.
NOTE:
As per your current configuration, "you have to change a requested URL". NO, you can't. Then your URL may be http://localhost:8083/releaseDashboard/project/CSOB.html; and projectName is "CSOB.html". Then you have to use java substring function to extract "CSOB" from "CSOB.html". And this is an ugly stuff!

Transactional annotation does not save on exit

I have configured spring jpa with annotation driven. I would expect the following code to persist the changes to the database upon method exist.
#Transactional
public Foo changeValue(int id){
final Foo foo = fooRepository.findOne(id);
if(foo != null){
foo.setValue("new value");
//fooRepository.save(foo);
}
}
FooRepository is a JPARepository and the foo object is getting fetched so it is managed. Based on what I read about #Transactional I would expect that even without the fooRepository.save(foo) call the changes in foo's value column in the database would be persisted upon method exist. However, this only happens if I uncomment the call to fooRepository.save(foo)
No exceptions are thrown and the configuration for the jpa datasource is as below.
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
...
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan
base-package="com.example.package.data" />
<jpa:repositories
base-package="com.example.package.data.repository"
entity-manager-factory-ref="entityManagerFactory"
transaction-manager-ref="transactionManager" />
Any ideas?
Update
I do have a ContextLoaderListener and a DispatcherServlet but I do not have component scan for both.
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
</servlet>
....
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Update
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
And there I do
<context:component-scan base-package="com.example.package">
<context:exclude-filter type="regex"
expression="com.example.package.data.*" />
<context:exclude-filter type="regex"
expression="com.example.package.web.controller.*" />
<context:exclude-filter type="regex"
expression="com.example.package.web.service.*" />
</context:component-scan>
And in servlet-context
<context:component-scan base-package="com.example.package.web" />
Your general approach is correct. The changes should get saved and committed on exit of the method. While this approach works great when it works it is a bitch to debug.
Your configuration looks ok to me, so I would double check, that you actually have Spring Beans at your disposal and not some instance that you created simply by calling the constructor.
To verify this, just put a breakpoint at the code point where the annotated method gets called. The bean with the annotated method should NOT by of the class you wrote, but some ProxySomething class.
This article also provides some pointers what might be wrong with your setup.
If you have both a ContextLoaderListener and DispatcherServlet they both load a configuration file.
Judging from your configuration the services are loaded by the DispatcherServlet and your <tx:annotation-driven /> is loaded by the ContextLoaderListener. They both create an ApplicationContext and as AOP is only applied to the beans in the same context your services will not be transactional (Transaction management is done by using AOP).
As a rule of thumb your ContextLoaderListener should contain all shared or global resources (like services, daos, datasources etc.) whereas your DispatcherServlet should only contain web related beans like controllers, view resolvers etc.

Transaction not working correctly - Spring/MyBatis

I have a Spring MVC Controller method which is tagged as "Transactional" which makes several service calls which are also tagged "Transactional" but they are treated as independent transactions and are committed separately instead of all under one transaction as I desire.
Based on the debug output, it appears Spring is only creating transactions when it reaches the service calls. I will see the output "Creating new transaction with name..." only for them but not one for the controller method who calls them.
Is there something obvious I am missing?
Sample code (abbreviated) below, controller:
#Controller
public class BlahBlah etc...
#Autowired
SomeService someService;
#Transactional
#RequestMapping(value="windows/submit", method=RequestMethod.POST)
#ResponseBody
public String submit (#RequestBody SomeObject blah) throws Exception {
someService.doInsert(blah);
if (true) throw Exception("blah");
... other stuff
}
service code:
public interface SomeService {
#Transactional
public void doInsert (SomeObject blah);
}
I tried removing the Transactional tag from the service call thinking maybe I messed it up and I am telling it to create one for each call but then in the debug output no transaction is created.
So the result is once I get my forced exception and check the table, the insert has committed instead of rolled back like I want.
So what did I do wrong?
Why is Spring ignoring the Transactional tag on the controller?
Posting relevant part of my context as per request from commenter:
Web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring.xml
classpath:spring-security.xml
classpath:spring-datasource.xml
</param-value>
</context-param>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
sping-mvc.xml:
<context:annotation-config/>
<context:component-scan base-package="com.blah"/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver" p:order="1" />
... non-relevent stuff
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="0"/>
<property name="useExpiresHeader" value="true"/>
<property name="useCacheControlHeader" value="true"/>
<property name="useCacheControlNoStore" value="true"/>
</bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean id="httpInterceptor" class="com.blah.BlahInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
<mvc:view-controller path="/" view-name="blah"/>
<context:component-scan base-package="com.blah"/>
Hmm, thats interested and unintended - I have component scan duplicated. Could that be causing problems with this?
I think Spring ignores the #Transactional annotation here because it creates a proxy for the transaction, but the dispatcher isn't calling the controller through the proxy.
There's an interesting note in the Spring MVC documentation, 17.3.2, about annotating controllers, it doesn't describe your exact problem but shows that there are problems with this approach:
A common pitfall when working with annotated controller classes
happens when applying functionality that requires creating a proxy for
the controller object (e.g. #Transactional methods). Usually you will
introduce an interface for the controller in order to use JDK dynamic
proxies. To make this work you must move the #RequestMapping
annotations, as well as any other type and method-level annotations
(e.g. #ModelAttribute, #InitBinder) to the interface as well as the
mapping mechanism can only "see" the interface exposed by the proxy.
Alternatively, you could activate proxy-target-class="true" in the
configuration for the functionality applied to the controller (in our
transaction scenario in ). Doing so indicates
that CGLIB-based subclass proxies should be used instead of
interface-based JDK proxies. For more information on various proxying
mechanisms see Section 9.6, “Proxying mechanisms”.
I think you'd be better off creating another service to wrap the existing ones and annotating that.

How to load Spring AOP into web app?

I was trying to implement Spring AOP in web app. Unfortunately all the sample code I found on the Web are console app. I was running out of clue how could I do it in web app?
In web.xml file, I load the applicationContext.xml like this:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
In applicationContext.xml file, I have ProxyFactoryBean defined like this:
<bean id="theBo" class="my.package.TheBo">
...
</bean>
<bean id="theProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<list>
<value>my.package.ITheBo</value>
</list>
</property>
<property name="target" ref="theBo"/>
<property name="interceptorNames">
<list>
<value>loggingBeforeAdvice</value>
</list>
</property>
</bean>
My situation now is I don't know where is the best place to put this code:
ApplicationContext context = new ClassPathXmlApplicationContext("WEB-INF/applicationContext.xml");
theBo = (ITheBo) context.getBean("theProxy");
If this was a console app, I would rather put it in the main(), but how could I do it in web app?
You do not need the following piece of code to load the context:
ApplicationContext context = new ClassPathXmlApplicationContext("WEBINF/applicationContext.xml");
theBo = (ITheBo) context.getBean("theProxy");
You have to add the ContextLoaderListener to your web.xml file:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Now when your web application starts the contexts declared in the <context-param> contextConfigLocation are loaded. In your case '/WEB-INF/applicationContext.xml'.
If you need your context in a specific class you can implement the ApplicationContextAware interface to retrieve it.
For the rest, your webapp is now a basic spring application where you can wire your classes as you would normally do.
Thanks to #Dave Newton giving me the clue. In order for me to inject theProxy from the web, for my case, it was JSF, I have to put following code in faces-config.xml.
<application>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
</application>
<managed-bean>
<managed-bean-name>theAction</managed-bean-name>
<managed-bean-class>org.huahsin68.theAction</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>theBo</property-name>
<value>#{theProxy}</value>
</managed-property>
</managed-bean>
And the put in the listener provided by #tom as well into web.xml.

Error while splitting application context file in spring

I am trying to split the ApplicationContext file in Spring.
For ex. the file is testproject-servlet.xml having all the entries. Now I want to split this single file into multiple files according to logical groups like :
group1-services.xml, group2-services.xml
I have created following entries in web.xml :
<servlet>
<servlet-name>testproject</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/group1-services.xml, /WEB-INF/group2-services.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
I am using SimpleUrlHandlerMapping as:
<bean id="simpleUrlMapping"class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="order" value="0"/>
<property name="mappings">
<props>
<prop key="/register.htm">RegisterController</prop> <prop key="/payroll_services.htm">PayrollServicesController</prop>
</props>
</property>
</bean>
I also have the controller defined as :
<bean id="PayrollServicesController" class="com.triforce.b2bseek.businessservices.controller.PayrollServicesController">
<property name="facadeLookup" ref="FacadeLookup"/>
..
..
</property>
</bean>
The problem is that I have splitted the ApplicationContext file "testproject-servlet.xml" into two different files and I have kept the above entries in "group1-services.xml". Is it fine? I want to group things logically based on their use in seperate .xml files.
But I am getting the following error when I try to access a page inside the application :
org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping for [/TestProject/payroll_services.htm] in DispatcherServlet with name 'testproject'
Please tell me how to resolve it.
Thanks in Advance !
Replace this
/WEB-INF/group1-services.xml, /WEB-INF/group2-services.xml
with
/WEB-INF/group1-services.xml
/WEB-INF/group2-services.xm
Hope this will work...:)
I don't think its a problem with your contextConfigLocation as such
I think its more that the dispatcher needs to know where to send payroll_servives.htm to, and can't find an appropriate handler knowing what to do with this pattern.
See reference documentation
Did you really want *.htm files to be matched to the dispatcher servlet?
If you are using annotation-based controllers (#Controller), then you need to have a line similar to:
<context:component-scan base-package="org.springframework.samples.petclinic.web"/>
This installs an appropriate annotation-based handler, that searchs for classes/methods annotated like:
#Controller
public class PayrollController {
#RequestMapping("payroll_services.htm")
public ModelAndView payrollServices() {
....
}
}
Otherwise, if you are using more traditional handlers/controllers, you need to define this using XML. The reference documentation link earlier in this posting mentions two such handlers: SimpleUrlHandlerMapping or BeanNameUrlHandlerMapping
Perhaps if you updated your question with snippets of handler/controller XML, this may help?
Did you add the ContextLoaderListener to your web.xml? I don't see it:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
You need to include something like this in each of your files:
<context:component-scan base-package="com.example.dao" />
If it is missing from a file, it seems the annotated classes are not known in the context of that file.
You may want to revisit the documentation for details.
Either the handler mapping of your DispatcherServlet is incorrect or you're using the wrong url. If you fix the layout around your SimpleUrlHandlerMapping configuration I can tell you what to change.

Resources