Following Jersey Tutorial - java

I am trying to follow the first part of jersey tutorial using Grizzly as the web container. I am just at the "Hello World!" part and trying to run my code. This is the main of the web services that I am trying to deploy.
public class Main {
public static void main(String [] args) throws IOException {
final String baseUri = "http://localhost:9998";
final Map<String, String > initParams = new HashMap<String, String>();
initParams.put("com.sun.jersey.config.property.packages", "com.sun.ws.rest.samples.helloworld.resources");
System.out.println("Starting grizzly");
SelectorThread threadSelector = GrizzlyWebContainerFactory.create(baseUri,initParams);
System.out.println(String.format("Jersey app started with WADL available at %sapplication.wadl Try out %shelloworld. Hit enter to stop it...", baseUri, baseUri));
System.in.read();
threadSelector.stopEndpoint();
System.exit(0);
}
}
When I run this, I always get
Exception in thread "main" java.lang.IllegalArgumentException: The URI path, of the URI http://localhost:9998, must be present
at com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory.create(GrizzlyWebContainerFactory.java:236)
at com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory.create(GrizzlyWebContainerFactory.java:138)
at com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory.create(GrizzlyWebContainerFactory.java:105)
at Main.main(Main.java:29)
Does anyone know what is happening? I have made sure that my packages are all correct. I do not know how to configure grizzly and just trying to learn how to use Jersey

final String baseUri = "http://localhost:9998/";
Note the / on the end; you're missing it.

Related

Running jrxlm report with Jasper Server

I have created jrxml report by iReport. Then I have run it with JasperServer and it work perfectly. I have generate pdf report by this URL:
http://localhost:8081/jasperserver/flow.html/flowFile/my_report.pdf
It works well but when I tried to refresh the page I get this error:
An id is required to lookup a FlowDefinition
Also when I try to call this REST service in JasperServer client application I get this error:
com.sun.jersey.api.client.UniformInterfaceException: Client response status: 500
This is the Java client application to call the REST service:
public final static String serverUrl = "http://localhost:8081/jasperserver/flow.html/flowFile/my_report.xls";
public final static String serverUser = "jasperadmin";
public final static String serverPassword = "jasperadmin";
static File outPutDir= new File(System.getProperty("java.io.tmpdir"));
public static void main(String[] args) {
try {
Report report = new Report();
report.setUrl("/reports/samples/Employees");
report.setOutputFolder(outPutDir.getAbsolutePath());
JasperserverRestClient client = JasperserverRestClient.getInstance(serverUrl, serverUser, serverPassword);
File reportFile = client.getReportAsFile(report);
} catch (Exception e) {
e.printStackTrace();
}
}
flowId
When calling flow.html you must provide an action, which is put into the flowId. JasperServer is using the flow.html to provide an interface which can be accessed over the URL. For example if calling a report this would be:
_flowId=viewReportFlow
Also the report and parameters have to be provided. So with this in mind the URL could look like this:
http://localhost:8081/jasperserver/flow.html?_flowId=viewReportFlow&reportUnit=/reports/samples/Employees&j_username=the_user&j_password=secret&output=pdf
Server error
When connecting to the server, this URL is used
http://localhost:8081/jasperserver/flow.html/flowFile/my_report.xls
This is not the server URL used by JasperserverRestClient. The server URL should look like this:
http://localhost:8081/jasperserver
NOTE: flow.html is for accessing JasperServer without logging into the UI. It is not an application path where you should put your reports.

'before' method is said to be undefined - spark java

I am new to building web applications using spark java.
I am trying to use 'Before' filter but getting the below error. please help. I have pasted my code below.Bootstrap is my class having the main method.
Error: "The method before is undefined for the type BootStrap"
public class BootStrap {
public static void main(String[] args) throws Exception {
ipAddress("localhost");
port(3003);
staticFileLocation("/public/html");
before((request, response) -> {
String user = request.queryParams("user");
String password = request.queryParams("password");
String dbPassword = usernamePasswords.get(user);
if (!(password != null && password.equals(dbPassword))) {
halt(401, "You are not welcome here!!!");
}
});
}
I think it's just lacking to statically import Spark.*;
Not sure this helps, but according to this "Access-Control-Request-Method" is a request header, not a response header. That said, a 404 always shows that the resource you want to find does not exist. Are you sure your url is correct?

Static Variable gives null or default value when read in an EJB- jboss EAP 6.1.0

We have migrated our application from weblogic 10.0 to jboss EAP 6.1.0.
While accessing the properties which is loaded in the init() method of the servlet from our EJB, the value returned is null.
Below method is in Ejbbean class:
public void execute() throws EJBException
{
System.out.println("Constants.x in execute ----"+Constants.x);
}
the value printed here is null. Although if we use the same code inside our application anywhere other than EJB, the correct value is returned.
We are loading the properies inside the init method of servlet.
public void init() throws javax.servlet.ServletException
{
ServletContext sContext = this.getServletContext();
try
{
String propFile = sContext.getInitParameter("abc");
Properties prop = new Properties();
FileInputStream inStream = new FileInputStream(propFile);
prop.load(inStream);
Constants.loadValues(prop);
System.out.println("Constants.x in execute ----"+Constants.x);
}
the correct value for static variable x is printed here.
public final class Constants
{
public static String x = null;
public final static void loadValues(Properties prop) throws Exception
{
// the properties are loaded here...
}
}
Whats the reason behind this unexpected behaviour of static variable inside EJB when the same code is working fine elsewhere? This problem was not there in the application when it was deployed on weblogic server.
How can this be fixed?
I got the solution to this problem. jboss-deployment-structure.xml needs to be written for the application with the dependency of the EJB on the WAR.
Reference link:
http://www.mastertheboss.com/jboss-server/jboss-deploy/configuring-jboss-as-7-deployment-order

REST API + Java Multithreaded

I managed to build a small REST API using eclipse. The following code works:
#Path("Info")
public class Rest {
#POST
#Path("/stats/{j}")
#Produces("application/json")
public Response Status(#PathParam("j") String j) throws JSONException{
JSONObject jsonObject = new JSONObject();
String status = j;
.
.
return Response.status(200).entity(result).build();
}
}
Could you advise me on how make this a multithreaded? I have an idea of what is multithreaded but I need some input on how to go about creating this code as multithreaded. was thinking of creating another class that implements Runnable:
class Demo implements Runnable {
.
.
}
Then, in my function Status(#PathParam("j") String j), I create an object of class Demo, For example:
public Response Status(#PathParam("j") String j) throws JSONException{
Demo newThread = new Demo();
JSONObject jsonObject = new JSONObject();
String status = j;
.
.
return Response.status(200).entity(result).build();
}
}
Thank you in advance!
It already is multithreaded.
When deploying the application into an application server such as Jetty or Tomcat the thread pool of the application determines how many threads will be used to serve web request. Every time a user makes a new web request against your controller method, one of the available threads from the application server threadpool will be used.

Restlet - trouble attaching Resource class with Router

Prototyping with Restlet 2.1.0, Java SE version, I am having trouble mapping ServerResource classes to urls. I've tried quite a few variations using the Router.attach method, but nothing has worked.
My current code looks like this:
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
final Router router = new Router();
router.attach("/hello", FirstServerResource.class);
router.attach("/json", Json.class);
Application myApp = new Application() {
#Override
public org.restlet.Restlet createInboundRoot() {
router.setContext(getContext());
return router;
};
};
new Server(Protocol.HTTP, 8182, myApp).start();
}
When I browse to http://localhost:8182/hello it doesn't do the template match correctly. Debugging through the source code, I see what happens is that the match logic sees the requested resource as http://localhost:8182/hello instead of just /hello. The Restlet code where this happens is here:
// HttpInboundRequest.java
// Set the resource reference
if (resourceUri != null) {
setResourceRef(new Reference(getHostRef(), resourceUri));
if (getResourceRef().isRelative()) {
// Take care of the "/" between the host part and the segments.
if (!resourceUri.startsWith("/")) {
setResourceRef(new Reference(getHostRef().toString() + "/"
+ resourceUri));
} else {
setResourceRef(new Reference(getHostRef().toString()
+ resourceUri));
}
}
setOriginalRef(getResourceRef().getTargetRef());
}
In the code above, it sees the Resource as relative, and therefore changes the requested resource from /hello to the full url. I'm missing something obvious here, but I'm totally stumped.
Finally found the solution by turning on the logging (FINE). I saw this log message:
By default, an application should be attached to a parent component in
order to let application's outbound root handle calls properly.
I don't totally understand what it meant (maybe I have to read docs start to finish?). Attaching the application to a VirtualHost fixed the problem:
public static void main(String[] args) throws Exception {
final Router router = new Router();
router.attach("/hello", FirstServerResource.class);
router.attach("/json", Json.class);
router.attachDefault(Default.class);
Application myApp = new Application() {
#Override
public org.restlet.Restlet createInboundRoot() {
router.setContext(getContext());
return router;
};
};
Component component = new Component();
component.getDefaultHost().attach("/test", myApp);
new Server(Protocol.HTTP, 8182, component).start();
}

Categories

Resources