/**
  * Returns an array with all accepted content types. if the root directory was specified.
  *
  * @return database
  */
 public String[] produces() {
   final String[] acc = req.getHeader("Accept").split("\\s*,\\s*");
   for (int a = 0; a < acc.length; a++) {
     if (acc[a].indexOf(';') != -1) acc[a] = acc[a].replaceAll("\\w*;.*", "");
   }
   return acc;
 }
Example #2
0
  @Override
  public final void service(final HttpServletRequest req, final HttpServletResponse res)
      throws IOException {

    final HTTPContext http = new HTTPContext(req, res, this);
    final boolean restxq = this instanceof RestXqServlet;
    try {
      http.authorize();
      run(http);
      http.log(SC_OK, "");
    } catch (final HTTPException ex) {
      http.status(ex.getStatus(), Util.message(ex), restxq);
    } catch (final LoginException ex) {
      http.status(SC_UNAUTHORIZED, Util.message(ex), restxq);
    } catch (final IOException | QueryException ex) {
      http.status(SC_BAD_REQUEST, Util.message(ex), restxq);
    } catch (final ProcException ex) {
      http.status(SC_BAD_REQUEST, Text.INTERRUPTED, restxq);
    } catch (final Exception ex) {
      final String msg = Util.bug(ex);
      Util.errln(msg);
      http.status(SC_INTERNAL_SERVER_ERROR, Util.info(UNEXPECTED, msg), restxq);
    } finally {
      if (Prop.debug) {
        Util.outln("_ REQUEST _________________________________" + Prop.NL + req);
        final Enumeration<String> en = req.getHeaderNames();
        while (en.hasMoreElements()) {
          final String key = en.nextElement();
          Util.outln(Text.LI + key + Text.COLS + req.getHeader(key));
        }
        Util.out("_ RESPONSE ________________________________" + Prop.NL + res);
      }
    }
  }
  /**
   * Constructor.
   *
   * @param rq request
   * @param rs response
   * @throws IOException I/O exception
   */
  public HTTPContext(final HttpServletRequest rq, final HttpServletResponse rs) throws IOException {

    req = rq;
    res = rs;
    final String m = rq.getMethod();
    method = HTTPMethod.get(m);

    final StringBuilder uri = new StringBuilder(req.getRequestURL());
    final String qs = req.getQueryString();
    if (qs != null) uri.append('?').append(qs);
    log(false, m, uri);

    // set UTF8 as default encoding (can be overwritten)
    res.setCharacterEncoding(UTF8);

    segments = toSegments(req.getPathInfo());
    path = join(0);

    user = System.getProperty(DBUSER);
    pass = System.getProperty(DBPASS);

    // set session-specific credentials
    final String auth = req.getHeader(AUTHORIZATION);
    if (auth != null) {
      final String[] values = auth.split(" ");
      if (values[0].equals(BASIC)) {
        final String[] cred = Base64.decode(values[1]).split(":", 2);
        if (cred.length != 2) throw new LoginException(NOPASSWD);
        user = cred[0];
        pass = cred[1];
      } else {
        throw new LoginException(WHICHAUTH, values[0]);
      }
    }
  }
Example #4
0
 @Override
 public void parseRequestParameters(
     final Map<String, String> params, final Map<String, com.bradmcevoy.http.FileItem> files)
     throws RequestParseException {
   try {
     if (isMultiPart()) {
       parseQueryString(params, req.getQueryString());
       @SuppressWarnings("unchecked")
       final List<FileItem> items = new ServletFileUpload().parseRequest(req);
       for (final FileItem item : items) {
         if (item.isFormField()) params.put(item.getFieldName(), item.getString());
         else files.put(item.getFieldName(), new FileItemWrapper(item));
       }
     } else {
       final Enumeration<String> en = req.getParameterNames();
       while (en.hasMoreElements()) {
         final String nm = en.nextElement();
         final String val = req.getParameter(nm);
         params.put(nm, val);
       }
     }
   } catch (final FileUploadException ex) {
     throw new RequestParseException("FileUploadException", ex);
   } catch (final Throwable ex) {
     throw new RequestParseException(ex.getMessage(), ex);
   }
 }
 /**
  * Returns a string with the remote user address.
  *
  * @return user address
  */
 private String remote() {
   return new StringBuilder()
       .append('[')
       .append(req.getRemoteAddr())
       .append(':')
       .append(req.getRemotePort())
       .append(']')
       .toString();
 }
Example #6
0
 @Override
 public Map<String, String> getHeaders() {
   final Map<String, String> map = new HashMap<>();
   final Enumeration<String> en = req.getHeaderNames();
   while (en.hasMoreElements()) {
     final String name = en.nextElement();
     final String val = req.getHeader(name);
     map.put(name, val);
   }
   return map;
 }
Example #7
0
 @Override
 public Cookie getCookie(final String name) {
   for (final javax.servlet.http.Cookie c : req.getCookies()) {
     if (c.getName().equals(name)) return new BXServletCookie(c);
   }
   return null;
 }
Example #8
0
  /**
   * Returns an array with all accepted content types. if the root directory was specified.
   *
   * @return database
   */
  public String[] produces() {
    final String accept = req.getHeader("Accept");
    if (accept == null) return new String[0];

    final String[] acc = accept.split("\\s*,\\s*");
    final int as = acc.length;
    for (int a = 0; a < as; a++) {
      if (acc[a].indexOf(';') != -1) acc[a] = acc[a].replaceAll("\\w*;.*", "");
    }
    return acc;
  }
 /**
  * Returns all query parameters.
  *
  * @return parameters
  */
 public Map<String, String[]> params() {
   final Map<String, String[]> params = new HashMap<String, String[]>();
   final Map<?, ?> map = req.getParameterMap();
   for (final Entry<?, ?> s : map.entrySet()) {
     final String key = s.getKey().toString();
     final String[] vals =
         s.getValue() instanceof String[]
             ? (String[]) s.getValue()
             : new String[] {s.getValue().toString()};
     params.put(key, vals);
   }
   return params;
 }
Example #10
0
  /**
   * Constructor.
   *
   * @param rq request
   * @param rs response
   * @param servlet calling servlet instance
   * @throws IOException I/O exception
   */
  public HTTPContext(
      final HttpServletRequest rq, final HttpServletResponse rs, final BaseXServlet servlet)
      throws IOException {

    req = rq;
    res = rs;
    params = new HTTPParams(this);

    method = rq.getMethod();

    final StringBuilder uri = new StringBuilder(req.getRequestURL());
    final String qs = req.getQueryString();
    if (qs != null) uri.append('?').append(qs);
    log('[' + method + "] " + uri, null);

    // set UTF8 as default encoding (can be overwritten)
    res.setCharacterEncoding(UTF8);
    segments = decode(toSegments(req.getPathInfo()));

    // adopt servlet-specific credentials or use global ones
    final GlobalOptions mprop = context().globalopts;
    user = servlet.user != null ? servlet.user : mprop.get(GlobalOptions.USER);
    pass = servlet.pass != null ? servlet.pass : mprop.get(GlobalOptions.PASSWORD);

    // overwrite credentials with session-specific data
    final String auth = req.getHeader(AUTHORIZATION);
    if (auth != null) {
      final String[] values = auth.split(" ");
      if (values[0].equals(BASIC)) {
        final String[] cred = org.basex.util.Base64.decode(values[1]).split(":", 2);
        if (cred.length != 2) throw new LoginException(NOPASSWD);
        user = cred[0];
        pass = cred[1];
      } else {
        throw new LoginException(WHICHAUTH, values[0]);
      }
    }
  }
Example #11
0
  /**
   * Authenticate the user and returns a new client {@link Context} instance.
   *
   * @return client context
   * @throws LoginException login exception
   */
  public Context authenticate() throws LoginException {
    final byte[] address = token(req.getRemoteAddr());
    try {
      if (user == null || user.isEmpty() || pass == null || pass.isEmpty())
        throw new LoginException(NOPASSWD);
      final Context ctx = new Context(context(), null);
      ctx.user = ctx.users.get(user);
      if (ctx.user == null || !ctx.user.password.equals(md5(pass))) throw new LoginException();

      context.blocker.remove(address);
      return ctx;
    } catch (final LoginException ex) {
      // delay users with wrong passwords
      for (int d = context.blocker.delay(address); d > 0; d--) Performance.sleep(100);
      throw ex;
    }
  }
 /**
  * Returns the content type of a request (without an optional encoding).
  *
  * @return content type
  */
 public String contentType() {
   final String ct = req.getContentType();
   return ct != null ? ct.replaceFirst(";.*", "") : null;
 }
Example #13
0
 /**
  * Returns a string with the remote user address.
  *
  * @return user address
  */
 private String address() {
   return req.getRemoteAddr() + ':' + req.getRemotePort();
 }
Example #14
0
 @Override
 public String getRemoteAddr() {
   return req.getRemoteAddr();
 }
Example #15
0
 @Override
 public String getRequestHeader(final Header header) {
   return req.getHeader(header.code);
 }
Example #16
0
 @Override
 public String getFromAddress() {
   return req.getRemoteHost();
 }
Example #17
0
 /**
  * Constructor.
  *
  * @param r HTTP servlet request
  */
 BXServletRequest(final HttpServletRequest r) {
   req = r;
   method = Method.valueOf(r.getMethod());
   url = r.getRequestURL().toString(); // MiltonUtils.stripContext(r);
   REQUEST.set(r);
 }
Example #18
0
 /**
  * Request content type.
  *
  * @return the content type of the current request
  */
 private ContentType getRequestContentType() {
   final String s = req.getContentType();
   if (s == null) return null;
   if (s.contains(Response.MULTIPART)) return ContentType.MULTIPART;
   return TYPE_CONTENTS.get(s);
 }
Example #19
0
 @Override
 public InputStream getInputStream() throws IOException {
   return req.getInputStream();
 }
Example #20
0
 @Override
 public List<Cookie> getCookies() {
   final List<Cookie> list = new ArrayList<>();
   for (final javax.servlet.http.Cookie c : req.getCookies()) list.add(new BXServletCookie(c));
   return list;
 }