+ /**
+ * Initialise methods
+ *
+ * @throws BindException
+ */
+ protected void init() throws BindException
+ {
+ init(MY_PATH);
+ }
+
+ protected void init(String path) throws BindException
+ {
+ setPath(path);
+ // Override this in extended class
+ // e.g. registerHandler and addEndpoints
+ }
+
+ protected boolean addEndpoint(EndpointI ep)
+ {
+ if (endpoints == null)
+ {
+ endpoints = new HashMap<>();
+ }
+ AbstractEndpoint e = (AbstractEndpoint) ep;
+ endpoints.put(ep.getPath(), ep);
+ return true;
+ }
+
+ protected String getRequestedEndpointName(HttpServletRequest request)
+ {
+ String pathInfo = request.getPathInfo();
+ int slashpos = pathInfo.indexOf('/', 1);
+ return slashpos > 1 ? pathInfo.substring(1, slashpos)
+ : pathInfo.substring(1);
+ }
+
+ protected String[] getEndpointPathParameters(HttpServletRequest request)
+ {
+ String pathInfo = request.getPathInfo();
+ int slashpos = pathInfo.indexOf('/', 1);
+ return slashpos < 1 ? null
+ : pathInfo.substring(slashpos + 1).split("/");
+ }
+
+ protected void returnError(HttpServletRequest request,
+ HttpServletResponse response, String message)
+ {
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ String endpointName = getRequestedEndpointName(request);
+ Console.error(getName() + " error: endpoint " + endpointName
+ + " failed: '" + message + "'");
+ try
+ {
+ PrintWriter writer = response.getWriter();
+ writer.write("Endpoint " + endpointName + ": " + message);
+ } catch (IOException e)
+ {
+ Console.debug("Could not write to REST response for endpoint "
+ + endpointName, e);
+ }
+ }
+
+ protected void returnStatus(HttpServletResponse response, String id,
+ Status status)
+ {
+ try
+ {
+ PrintWriter writer = response.getWriter();
+ if (id != null)
+ writer.write("id=" + id + "\n");
+ if (status != null)
+ writer.write("status=" + status.toString() + "\n");
+ } catch (IOException e)
+ {
+ Console.debug("Could not write status to REST response for id:" + id,
+ e);
+ }
+ }
+
+ protected String getRequestBody(HttpServletRequest request)
+ throws IOException
+ {
+ StringBuilder sb = new StringBuilder();
+ BufferedReader reader = request.getReader();
+ try
+ {
+ String line;
+ while ((line = reader.readLine()) != null)
+ {
+ sb.append(line).append('\n');
+ }
+ } finally
+ {
+ reader.close();
+ }
+ return sb.toString();
+ }
+
+}
\ No newline at end of file