Proper way to initialize settings for a Jersey restlet - java

I am trying to find out what is the proper way to initialize a static settings object, which should be loaded once and re-used by the restlets? Should I create a servlet which auto-loads, or is there (I am almost sure) a better way to do this?
Let's say I have a configuration.xml and would like to have it loaded so my restlets could start using it's settings. What would be the proper and most efficient way to do this?
Many thanks in advance!

You can create a ServletFilter that you map to your REST URLs in web.xml:
<filter-mapping>
<filter-name>MyServletFilter</filter-name>
<url-pattern>/rest/*</url-pattern>
</filter-mapping>
Then you override the init method to do your init business:
public class MyServletFilter implements javax.servlet.Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
loadConguration();
}

Related

tomcat jersey retrieve full context path

I'm implementing ApplicationEventListener, I need to retrieve the context path, the one declared in my web.xml:
<servlet-mapping>
<servlet-name>MyApplication</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
I'm implementing onEvent method
#Override
public void onEvent(ApplicationEvent event) {
if (event.getType() == ApplicationEvent.Type.INITIALIZATION_FINISHED) {
final ResourceModel resourceModel = event.getResourceModel();
}
}
I can also use #Context ServletContext servletContext in ResourceConfig to pass the info if necessary but I don't know how to reach this.
From a servlet using HttpServletRequest, it's possible to call request.getContextPath(), but obviously I can't use HttpServletRequest.
Generally speaking, in my application I need a way to retrieve servlet-mapping
Thanks
Edit:
listener class: org.glassfish.jersey.server.monitoring.ApplicationEventListe‌​ner

Spring and returning protected resources

I have a pretty standard Spring 3.0.7 web app
The structure is like this
WebContent/
resources/
myStaticConent/
WEB-INF/
views/
myProtectedContent/
I am using the <mvc:resources> configuration for the static content and my controllers get views using the InternalViewResolver from WEB-INF/views
Now I have a requirement to return non-JSP content ( JPGs,PNGs,HTML,etc ) from a protected directory in WEB-INF
So a user might enter a URL like http:myWebApp/myProtectedContent and hit my protected content controller.
#Controller
public class HelloWorldController {
#RequestMapping(value="/myProtectedContent")
public String index() {
return "myjpg.jpg";
}
}
Essentially I want to conditionally serve a file just like I would a view. Anyone know how this can be done ?
I looked at some of the other methods here, Streaming using Inputstream seems overkill for files that are essentially static. Can I register another "view" type ? I need this to appear l( from the web browser side ) like a standard http request response ( like the current view implementation).
I would really like to avoid inventing my own file handling methods unless there is some reason why using the file access methods are better then Springs "other" view resolvers like ResourceBundleResolver
So the requirement is
Conditionally respond to a http request with variable file type (jpg,png,html) from inside WEB-INF without wrapping in a jsp or having the file interpreted by the JSTL view. The names of the files are known and static. The controller will determine the file name based on its own business logic.
You can reproduce the behavior of the underlying implementation of <mvc:resources/> which is org.springframework.web.servlet.resource.ResourceHttpRequestHandler, which essentially streams out the content of the static files - You can like ResourceHttpRequestHandler, extend from org.springframework.web.servlet.support.WebContentGenerator which has extensive support for sending last-modified and caching related headers, and finally to stream the content also there is a utility that Spring provides:
org.springframework.util.FileCopyUtils.copy(resource.getInputStream(), response.getOutputStream());
Updated:
#Controller
public class HelloWorldController implements ApplicationContextAware {
ApplicatonContext ctx = ...;
#RequestMapping(value="/myProtectedContent")
public void index(HttpServletRequest req, HttpServletResponse res) {
Resource resource = ctx.getResource("classpath:staticpath/myjpg.jpg");
FileCopyUtils.copy(resource.getInputStream(), response.getOutputStream());
}
}
Something you can do is to map a new servlet to the path you want to be protected and handle the request the way you want.
For example, in web.xml:
<servlet>
<servlet-name>protServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/protServlet-context.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>protServlet</servlet-name>
<url-pattern>/myProtectedContent</url-pattern>
</servlet-mapping>
This way, you map a new servlet (DispatcherServlet) for URLs that are protected content.
The load-on-startup value equals 2 is due if you already have a DispatcherServlet with this field value equals 1.

What's the best way to capture information on every action in java?

Suppose you want to capture the page source of a web application on every action, e.g.
public void click() {
getPageSource();
}
public void type() {
getPageSource();
}
public void select() {
getPageSource();
}
I have to call getPageSource() in every function, but is there a neater way to achieve this?
If you're working in a Java Web Application, you should create a Filter to intercept every request made in the application. Here is a sample:
Java Class
package edu.home;
import javax.servlet.*;
public class MyFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
System.out.println("New request in the application!");
//here you can add getPageSource() and send request/response
}
}
Configure the Filter in web.xml
<!--declare the filter -->
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>edu.home.FISesionExpirada</filter-class>
</filter>
<!-- declare where the filter should be used -->
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
Things like these are typically called cross-cutting concerns and they don't fit well into the object oriented framework. The simple answer is that, in plain old Java, there really isn't a better way to do this.
There are solutions, but they aren't widely used in my experience, see e.g.,
http://www.eclipse.org/aspectj/
See if your web application framework supports filters, or listeners, or observers, or interceptors, or some kind of aspect-oriented programming. The kind of problem you describe has been solved many times, surely in your particular development environment you'll find a solution.

config.getInitParameter always return null

Why does config.getInitParameter(String) always return null in the following code example?
public void init(ServletConfig config) throws ServletException
{
super.init(config);
filename = config.getInitParameter("addressfile");
This is web.xml file
<servlet>
<servlet-name>ListManagerServlet</servlet-name>
<servlet-class>savva.listmanagerservlet.ListManagerServlet</servlet-class>
<init-param>
<param-name>addressfile</param-name>
<param-value>d:\temp\demo.txt</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ListManagerServlet</servlet-name>
<url-pattern>/ListManagerServlet</url-pattern>
</servlet-mapping>
UPD: Eclipse EE Indigo, Java 1.6, Tomcat 7.0
The canonical way is to just use the inherited GenericServlet#getInitParameter() in the argumentless init() method (and remove any init(config) method).
#Override
public void init() throws ServletException {
filename = getInitParameter("addressfile");
}
If that still doesn't work, then your web.xml is not properly been deployed, or you have a typo in the parameter name, or you actually accessed a different instance variable than filename to use/test it.
Ensure your servlet is calling super.init(config) on its init method, else it won't work.
Make sure you have really deployed the proper web.xml. Also check with config.getInitParameterNames() what parameters have been found.
It's never a good idea to override the init(config) method. Instead use the provided init() convenience method and do a getServletConfig() to get the configuration parameters:
http://docs.oracle.com/javaee/1.2.1/api/javax/servlet/GenericServlet.html#init()
http://docs.oracle.com/javaee/1.2.1/api/javax/servlet/GenericServlet.html#getServletConfig()
If use the IDE STS4, checkout if annotation on the class name exists, use BOTH "annotation" and "web.xml" may cause the value null.

Eclipse can't get init params from web.xml [duplicate]

Why does config.getInitParameter(String) always return null in the following code example?
public void init(ServletConfig config) throws ServletException
{
super.init(config);
filename = config.getInitParameter("addressfile");
This is web.xml file
<servlet>
<servlet-name>ListManagerServlet</servlet-name>
<servlet-class>savva.listmanagerservlet.ListManagerServlet</servlet-class>
<init-param>
<param-name>addressfile</param-name>
<param-value>d:\temp\demo.txt</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ListManagerServlet</servlet-name>
<url-pattern>/ListManagerServlet</url-pattern>
</servlet-mapping>
UPD: Eclipse EE Indigo, Java 1.6, Tomcat 7.0
The canonical way is to just use the inherited GenericServlet#getInitParameter() in the argumentless init() method (and remove any init(config) method).
#Override
public void init() throws ServletException {
filename = getInitParameter("addressfile");
}
If that still doesn't work, then your web.xml is not properly been deployed, or you have a typo in the parameter name, or you actually accessed a different instance variable than filename to use/test it.
Ensure your servlet is calling super.init(config) on its init method, else it won't work.
Make sure you have really deployed the proper web.xml. Also check with config.getInitParameterNames() what parameters have been found.
It's never a good idea to override the init(config) method. Instead use the provided init() convenience method and do a getServletConfig() to get the configuration parameters:
http://docs.oracle.com/javaee/1.2.1/api/javax/servlet/GenericServlet.html#init()
http://docs.oracle.com/javaee/1.2.1/api/javax/servlet/GenericServlet.html#getServletConfig()
If use the IDE STS4, checkout if annotation on the class name exists, use BOTH "annotation" and "web.xml" may cause the value null.

Categories