PageRenderTime 129ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/net/handle/servlet/OpenHandleServlet.java

http://openhandle.googlecode.com/
Java | 243 lines | 139 code | 24 blank | 80 comment | 11 complexity | fcafeebe43e9c1208420afa7f2a62108 MD5 | raw file
  1. /*
  2. * Created by: christopher
  3. * Date: 14 Sep 2007
  4. * Time: 14:49:55
  5. *
  6. * <p>Copyright (C) 2007 Nature Publishing Group, Inc.</p>
  7. *
  8. * <p><a rel="license" href="http://creativecommons.org/licenses/GPL/2.0/">
  9. * <img alt="Creative Commons License" style="border-width:0"
  10. * src="http://i.creativecommons.org/l/GPL/2.0/88x62.png" /></a><br />
  11. * This work is licensed under a <a rel="license"
  12. * href="http://creativecommons.org/licenses/GPL/2.0/">Creative Commons GNU
  13. * General Public License License</a>.</p>
  14. */
  15. package net.handle.servlet;
  16. import static org.apache.commons.lang.StringUtils.isBlank;
  17. import static org.apache.commons.lang.StringUtils.isNotBlank;
  18. import java.io.IOException;
  19. import java.io.Writer;
  20. import java.util.Properties;
  21. import javax.servlet.ServletConfig;
  22. import javax.servlet.ServletContext;
  23. import javax.servlet.ServletException;
  24. import javax.servlet.http.HttpServlet;
  25. import javax.servlet.http.HttpServletRequest;
  26. import javax.servlet.http.HttpServletResponse;
  27. import net.handle.hdllib.HandleException;
  28. import org.apache.commons.configuration.Configuration;
  29. import org.apache.commons.configuration.XMLConfiguration;
  30. import org.apache.commons.logging.Log;
  31. import org.apache.commons.logging.LogFactory;
  32. import org.apache.velocity.VelocityContext;
  33. import org.apache.velocity.app.VelocityEngine;
  34. import org.apache.velocity.context.Context;
  35. import org.apache.velocity.tools.generic.DateTool;
  36. /**
  37. * <p>
  38. * Servlet to obtain handle record data and return as any desired
  39. * representation.
  40. * </p>
  41. *
  42. * @author <a href="mailto:christopher.townson@googlemail.com">Christopher
  43. * Townson</a>
  44. * @author <a href="mailto:tony.hammond@gmail.com">Tony Hammond</a>
  45. */
  46. public class OpenHandleServlet extends HttpServlet {
  47. private static final long serialVersionUID = 3323381446195576928L;
  48. private static final Log LOG = LogFactory.getLog(OpenHandleServlet.class);
  49. private OpenHandle resolver;
  50. private Settings settings;
  51. private VelocityEngine velocity;
  52. /**
  53. * <p>
  54. * Performs steps necessary to correctly configure and initialize this
  55. * servlet. At present, this consists of the following:
  56. * </p>
  57. * <ol>
  58. * <li>Attempting to load a custom config, if one is specified as an
  59. * init-param using the key 'config'.</li>
  60. * <li>Loading the default config if no custom config is available.</li>
  61. * <li>Loading up an instance of {@link Settings} from the config.</li>
  62. * <li>Initializing an instance of {@link OpenHandle} to act as a resolver.</li>
  63. * </ol>
  64. * <p>
  65. * A custom configuration detailing available templates, handle client
  66. * options, and request parameter names can be specified as an init-param:
  67. * </p>
  68. *
  69. * <pre>
  70. * &lt;init-param&gt;
  71. * &lt;param-name&gt;config&lt;/param-name&gt;
  72. * &lt;param-value&gt;/WEB-INF/OpenHandle.xml&lt;/param-value&gt;
  73. * &lt;/init-param&gt;
  74. * </pre>
  75. *
  76. * <p>
  77. * The path specified as a value must point to a resource obtainable via
  78. * {@link ServletContext#getResource(String)}.
  79. * </p>
  80. *
  81. * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
  82. */
  83. @Override
  84. public void init(ServletConfig config) throws ServletException {
  85. super.init(config);
  86. // start with a null configuration
  87. Configuration configuration = null;
  88. // has a custom config been specified?
  89. String customConfig = config.getInitParameter("config");
  90. if (isNotBlank(customConfig)) {
  91. try {
  92. configuration = new XMLConfiguration(getServletContext()
  93. .getResource(customConfig));
  94. } catch (Exception e) {
  95. LOG.error("Could not load custom configuration '"
  96. + customConfig
  97. + "'. Proceeding to load default configuration.", e);
  98. }
  99. }
  100. // load the default config
  101. try {
  102. configuration = new XMLConfiguration(OpenHandleServlet.class
  103. .getResource("/OpenHandle.xml"));
  104. } catch (Exception e) {
  105. throw new ServletException("Could not load default configuration",
  106. e);
  107. }
  108. try {
  109. // load settings
  110. settings = new Settings(configuration);
  111. // initialize resolver
  112. resolver = new OpenHandle(settings.getPreferredProtocols(),
  113. settings.isTraceMessages());
  114. } catch (SettingsException e) {
  115. throw new ServletException(e);
  116. }
  117. try {
  118. Properties properties = new Properties();
  119. properties.load(OpenHandleServlet.class
  120. .getResourceAsStream("/velocity.properties"));
  121. velocity = new VelocityEngine();
  122. velocity.setApplicationAttribute(ServletContext.class.getName(), getServletContext());
  123. velocity.init(properties);
  124. } catch (Exception e) {
  125. throw new ServletException("Could not initialize velocity engine",
  126. e);
  127. }
  128. }
  129. /**
  130. * <p>
  131. * </p>
  132. *
  133. * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
  134. * javax.servlet.http.HttpServletResponse)
  135. */
  136. @Override
  137. protected void doGet(HttpServletRequest request,
  138. HttpServletResponse response) throws ServletException, IOException {
  139. doPost(request, response);
  140. }
  141. /**
  142. * <p>
  143. * </p>
  144. *
  145. * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
  146. * javax.servlet.http.HttpServletResponse)
  147. */
  148. @Override
  149. protected void doPost(HttpServletRequest request,
  150. HttpServletResponse response) throws ServletException, IOException {
  151. RequestAdapter adapter = new RequestAdapter(request, settings);
  152. if (isBlank(adapter.getHandle())) {
  153. doErrorResponse(adapter, request, response,
  154. "No handle identifier specified",
  155. HttpServletResponse.SC_BAD_REQUEST,
  156. HttpServletResponse.SC_BAD_REQUEST);
  157. } else {
  158. doHandleResponse(adapter, request, response);
  159. }
  160. }
  161. /*
  162. * Method that gets delegated to to handle an error response
  163. */
  164. private void doErrorResponse(RequestAdapter adapter,
  165. HttpServletRequest request, HttpServletResponse response,
  166. String message, int httpStatus, int handleErrorCode)
  167. throws ServletException, IOException {
  168. Template template = adapter.getErrorResponseTemplate();
  169. response.setStatus(httpStatus);
  170. String override = request.getParameter("mimetype");
  171. if (isNotBlank(override) && Mimetype.forName(override) != null) {
  172. response.setContentType(Mimetype.forName(override).toString());
  173. } else {
  174. response.setContentType(template.getMimetype().toString());
  175. }
  176. request.setAttribute("error", new HandleExceptionAdapter(
  177. handleErrorCode, message));
  178. render(request, response, template);
  179. }
  180. /*
  181. * Method that gets delegated to to handle a handle response
  182. */
  183. private void doHandleResponse(RequestAdapter adapter,
  184. HttpServletRequest request, HttpServletResponse response)
  185. throws ServletException, IOException {
  186. try {
  187. HandleResponseAdapter handleData = resolver.get(
  188. adapter.getHandle(), adapter.getIndices(), adapter
  189. .getTypes());
  190. Template template = adapter.getHandleResponseTemplate();
  191. response.setStatus(HttpServletResponse.SC_OK);
  192. String override = request.getParameter("mimetype");
  193. if (isNotBlank(override) && Mimetype.forName(override) != null) {
  194. response.setContentType(Mimetype.forName(override).toString());
  195. } else {
  196. response.setContentType(template.getMimetype().toString());
  197. }
  198. request.setAttribute(settings.getHandleIdRequestParameterName(),
  199. handleData);
  200. render(request, response, template);
  201. } catch (HandleException e) {
  202. doErrorResponse(adapter, request, response, e.getMessage(),
  203. HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getCode());
  204. }
  205. }
  206. private void render(HttpServletRequest request,
  207. HttpServletResponse response, Template template)
  208. throws ServletException, IOException {
  209. try {
  210. Context context = new VelocityContext();
  211. context.put("request", request);
  212. context.put("dateTool", new DateTool());
  213. Writer writer = response.getWriter();
  214. velocity.getTemplate(template.toString()).merge(context, writer);
  215. } catch (Exception e) {
  216. throw new ServletException(e);
  217. }
  218. }
  219. }