Serving static CSS file from a Jersey REST service - java

I have an application running on embedded Tomcat and using Jersey. There is a resource class that exposes some endpoints, written like in this tutorial: http://www.sortedset.com/embedded-tomcat-jersey/. Everything is working fine, now I would like one of the endpoint methods to output formatted text.
My method in the resource looks like this:
#Path("/res")
#GET
#Produces("text/html")
public String get(){
return "<html><head><link rel='stylesheet' href='/style.css'></head><body>some text</body></html>";
}
}
I put the style.css in the WebContent folder.
When I access the resource, the text is displaying as expected, but the link to the .css file seams to have no effect.
What could be the problem?
Update
After Paul's suggestions in the comments, I tried to add the servlet context path the URL path, but it still is not working
1)
#Path("/res")
#GET
#Produces("text/html")
public String get(#Context ServletContext ctx) {
String ctxPath = ctx.getContextPath();
return "<html><head><link rel='stylesheet' href='+"ctxPath"+/style.css'></head><body>some text</body></html>";
}
}
2)
String ctxPath = ctx.getRealPath("/");
return "<html><head><link rel='stylesheet' href='+"ctxPath"+style.css'></head><body>some text</body></html>";
Update
Since the problem could be somewhere here, this is the part of the Main class, where I start the embedded Tomcat and set up the web application
public void start() {
String webappDirLocation = "WebContent/"
Tomcat tomcat = new Tomcat();
tomcat.setPort(0);
Context ctx = tomcat.addWebApp("", new File(webappDirLocation).getAbsolutePath());
Tomcat.addServlet(ctx, "jersey-container-servlet", resourceConfig()).addMapping("/*");
//start tomcat
}
private ServletContainer resourceConfig() {
return new ServletContainer(new ResourceConfig(new ResourceLoader().getClasses()));
}

Related

JAX-RS Post requests works fine locally but doesn't on Heroku. What can it be?

I uploaded the server project by WAR file in Heroku, Jersey is okay working locally, just isn't in the server, so annotations seems okay. JSP pages age working both locally and remotely with Spring MVC and Hibernate in a Maven project. URLs seems okay to the request. It returns me 500 Internal Server Error, even when I try by post http request online. What can it be?
Unity Client:
public class Test{
//Simplified version of the code:
public string Testing() {
string url = URL.HEROKUPOST.url;
WWWForm form = new WWWForm();
form.AddField( "JsonRequest", "JsonRequest");
form.AddField( "Action", "Action");
WWW www = new WWW( url, form );
yield return www;
if (string.IsNullOrEmpty(www.error))
{
yield return www.data;
}
else
{
yield return www.error ;
}
}
Java Server:
#Path("/helloworld")
public class JSONController
{
#POST #Produces("application/json")
public String unityRequest(#FormParam("JsonRequest") String requisition, #FormParam("Action")String action)
{
return "Okay";
}
}

Jersey, using HTML file instead of HTML string

Currently I need to programm a RESTful Webservice in Java and I'm using Grizzly server as my server and I'm using Jersey for the HTML code generation.
This is my Grizzly server:
public static void main(String[] args) throws IOException {
URI baseUri = URI.create("http://localhost:9998");
final ResourceConfig resourceConfig = new ResourceConfig(homepage.class);
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig);
System.out.println("Starting grizzly ...");
JOptionPane.showMessageDialog(null, "Stop Server");
server.shutdownNow();
}
And this is my current homepage code:
#Path("")
public class homepage {
#GET
#Produces("text/html")
public String sayHelloInHtml() {
return "<html><body><h2>Hello World</h2></body></html>";
}
}
Right now I'm using a string for my HTML code but is their a way to use a HTML file instead?
Also how can I create a button that triggers a Java method on click? I know how to create a button but I don't know how to make the event handler to trigger the Java method on click.

Does anyone encounter unuseful rootpath in resteasy

I'm using RESTEasy to write a example of WebService, and set the root resource path.But I find that even no root path in the url, I still can get the right resource.
Main function Code:
NettyJaxrsServer netty = new NettyJaxrsServer();
ResteasyDeployment deploy = new ResteasyDeployment();
List<Object> resources = new ArrayList<Object>();
resources.add(new UserService());
deploy.setResources(resources);
netty.setDeployment(deploy);
netty.setPort(8180);
netty.setRootResourcePath("/hello/");
netty.setSecurityDomain(null);
netty.start();
Service Code:
#Path("user")
#Produces(MediaType.APPLICATION_JSON)
public class UserService {
For the code, url /user can work normal, no need to add root path of /hello. I checked the source code; it adds the root path by itself.
source code:
public static String getEncodedPathInfo(String path, String contextPath)
{
if(contextPath != null && !"".equals(contextPath) && path.startsWith(contextPath))
path = path.substring(contextPath.length());
return path;
}
My question is why RESTEasy do this? I can't understand.

How to return actual html file using JAX-RS

so far, I'm returning html my home page by:
#GET
#Produces({MediaType.TEXT_HTML})
public String viewHome()
{
return "<html>...</html>";
}
what I want to do is return home.html itself and not copying its contents and returning the string instead.
How do I do this? thanks :)
You can just return an instance of java.io.InputStream or java.io.Reader — JAX-RS will do the right thing.
#GET
#Produces({MediaType.TEXT_HTML})
public InputStream viewHome()
{
File f = getFileFromSomewhere();
return new FileInputStream(f);
}
Read the File using getResourceAsStream
write back to returned String.
This is my preferred way of serving a web page using JAX-RS. The resources for the web page (html, css, images, js, etc.) are placed in main/java/resources, which should deploy them in WEB-INF/classes (may require some configuration depending on how you set up your project). Inject ServletContext into your service and use it to find the file and return it as an InputStream. I've included a full example below for reference.
#Path("/home")
public class HomeService {
#Context
ServletContext servletContext;
#Path("/{path: .+}")
#GET
public InputStream getFile(#PathParam("path") String path) {
try {
String base = servletContext.getRealPath("/WEB-INF/classes/files");
File f = new File(String.format("%s/%s", base, path));
return new FileInputStream(f);
} catch (FileNotFoundException e) {
// log the error?
return null;
}
}
}
You can use HtmlEasy which is built on top of RestEasy, which is a really good implementation of Jax-RS.

Reference to own wsdl url

I'm building a web service that's supposed to register on another server by sending its wsdl URL to that server.
I built a very basic web service in Netbeans,
#WebService
public class RegisterTest{
#WebMethod(operationName = "emphasize")
public String emphasize(#WebParam(name = "inputStr") String input){
return input + "!!!";
}
}
and Netbeans automatically directs me to localhost:8080/RegisterTest/RegisterTestService?Tester, and naturally, the wsdl can be found at localhost:8080/RegisterTest/RegisterTestService?wsdl.
How would I programmatically get this URL?
Edit:
I've noticed that the only place that seems to store this URL is the glassfish server itself. The context-root seems to only be found in glassfish/domain//config/domain.xml.
Is there a nice way of accessing the glassfish server APIs? I can easily get the endpoint address through the UI in applications > serviceName > View Endpoint, is there a programmatic way of doing this?
I've tried looking through asadmin commands, but can't seem to find anything there that gets the context-root or the endpoint URL either.
Untested, but should be pretty close to what you're looking for:
#WebService
public class RegisterTest
{
#Resource
private WebServiceContext context;
#WebMethod(operationName = "emphasize")
public String emphasize(#WebParam(name = "inputStr") String input)
{
return input + "!!!";
}
#WebMethod(operationName = "getWsdlUrl")
public String getWsdlUrl()
{
final ServletContext sContext = (ServletContext)
this.context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
final HttpServletRequest req = (HttpServletRequest)
this.context.getMessageContext().get(MessageContext.SERVLET_REQUEST);
final StringBuilder sb = new StringBuilder();
sb.append(req.isSecure() ? "https" : "http");
sb.append("://");
sb.append(req.getLocalName());
if ((req.isSecure() && req.getLocalPort() != 443) ||
(!req.isSecure() && req.getLocalPort() != 80))
{
sb.append(":");
sb.append(req.getLocalPort());
}
sb.append(sContext.getContextPath());
sb.append(RegisterTest.class.getSimpleName());
sb.append("Service?wsdl");
return sb.toString();
}
}

Categories

Resources