Eclipse Web Service: how to get current path - java

Sure this question has been asked some times already. Still, I don't get the right answer until now.
Using Eclipse, I did the following steps:
Create Dynamic Web Project
Implement my service class
Create new Web Service
It all works and the service more or less starts. Apparently, a WSDL (which I will use later) is generated as well.
In the constructor of my service implementation, I'm desperately trying to read a custom file - which resides in WebContent
I'm not very experienced at creating web services. But I'm using Tomcat 7, Axis 2 and some JPA. In any case, I cannot access the ServletContext class. I'm not implementing my own servlet either.
I tried all of these:
1
`new File(".").getAbsolutePath()`
--> returns my own home directory.
2
#Resource
private WebServiceContext context;
....
ServletContext servletContext =
(ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
--> context is always null. I found somewhere, that this is only injected after calling a first service method. Not really my solution.
3
Don't have the code handy anymore, I used some snippet with NIO. Gotta find it... Didn't work either.

If you are trying to read a file in the service, you can place it in the package and access as a resource.
InputStream is = className.class.getResourceAsStream("filename.xml");

Related

Load webapp on container startup without web.xml in Tomcat+Jersey?

I currently have a Jersey webapp without a web.xml. It deploys nicely, but doesn't start up until it receives its first web request.
To get the webapp to load at startup, I could create a web.xml for the webapp and give a load-on-startup tag. However, I'd strongly prefer not to make a web.xml.
Is there a way to get a JAX-RS application to load at startup without web.xml? I'll even accept a solution that is specific to Jersey and/or Tomcat.
EDIT: I would also accept a solution that loads all apps in a Tomcat instance eagerly.
EDIT: Let me give a little more information on how the app is being deployed, per a comment.
The deployment process is not sophisticated.
The App will live on an EC2 instance running Ubuntu 12.04. I'm setting up one instance of the App by hand; once it works, I will make an AMI of the app and create additional copies of it as needed.
To deploy the app on the initial instance, I'm simply copying the WAR file to /var/lib/tomcat7/webapps and restarting Tomcat. No other webapps will be running on this Tomcat instance.
If any additional information would be useful, let me know! I'll happily add it.
EDIT: For clarity's sake, this is how my webapp Application class looks, at a high level:
#ApplicationPath("/")
public class App extends ResourceConfig {
// ...
}
I'm using the Jersey-specific ResourceConfig class instead of the more general JAX-RS Application class because I'm using Jersey's built-in HK-2 to do some dependency injection.
The only way I can think of to do that is to switch to setting up the Jersey ServletContainer yourself and set its "load on startup" value to something greater than zero. You might use a ServletContainerInitializer (no relation--the naming is just a coincidence) to do it. If you happen to be using Spring, its WebApplicationInitializer offers the same mechanism with a slightly more convenient interface.
Another, rather hacky, way would be to write a class that extends ServletContainer and give it an appropriate Servlet 3.0 annotation, something like #WebServlet(value="/", loadOnStartup=1)
One solution would be to force a first request to the app by simply adding a call to curl or wget to your deployment script. It has the additional advantage of warming up any caches. And it can be used for testing if the deployment and the app really work. (Just check HTTP status code or some text on the response page...)

Pure java app port to glassfish

I have an application written in pure/basic Java without GUI. I have three classes with main methods, so each of them can run for themselves. Now I run them with ant in specific order.
In glassfish I deployed Web application only with RESTful service.
What I want to do now is to transfer the three classes into glassfish, so I will call them in exact same order as before from RESTful service.
I watched series of videos on youtube on Java EE 6 APIs, but I didn't find anything that would help transfer pure Java application to glassfish. Should I use EJB API for this?
There is nothing special to do. Just package the three classes into the .war file with your web service. When the web service method is called, create an instance of each class and call the appropriate method.
Of course you could also create EJBs for each class and inject an instance of each class into the web service class.
I would image that in the simplest form you can create servlet for each class that you normally call on the command line. Then, indeed you can pack them into a war file and deploy into glassfish. You do not have to use glassfish, by the way. You can use tomcat, jetty or any other servlet containers.
I assume you want the applications to run without user interaction like a human being clicking on a page. Create a singleton ejb which will be created as soon as the application is uploaded to the webserver, in the singleton create instances of your classes and call a method which should replicate the behaviour of the main method in each class.
`#Startup
#Singleton
public class StartupBean {
private MyClass obj;
private MyClass2 obj2;
#PostConstruct
initializeMyClasses(){
obj = new MyClass();
obj.start();//the start method contains code copy pasted from main
obj2 = new MyClass2();
obj2.start();`

Get properties files from multiple servlet contexts

I'm working on a web application that is spread over multiple contexts running inside one instance of tomcat. The contexts are marked with crossContext="true" so that we can share some of the jsp between the different contexts. There is also a set of common classes that are part of the common.loader for tomcat. We are to far away into the project to change this structure so please be sensitive to this structure when answering the question.
What I would like to do is get all the resources, say com.something.messages, that are present in all the different contexts. Is this at all possible? Should I record the class loader for each context created and use it to load the resources? What do you recommend?
If you're already on Servlet 3.0, then you could use ServletContext#getClassLoader() to obtain the servlet context's own class loader:
ServletContext otherContext = servletContext.getContext("/other");
ClassLoader otherClassLoader = otherContext.getClassLoader();
// ...
(if this throws a security exception, edit the policy file accordingly)
You could then pass this class loader into for example ResourceBundle#getBundle():
ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, otherClassLoader);
// ...
If that's not possible due to various reasons (e.g. not using Servlet 3.0 yet, or not willing to fiddle with policy files (very reasonable...), etc), then your best bet is to give each web application its own ServletContextListener which loads the desired bundle and stores it as an attribute of the ServletContext during the contextInitialized() method. This way you can just get it as an attribute the usual way.

Serving jetty webapp from two directories simultaneously

In development I use jetty as the servlet container. I have the following development configuration:
master project which has wabapp directory
derived project which overrides some of the files in webapp directory
The master project webapp can be started in development mode thanks to providing appropriate WebAppContext to jetty.
Now I want to start derived project analogously, assuming that when request is made, there is an attempt to:
get resource from webapp directory of derived project
if it does not exists, get it from webapp directory of master project
I know that it is possible to override WebAppContext#getResource() method, however some libraries we use in the project seem to perform IO operations on wabapp directory on their own. For example by calling ServletContext#getRealPath("/"), and then reading files without use of ServletContext#getResource() method. The problem could be solved on lower level by some virtual file system on top of File, however it does not seem to be supported in JDK 1.6, any suggestions?
It seems that using something like ResourceCollection is sufficient:
http://download.eclipse.org/jetty/stable-7/apidocs/org/eclipse/jetty/util/resource/ResourceCollection.html
Unfortunately the GWT's DevMode which I use is based on jetty 6, where ResourceCollection is unavailable. I extended the Resource class myself, and together with own GWT JettyLauncher, and thanks to small trick with setting resourceBase on DefaultServlet via reflection, I was able to serve webapp from two directories simultaneously.
protected void doStart() throws Exception {
setClassLoader(new LauncherWebAppClassLoader());
super.doStart();
ServletHolder holder = getServletHandler().getServlet("default");
Servlet servlet = holder.getServlet();
Field field = servlet.getClass().getDeclaredField("_resourceBase");
field.setAccessible(true);
field.set(servlet, combinedResourceBase);
}

What is the best way to allow both a servlet and client-side scripts read the same file?

We want to share user validation configuration between a Java validation class (for sanity checking) and a Javascript-enabled form web interface (for usability). What's the best way to deploy this static file in our web application so that it is both available to the server-side code, and available via a URL accessed by the client?
So far I've thought of putting the file in the application root and pointing the validation class at it when it is used, and putting the file in the WEB-INF/classes directory and somehow configuring the container to serve it.
Has anyone else configured a web application like this? What did you end up doing?
Yeah. Put it in the WEB-INF/classes and have a servlet serve out the relevant portion of the validation configurations based on something like a form-id. Better yet, have the servlet transform the configuration into a JSON object and then you can simply include a script tag and start using it :)

Categories

Resources