I am working on a web application that will run on a Jetty server. I want to be able to put an object into a hashmap from the Application itself and then read back the same Object using a Client. I created a Singleton instance of the HashMap in both the application and the client thinking it would be the same instance, but after printing both Objects to the console, I am seeing that they are two separate instances and thus do not contain the same data. Does anyone know how to make the HashMap accessible from the app and from the client? Looking at this post, Singleton is not really a singleton I see that I should be using org.eclipse.jetty.webapp.WebAppContext
to set the parent loader but am not exactly sure how to approach this. Here is what I have so far.
Server:
public static void main(String[] args) throws Exception {
Server server = new Server(8888);
ServletHandler handler = new ServletHandler();
handler.addServletWithMapping(App.class, "/S3Mock");//Set the servlet to run.
server.setHandler(handler);
server.start();
server.join();
}
App:
@SuppressWarnings("serial")
public class App extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
S3Controller s3cont = new S3Controller();
Map appMap = Storage.getInstance();
s3cont.putObject(appMap, "aws.amazon.com/buckets/mybucket", new Object());
s3cont.putObject(appMap, "aws.amazon.com/buckets/mybucket2", new Object());
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("<h2>AWS S3</h2>");
}
}
Client:
public static void main(String[] args) {
Client client = Client.create();
//Get
WebResource webResource = client.resource("http://localhost:8888/S3Mock");
ClientResponse response = webResource.accept(MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
S3Controller s3cont = new S3Controller();
Map m = Storage.getInstance();
Object b = s3cont.getObject(m, "aws.amazon.com/buckets/mybucket2");
if(b != null)
System.out.println(b.toString());
else
System.out.println("Object not found");
}
Storage:
public class Storage {
private static Map<String, Object> theMap = new HashMap<String, Object>();
private Storage() {}
public static Map getInstance() {
return theMap;
}
}
After firing up the Jetty server, when I run the client, the console reads, Object not found
which tells me that that there are, in fact, two separate HashMap instances.