/**
* $Id$
*
* Copyright (c) 2011-2012 Jens Elkner.
* All Rights Reserved.
*
* This software is the proprietary information of Jens Elkner.
* Use is subject to license terms.
*/
package org.opensolaris.opengrok.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.opensolaris.opengrok.history.Annotation;
/**
* @author Jens Elkner
* @version $Revision$
*/
/* Apache 6.x doesn't support it:
@WebServlet(name="Annotation Servlet",
description="Provides annotations for a source file in compact JSON format",
value= "/json/annotate/*")
*/
public class AnnotationServlet extends HttpServlet {
private static final long serialVersionUID = -7799365322134860997L;
private static final Logger logger =
Logger.getLogger(AnnotationServlet.class.getName());
static void sendProlog(PrintWriter out) {
out.write("{\"data\":");
}
static void sendEpilog(PrintWriter out, boolean noDataSent, String[] errors)
throws IOException
{
if (noDataSent) {
out.write("''");
}
if (errors != null && errors.length != 0) {
out.write(',');
Util.writeJsonArray(out, "errors", errors);
}
out.write('}');
}
private static void writeAnnos(PrintWriter out, Annotation a, PageConfig cfg) {
String tmp = cfg.getConfig().getUserPage();
out.write('{');
if (tmp != null && tmp.length() > 0) {
out.write("\"userPage\":{\"link\":");
out.write(Util.jsStringLiteral(tmp));
tmp = cfg.getConfig().getUserPageSuffix();
if (tmp != null && tmp.length() > 0) {
out.write(",\"suffix\":");
out.write(Util.jsStringLiteral(tmp));
}
out.write("},");
}
out.write("\"a\":");
out.write(a.toJson());
out.write('}');
}
/**
* {@inheritDoc}
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException
{
PageConfig cfg = PageConfig.get(req);
long flast = cfg.getLastModified()/1000 * 1000;
long lmdate = cfg.getConfig().getLastModified();
if (lmdate > flast) {
flast = lmdate;
}
if (req.getDateHeader("If-Modified-Since") >= flast) {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
resp.setDateHeader("Last-Modified", flast);
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
ArrayList<String> errors = new ArrayList<String>();
int data = 0;
try {
sendProlog(out);
if (cfg.resourceNotAvailable()) {
errors.add("Resource ignored");
return;
}
Annotation annotation = cfg.getAnnotation();
if (annotation == null) {
errors.add("Annotations not available");
return;
}
writeAnnos(out, annotation, cfg);
data++;
} catch (Exception ex) {
logger.log(Level.SEVERE, req.getRequestURI(), ex);
errors.add(ex.getLocalizedMessage());
} finally {
sendEpilog(out, data == 0, errors.toArray(new String[errors.size()]));
out.close();
}
}
}