I have the java server on the cloud running. Everything is ok with GET and DELETE requests, but not ok with the PUT request. I have the following PUT request handler
#PUT
#JSONP(queryParam = "callback")
public void putEvent(String eventJson) throws Exception {
Event event = new ObjectMapper().readValue(eventJson, Event.class);
EventDao.getInstance().saveOrUpdateEvent(event);
}
And here is the Server class
public static final String BASE_API_URI = "http://localhost:8080/myrest-api/";
public boolean getFileCacheEnabled() {
return false;
}
public static void main(String[] args) throws Exception {
Server server = new Server();
final HttpServer httpServer = server.startServer();
System.out.println("Press enter to stop the server...");
System.in.read();
httpServer.shutdown();
}
public HttpServer startServer() {
final ResourceConfig rc = new ResourceConfig().packages("com.myrest.events");
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_API_URI), rc);
server.getServerConfiguration().addHttpHandler(getHttpHandler(), "/page");
return server;
}
public HttpHandler getHttpHandler() {
StaticHttpHandler handler = new StaticHttpHandler("src/main/resources/webapp/");
handler.setFileCacheEnabled(getFileCacheEnabled());
return handler;
}
When I send PUT request with following JSON body
{
"name":"SimpleName",
"description":"SimpleDescription",
"author":"Me"
}
I get
Status: 500 Request failed
Although when I deploy the app locally, and try the same everything is fine. Btw I tried POST request instead, I get the same error.
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.
I have an endpoint with:
#POST
#Path("/test")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String canaryTest(String JSON) {
return JSON;
}
When I register it in Jetty using Jersey
ServletHolder holder = new ServletHolder(new ServletContainer());
everything seems to work fine.
But in case I try to specify explictly the default config, it stops working (returning a media type error from the endpoint). Even by just passing a default instance of a ResourceConfig to the ServletContainer, it stops working.
ResourceConfig config = new ResourceConfig();
//config.property(x,defaultX)
//config.property(y,defaultY)
ServletHolder holder = new ServletHolder(new ServletContainer(config));
I'd like to emulate the default configuration behavior manually and explicitly, so what I am asking here is how should I configure ResourceConfig so the behavior keeps working (i.e, what properties to set)
P.S: i'm using Jetty 9.2.6.v20141205 and Jersey 2.14.
Dependencies in Maven:
org.eclipse.jetty.jetty-server org.eclipse.jetty.jetty-servlet
org.eclipse.jetty.jetty-servlets
org.glassfish.jersey.containers.jersey-container-servlet-core
com.sun.jersey.jersey-json
org.glassfish.jersey.media.jersey-media-json-jackson
I don't know how you got this to work
ServletHolder holder = new ServletHolder(new ServletContainer());
I could not produce a working example simply instantiating the ServletContainer(). Though I was about to get it to work with the following code
public class TestJerseyServer {
public static void main(String[] args) throws Exception {
ResourceConfig config = new ResourceConfig();
config.packages("jetty.practice.resources");
ServletHolder jerseyServlet
= new ServletHolder(new ServletContainer(config));
Server server = new Server(8080);
ServletContextHandler context
= new ServletContextHandler(server, "/");
context.addServlet(jerseyServlet, "/*");
server.start();
server.join();
}
}
Using all your dependencies, excluding the com.sun.jersey:jersey-json, as it's not needed. No other configuration. The resource class
#Path("test")
public class TestResource {
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getTest() {
Hello hello = new Hello();
hello.hello = "world";
return Response.ok(hello).build();
}
#POST
#Consumes(MediaType.APPLICATION_JSON)
public Response postHello(Hello hello) {
return Response.ok(hello.hello).build();
}
public static class Hello {
public String hello;
}
}
in the jetty.practice.resources package.
I'm curious to see how you got it to work without the ResourceConfig
Another thing I should mention is that jersey-container-servlet-core should be switched out for jersey-container-servlet. The former is for 2.5 container support, but the latter is recommended for 3.x containers. It not have any effect though, with my example
cURL
C:\>curl http://localhost:8080/test -X POST -d "{\"hello\":\"world\"}" -H "Content-Type:application/json"
world
C:\>curl http://localhost:8080/test
{"hello":"world"}
I am trying to invoke a axis2 web service enabled with Rampart security. When I try to invoke the service through the client I am getting the following exception, (I have also included Jaxen Jar in my project)
Exception in thread "main" org.apache.axis2.AxisFault: java.lang.NoClassDefFoundError: org/jaxen/JaxenException
at org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(Utils.java:446)
at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:371)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:417)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at com.tcs.secure.SecureServiceStub.add(SecureServiceStub.java:186)
at com.tcs.secure.Client.main(Client.java:16)
I have generated stubs for my password call back class and my sample class and imported it to my client. Here is my sample client.
public class Client {
public static void main(String[] args) throws RemoteException {
SecureServiceStub stub = new SecureServiceStub();
Add request = new Add();
request.setA(23);
request.setB(389);
AddResponse response = stub.add(request);
System.out.println(response);
}
}
I have embedded jetty server I want to create RESTful GET service which returns a pojo in XML/JSON format as response. can anyone give me one basic example how to write the handler for jetty? the example given only shows text type output.
I suggest you use Jersey java REST framework (http://jersey.java.net/). The framework is easy to learn. You can use Object to Xml converter like JAXB to make your life easier.
Hmm. I had the same problem.
I solved it by having a utility jar file that reads a properties file to configure contexts for Jersey Servlets, handlers, static files, exploded webapps etc in such a way that the resulting application jar configures the contexts automagically and is run from the command line.
Basically I have a HandlerCollection and successively add the servlets to it.
ServletHolder servletHolder = new ServletHolder(ServletContainer.class);
servletHolder.setInitParameter(
"com.sun.jersey.config.property.packages",
clazz.getPackage().getName()
);
ServletContextHandler context = new ServletContextHandler(
server,
"/some_path",
ServletContextHandler.SESSIONS
);
context.setClassLoader(Thread.currentThread().getContextClassLoader());
context.addServlet(servletHolder, "/");
context.setHandler(handler);
handlers.addHandler(context);
Then I have an example Jersey servlet:
#Path("/user1")
public class JerseyResource1 {
public JerseyResource1() {
}
#GET
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public ExamplePojo getUser() {
log.debug("Inside ExampleJerseyResource1 getUser()");
ExamplePojo pojo = new ExamplePojo();
pojo.setNumber(100);
pojo.setWords("hello world 1");
return pojo;
}
}
The first calls gets a perf hit as Jersey configures stuff, but it works just peachy.
A junit test looks like this:
#BeforeClass
public static void setUpClass() throws Exception {
Thread startupThread = new Thread() {
#Override
public void run() {
try {
System.out.println("Starting Jetty...");
JettyMain.main(new String[] {});
// CHECKSTYLE_OFF: Because it does throw Exception!
} catch (Exception ex) {
// CHECKSTYLE_ON
System.err.println("Error Starting Jetty: " + ex);
}
}
};
startupThread.start();
System.out.println("Waiting a few seconds to ensure Jetty is started");
Thread.sleep(2000);
System.out.println("Ok. Starting tests");
}
#AfterClass
public static void tearDownClass() throws Exception {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(
UriBuilder.fromUri(
"http://localhost:8080/admin/stop?secret=YourSecret"
).build());
service.get(String.class);
System.out.println("Sent stop command");
}
#Test
public void testJersey1() {
System.out.println("Jersey1 returns correct 200 and body");
ClientResponse response = getService(
"http://localhost:8080/jersey1/user1/"
).get(ClientResponse.class);
assertEquals("Response is 200", 200, response.getStatus());
assertEquals(
"Valid body",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<examplePojo><number>100</number><words>hello world 1</words></examplePojo>",
response.getEntity(String.class)
);
System.out.println("--> WORKED!");
}
CURL calls look like this:
# Show static public files folder:
curl -v http://localhost:8080/public/x.html
curl -v http://localhost:8080/public/x.txt
# Use baseline handlers:
curl -v http://localhost:8080/handler1/?url=hello
curl -v http://localhost:8080/handler2/?url=hello
# Use raw servlets with specific contexts:
curl -v http://localhost:8080/servlet1?url=hello
curl -v http://localhost:8080/servlet2?url=hello
# Call a Jersey servlet using default Accept header (xml):
curl -v http://localhost:8080/jersey1/user1/
curl -v http://localhost:8080/jersey2/user2/
# Request Jersey servlet but want JSON:
curl -v --header "Accept:application/json" http://localhost:8080/jersey1/user1/
# Use an exploded webapp:
curl -v http://localhost:8080/www/x.html
# Stop the server:
curl -v http://localhost:8080/admin/stop?secret=MySecret
Er... The following is not a plug. Seriously. It might be refused by the company...
I have a complete solution by which 1 jar file is added as a dependency and several tiny files (app.properties, classpath.sh, log4j.properties and run.sh) that completely configure a Jetty8 instance for numerous contexts, Handlers, Servlets, JerseyServlets, StaticFiles and ExplodedWebApps. The result is a self contained executable Jar that restarts, reloads, stops etc with almost zero effort. An added benefit is that it can act as a pseudo-classloader and avoids jar-hell. (A side effect is that mvn clean test works against it also)
If any one is interested, ping me and I can see if the company will allow me to OpenSource it and get it up on GitHub.
Or perhaps even document it via my own site http://www.randomactsofsentience.com
Just FYI on embedded Jetty in general... I have created a github project that I humbly submit may cover most of the embedded jetty issues that keep cropping up. See https://github.com/ZenGirl/EmbeddedJettyRepository for details.
Using a framework to handle the serialisation of JSON is the way to go. However, here is a simple example:
public class MyServer extends AbstractHandler
{
private static final int PORT = 8080;
#Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().print("{ \"my_data\": \"Hello from Java!\" }");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
}
public static void main(String[] args) throws Exception {
Server server = new Server(PORT);
server.setHandler(new MeServer());
server.start();
System.out.println("Jetty started: http://localhost:" + PORT + "/");
server.join();
}
}