public static final byte[] TERMINATING_BYTES = new byte[] { -100, -100,
-100, -100, -100, -100 };
static final long serialVersionUID = 1L;
private Map<String, List<Shareable>> shareablesSentToClients;
/*
* (non-Java-doc)
*
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public ShareablePostingServlet() {
super();
shareablesSentToClients = new HashMap<String, List<Shareable>>();
}
/*
* (non-Java-doc)
*
* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
* HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.resetBuffer();
HttpSession session = request.getSession();
String id = session.getId();
String shareableIdasString = request.getParameter("shareableId");
OutputStream out = response.getOutputStream();
WebApplicationContext context = WebApplicationContextUtils
.getWebApplicationContext(this.getServletContext());
try {
if (shareableIdasString != null) {
Shareable shareable = ((ShareableDao) context
.getBean("ShareableDao")).getShareableById(Long
.valueOf(shareableIdasString));
out.write(shareable.getContent());
} else {
if (shareablesSentToClients.get(id) == null) {
shareablesSentToClients.put(id, new ArrayList<Shareable>());
}
List<Shareable> shareables = ((ShareableDao) context
.getBean("ShareableDao")).getShareables(null);
// don't resend the same shareables to the same clients
for (Shareable shareable : shareables) {
if (!shareablesSentToClients.get(id).contains(shareable)) {
shareablesSentToClients.get(id).add(shareable);
shareable.setContent(null);
out.write(shareable.getBytes());
out.write(TERMINATING_BYTES);
}
}
System.out.println();
}
} catch (Exception e) {
out.write(("There was a problem" + e.getMessage()).getBytes());
}
}
/*
* (non-Java-doc)
*
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
* HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
InputStream inputStream = request.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int current;
while ((current = inputStream.read()) != -1) {
bos.write(current);
}
Shareable shareable;
try {
byte[] rawByteArray = bos.toByteArray();
shareable = Shareable.readFromBytes(rawByteArray);
WebApplicationContext context = WebApplicationContextUtils
.getWebApplicationContext(this.getServletContext());
((ShareableDao) context.getBean("ShareableDao"))
.uploadShareable(shareable);
PrintWriter out = response.getWriter();
out.println(shareable.getDescription());
} catch (ParseException e) {
PrintWriter out = response.getWriter();
out.println("There was a problem");
} catch (BeansException e) {
PrintWriter out = response.getWriter();
out.println("There was a problem");
} catch (Exception e) {
PrintWriter out = response.getWriter();
out.println("There was a problem");
}
}