Beispiel #1
0
 /** Close the session. This implies closing any open methods. */
 public synchronized void close() {
   if (this.closed) return; // multiple calls ok
   while (methodList.size() > 0) {
     HTTPMethod m = methodList.get(0);
     m.close(); // forcibly close; will invoke removemethod().
   }
   closed = true;
 }
Beispiel #2
0
 public static int putUrlAsString(String content, String url) throws HTTPException {
   HTTPSession session = new HTTPSession(url);
   HTTPMethod m = HTTPMethod.Put(session);
   m.setRequestContentAsString(content);
   int status = m.execute();
   m.close();
   return status;
 }
Beispiel #3
0
 static String getUrlAsString(String url) throws HTTPException {
   try (HTTPMethod m = HTTPFactory.Get(url); ) {
     int status = m.execute();
     String content = null;
     if (status == 200) {
       content = m.getResponseAsString();
     }
     return content;
   }
 }
Beispiel #4
0
 public static String getUrlAsString(String url) throws HTTPException {
   HTTPSession session = new HTTPSession(url);
   HTTPMethod m = HTTPMethod.Get(session);
   int status = m.execute();
   String content = null;
   if (status == 200) {
     content = m.getResponseAsString();
   }
   m.close();
   return content;
 }
Beispiel #5
0
 static int putUrlAsString(String content, String url) throws HTTPException {
   int status = 0;
   try {
     try (HTTPMethod m = HTTPFactory.Put(url)) {
       m.setRequestContent(
           new StringEntity(content, ContentType.create("application/text", "UTF-8")));
       status = m.execute();
     }
   } catch (UnsupportedCharsetException uce) {
     throw new HTTPException(uce);
   }
   return status;
 }
  /**
   * 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]);
      }
    }
  }
Beispiel #7
0
  public Either<IOException, HttpResponse> execUploadRequest(
      String path, List<FormBodyPart> parts, HTTPMethod method, String acceptType) {
    HttpEntityEnclosingRequestBase httpReq = null;
    String url = getUriForPath(path);
    if (method.equals(HTTPMethod.POST)) {
      httpReq = new HttpPost(url);
    } else if (method.equals(HTTPMethod.PUT)) {
      httpReq = new HttpPut(url);
    } else {
      throw new IllegalArgumentException("gotta be this or that: post or put");
    }
    MultipartEntity entity = new MultipartEntity();
    for (FormBodyPart part : parts) {
      entity.addPart(part);
    }
    httpReq.setEntity(entity);

    return execRequest(httpReq, acceptType);
  }
Beispiel #8
0
  public Either<IOException, HttpResponse> execNormalRequest(
      String path, Map<String, String> params, HTTPMethod method, String acceptType) {
    String url = getUriForPath(path);
    if (params == null) {
      params = new HashMap<String, String>();
    }
    HttpUriRequest httpReq = null;
    if (method.equals(HTTPMethod.GET)) {
      HttpGet get = new HttpGet(url);
      for (Map.Entry<String, String> param : params.entrySet()) {
        get.getParams().setParameter(param.getKey(), param.getValue());
      }
      httpReq = get;
    } else {
      HttpEntityEnclosingRequestBase postOrPut = null;
      if (method.equals(HTTPMethod.PUT)) {
        postOrPut = new HttpPut(url);
      } else {
        postOrPut = new HttpPost(url);
      }
      MultipartEntity entity = new MultipartEntity();

      List<NameValuePair> args = new ArrayList<NameValuePair>();
      for (Map.Entry<String, String> param : params.entrySet()) {
        args.add(new BasicNameValuePair(param.getKey(), param.getValue()));
      }
      try {
        postOrPut.setEntity(new UrlEncodedFormEntity(args));
      } catch (UnsupportedEncodingException e) {
        return new Left<IOException, HttpResponse>(e);
      }
      httpReq = postOrPut;
    }

    return execRequest(httpReq, acceptType);
  }
 @Test
 public void testDefaultMethods() {
   List<String> methods =
       Arrays.asList(
           "connect", "DELEte", "geT", "HEAD", "OpTiOnS", "patch", "post", "pURGe", "put",
           "Trace");
   Set<HTTPMethod> actual = new LinkedHashSet<HTTPMethod>();
   for (String method : methods) {
     actual.add(HTTPMethod.valueOf(method));
   }
   Assert.assertEquals(defaultMethods.size(), actual.size());
   ArrayList<HTTPMethod> expected = new ArrayList<>(defaultMethods.values());
   Collections.sort(expected);
   Iterator<HTTPMethod> defaultIterator = expected.iterator();
   Iterator<HTTPMethod> actualIterator = actual.iterator();
   while (actualIterator.hasNext()) {
     HTTPMethod m = defaultIterator.next();
     HTTPMethod am = actualIterator.next();
     Assert.assertSame(m, am);
   }
 }
Beispiel #10
0
    @Override
    public HTTPResponse call() throws Exception {
      final HttpURLConnection hc = (HttpURLConnection) uri.toURL().openConnection();
      try {
        hc.setDoOutput(true);
        hc.setRequestMethod(method.name());
        hc.setRequestProperty(MimeTypes.CONTENT_TYPE, MimeTypes.APP_XML);
        hc.getOutputStream().write(content);
        hc.getOutputStream().close();

        hc.setReadTimeout(SOCKET_TIMEOUT);
        while (!stop) {
          try {
            return new HTTPResponse(hc.getResponseCode());
          } catch (final SocketTimeoutException e) {
          }
        }
        return null;
      } finally {
        hc.disconnect();
      }
    }
 @Test(expected = IllegalArgumentException.class)
 public void testEmpty() {
   HTTPMethod.valueOf("");
   HTTPMethod.valueOf(" ");
 }
 @Test(expected = IllegalArgumentException.class)
 public void testNull() {
   HTTPMethod.valueOf(null);
 }
 @Test
 public void testUnknown() {
   Assert.assertFalse(defaultMethods.containsValue(HTTPMethod.valueOf("UNKNOWN")));
 }
Beispiel #14
0
  /**
   * Checks a function for RESTFful annotations.
   *
   * @return {@code true} if module contains relevant annotations
   * @throws QueryException query exception
   */
  boolean analyze() throws QueryException {
    // parse all annotations
    final EnumSet<HTTPMethod> mth = EnumSet.noneOf(HTTPMethod.class);
    final boolean[] declared = new boolean[function.args.length];
    boolean found = false;
    final int as = function.ann.size();
    for (int a = 0; a < as; a++) {
      final QNm name = function.ann.names[a];
      final Value value = function.ann.values[a];
      final byte[] local = name.local();
      final byte[] uri = name.uri();
      final boolean rexq = eq(uri, QueryText.RESTXQURI);
      if (rexq) {
        if (eq(PATH, local)) {
          // annotation "path"
          if (path != null) error(ANN_TWICE, "%", name.string());
          path = new RestXqPath(toString(value, name));
          for (final String s : path) {
            if (s.trim().startsWith("{")) checkVariable(s, AtomType.AAT, declared);
          }
        } else if (eq(CONSUMES, local)) {
          // annotation "consumes"
          strings(value, name, consumes);
        } else if (eq(PRODUCES, local)) {
          // annotation "produces"
          strings(value, name, produces);
        } else if (eq(QUERY_PARAM, local)) {
          // annotation "query-param"
          queryParams.add(param(value, name, declared));
        } else if (eq(FORM_PARAM, local)) {
          // annotation "form-param"
          formParams.add(param(value, name, declared));
        } else if (eq(HEADER_PARAM, local)) {
          // annotation "header-param"
          headerParams.add(param(value, name, declared));
        } else if (eq(COOKIE_PARAM, local)) {
          // annotation "cookie-param"
          cookieParams.add(param(value, name, declared));
        } else {
          // method annotations
          final HTTPMethod m = HTTPMethod.get(string(local));
          if (m == null) error(ANN_UNKNOWN, "%", name.string());
          if (!value.isEmpty()) {
            // remember post/put variable
            if (requestBody != null) error(ANN_TWICE, "%", name.string());
            if (m != POST && m != PUT) error(METHOD_VALUE, m);
            requestBody = checkVariable(toString(value, name), declared);
          }
          if (mth.contains(m)) error(ANN_TWICE, "%", name.string());
          mth.add(m);
        }
      } else if (eq(uri, QueryText.OUTPUTURI)) {
        // serialization parameters
        final String key = string(local);
        final String val = toString(value, name);
        if (output.get(key) == null) error(UNKNOWN_SER, key);
        output.set(key, val);
      }
      found |= rexq;
    }
    if (!mth.isEmpty()) methods = mth;

    if (found) {
      if (path == null) error(ANN_MISSING, PATH);
      for (int i = 0; i < declared.length; i++)
        if (!declared[i]) error(VAR_UNDEFINED, function.args[i].name.string());
    }
    return found;
  }