Open html file on Tomcat server in Restfull web service - java

I hava a small web service which is running on tomcat server and i want to open my html file on my tomcat server.
My web service is:
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("myresource")
public class MyResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() throws Exception {
String url = "E:/this.html";
File htmlFile = new File(url);
Desktop.getDesktop().browse(htmlFile.toURI());
return "Got it!";
}
}

These answers are based on the potential questions in the comments section of the question.
Q: Which url do I put in your browser to see the message "Got it!"?
A: http://localhost:8080/myresource
However, that might not be the exact case for you. There are lots of ways of setting up a web container (like tomcat) and you will have to verify what port you're running on and what your servlet context is. The above answer assumes that you are running on your local machine, under port 8080 (which tends to be the default for java web servers) and under the ROOT context.
A more complete answer would be:
http://<host_name>:<port>:<context>/myresource
Q: How do I allow the End User to say which file they want to download?
A: This is a HUGE security risk. Allowing an End User to enter a path to a file on the server is just not smart. No offense...
The End User could just enter {/etc/passwd} and depending on which system user was used to start your web container, the web container will serve that file. Not a good situation.
Q: Ok, great, so how do I allow a user to download a file from my web container?
A: There are several ways of doing this and I won't go into great detail, but, you could allow the container to serve the files themselves directly. Meaning place the files inside of the /webapp directory itself. Then your web container will serve them automajically.
You could set a directory in your MyResource classes constructor and only serve requested files from that particular directory. You would need to do some serious validation on End User input to verify that they aren't asking for a file like this: ../../../../etc/passwd
Q: FINE, got it, so I'll do validation, NOW, how do I actually serve the file to the End User? I promise I'll be careful...
Well, that is easy, just go take a peek at this question here:
what's the correct way to send a file from REST web service to client?

Related

How to create simple RESTful service in IntellijIDEA 2016? (JAX-RS)

My google-fu has failed me.
I have lost 2.5 hours trying to figure this out. I just want to make this simple RESTful service with get and post requests that generate hello world on get (i.e. localhost:9000/hello ) and on post prints to service console what was sent in bla variable.
I have found some simple examples
import javax.ws.rs.GET;
import javax.ws.rs.Path;
#Path("greeting")
public class Greeter {
#GET
public String sayHi() {
return "Hi!!";
}
}
But it doesn't work intellij doesnt recognize Path and GET annotations. It asks me if I want to implement them. I've tried on both NewProj->JavaEE->Restful Web Service and NewProj->Java->WebApp->WebServices.
Some sample generated code from one of them made this #webmethod annotation for which I wasn't able to find any info on the net. And the JetBrains video from 2013 looks like an overkill/a-bit-outdated?. This is really simple app, I don't need/know how to use/ Maven.
You need to download the jar-file containing the classes you have imported (from e.g. http://download.oracle.com/otndocs/jcp/jaxrs-2_0_rev_A-mrel-spec/index.html).
Open Project Structure, Go to Libraries, press the plus button, and add the jar-file to your project.

Embedding Jetty as a Servlet Container

I'm using Tomcat to serve my Java Servlets and it's kinda more for me. I just need to serve, Servlet Requests alone, no static content, neither JSP, etc. So I was looking for a Servlet container that can be embedded in my Application. I felt it if stripped Jetty and use it as a Servlet Container alone, it can be more scalable and occupying small memory footprint, [I don't need Jetty's 'Web Server' and other Parts]. So I've a few questions though,
How do I embed Jetty in my Application Code to serve Servlet Requests alone?
If I embed Jetty code in my Application Code, will I be able to easily upgrade Jetty Versions?
I got the Jetty code here, if I have to embed Jetty's Servlet Container in my App, which one should I use from the source,
http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/snapshot/jetty-9.0.3.v20130506.tar.bz2 ,
jetty-9.0.3.v20130506/jetty-servlet or jetty-9.0.3.v20130506/jetty-servlets
I intend to serve API Requests with my Applications and I'm looking for Performance and Scalability as main constraints. And of course Servlet 3.0 support.
What you are looking for is running Jetty in an embedded scenario.
There's plenty of examples available showing how to tie together the various pieces you need to accomplish your goals.
Check out the embedded examples in the jetty source tree.
For the record, jetty standalone is really just jetty embedded with a few startup and classpath related bootstraps. It is the same code, and assembled in basically the same way.
Since you stated you want Servlet 3.0, have no interest in JSP, this is rather easy to setup. (JSP is trickier to setup, but possible).
For servlet 3.0 specific embedding, there's a complete example project hosted at github.
https://github.com/jetty-project/embedded-servlet-3.0
In short, you'll have the following initialization code.
package com.company.foo;
import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.plus.webapp.EnvConfiguration;
import org.eclipse.jetty.plus.webapp.PlusConfiguration;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.FragmentConfiguration;
import org.eclipse.jetty.webapp.MetaInfConfiguration;
import org.eclipse.jetty.webapp.TagLibConfiguration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.webapp.WebInfConfiguration;
import org.eclipse.jetty.webapp.WebXmlConfiguration;
public class EmbedMe {
public static void main(String[] args) throws Exception {
int port = 8080;
Server server = new Server(port);
String wardir = "target/sample-webapp-1-SNAPSHOT";
WebAppContext context = new WebAppContext();
// This can be your own project's jar file, but the contents should
// conform to the WAR layout.
context.setResourceBase(wardir);
// A WEB-INF/web.xml is required for Servlet 3.0
context.setDescriptor(wardir + "WEB-INF/web.xml");
// Initialize the various configurations required to auto-wire up
// the Servlet 3.0 annotations, descriptors, and fragments
context.setConfigurations(new Configuration[] {
new AnnotationConfiguration(),
new WebXmlConfiguration(),
new WebInfConfiguration(),
new TagLibConfiguration(),
new PlusConfiguration(),
new MetaInfConfiguration(),
new FragmentConfiguration(),
new EnvConfiguration() });
// Specify the context path that you want this webapp to show up as
context.setContextPath("/");
// Tell the classloader to use the "server" classpath over the
// webapp classpath. (this is so that jars and libs in your
// server classpath are used, requiring no WEB-INF/lib
// directory to exist)
context.setParentLoaderPriority(true);
// Add this webapp to the server
server.setHandler(context);
// Start the server thread
server.start();
// Wait for the server thread to stop (optional)
server.join();
}
}

How to do HTTP binding for Openfire plugin

I'm using Openfire as the chat server for my company. And now I need to create a plugin for Openfire.
As I can see from other plugins, they can have HTTP binding to themself through port 7070.
For example: http://example.com:7070/redfire where redfire is the name of the plugin.
The name of my plugin is toplug, so I want to be able to access the JSP pages of my plugin through: http://example.com:7070/toplug/index.jsp where 'index.jsp' is some example page.
But when I try to access my JSP pages through port 7070, the Jetty server (on which Openfire runs) always reports error 404 'page not found'. I guess this is because the binding to my folder which contains JSP pages hasn't been set. How to do this binding thing please?
The question is answered here:
http://community.igniterealtime.org/message/224134
You do not need a plugin to access the web service for the http bing port. Just put your web pages in a folder under:
OPENFIRE_HOME/openfire/resources/spank
and access with:
http://example.com:7070/your_folder/your_page.html
Note that Openfire does not compile JSP pages unless you replace jasper-xxxx.jar files in the lib folder.
If you still want to create a jetty web context (application) from your plugin, see source code of Redfire plugin:
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.webapp.WebAppContext;
...
public void initializePlugin(PluginManager manager,File pluginDirectory) {
ContextHandlerCollection contexts =
HttpBindManager.getInstance().getContexts();
context = new WebAppContext(contexts,pluginDirectory.getPath(),"/"+NAME);
context.setWelcomeFiles(new String[]{"index.html"});
...

How do I find the URL of my web service?

I know this might seem a stupid question but I am just not able to find any information regarding this question.
I have a java web service (generated using NetBeans) and inside the web service class I would like to know the URL at which the web service was deployed.
For example, if I am deploying the web service on my local glassFish server, the web service is available at "http://localhost:8080/MyService/" where "MyService" is the name of my service.
The reason I need to know this URL is because my web service generates some files that I need to make available at this URL. For example, the web service call returns a URL "http://localhost:8080/MyService/report.html"
I have found some links about "WebServiceContext" but I am not able to get the URL at which my web service is running.
Edited
To clarify: Inside MyWebService.java class I want to find out the URL at which my web service was deployed (in this case, my web service is running at "http://localhost:8080/MyService/", but once it is deployed on a production server, this URL will change)
Easier in my opinion, for example:
#GET
public URI redirectSendMail(#Context UriInfo ui) {
return ui.getBaseUri();
}
If we want to send a String back to the client, indicating the exact path of some resource, we might want something like this.
#GET
public String getResourcePath(#Context UriInfo ui) {
return ui.getAbsolutePath();
}
If you are asking how to find the hostname (e.g. 'localhost' or 'www.example.com') that your servlet container is listening to you have a few options:
Add a configuration point that is set at deployment time (e.g. config file, system property)
Look into if your servlet container exposes any 'virtual host' configuration via JMX or read its config files (e.g. tomcat hosts)
Find the IP Address of the server and do a DNS lookup to get its configured hostname
Inspect the 'Host' header of the incoming HttpServletRequest
String hostname = request.getRequestHeader("Host");
Add the below property in your webservice class.
#Resource
private WebServiceContext wsCtxt;
Now below code snippet will give you the values you are looking for:
MessageContext msgCtxt = wsCtxt.getMessageContext();
HttpServletRequest request =
(HttpServletRequest)msgCtxt.get(MessageContext.SERVLET_REQUEST);
String hostName = request .getServerName();
int port = request .getServerPort();
to check from where the webservice was invoked, use the below code.
String clientIP = request .getRemoteAddr();
Related imports are below:
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import weblogic.jws.Context;
import weblogic.wsee.jws.JwsContext;
Hopefully I am able to help you, I have just recently started working with webservices (Jersey REST) and I have found that the url to your endpoint is :
'http://localhost:8080/MyService/XXX/YYY'
where XXX = the URL pattern in the servlet mapping in your web.xml file (eg. file below)
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
and the YYY is the path defined by your webservice's #Path() parameter so in the case of this example it would be something like:
'http://localhost:8080/MyService/rest/myPathDefinition'
Another thing to note is that you can in fact change the web context root in eclipse, though it will default to the name of your Java project. Please let me know if you need further clarification or if this did not help / someone can expand on it.
It could be found on your wsdl file as:
therefore: http://localhost:8080/TestSOAPWebservice/services/TestClassImpl?wsdl would be the url to your wsdl file.

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