@SuppressWarnings("unchecked")
 Request populate(Request toPopulate) {
   for (Map.Entry<String, String> header : headers.entrySet()) {
     toPopulate.addHeader(header.getKey(), header.getValue());
   }
   if (content == null) return toPopulate;
   if (contentClass.equals(byte[].class)) {
     toPopulate.bodyByteArray((byte[]) content);
   } else if (contentClass.equals(String.class)) {
     toPopulate.bodyString((String) content, contentType);
   } else if (Map.class.isAssignableFrom(contentClass)) {
     List<NameValuePair> formContent = Lists.newArrayList();
     for (Map.Entry<String, String> val : ((Map<String, String>) content).entrySet()) {
       formContent.add(new BasicNameValuePair(val.getKey(), val.getValue()));
     }
     toPopulate.bodyForm(formContent);
   } else if (contentClass.equals(File.class)) {
     toPopulate.bodyFile((File) content, contentType);
   } else if (InputStream.class.isAssignableFrom(contentClass)) {
     toPopulate.bodyStream((InputStream) content);
   } else {
     throw new IllegalArgumentException(
         String.format(
             "Unknown content class %s. Only byte[], String, Map, File and InputStream are accepted",
             contentClass));
   }
   return toPopulate;
 }
示例#2
0
  /**
   * Create and POST a request to the Watson service
   *
   * @param req the Http Servlet request
   * @param resp the Http Servlet response
   * @throws ServletException the servlet exception
   * @throws IOException Signals that an I/O exception has occurred.
   */
  @Override
  protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
      throws ServletException, IOException {

    req.setCharacterEncoding("UTF-8");
    try {
      String reqURI = req.getRequestURI();
      String endpoint = reqURI.substring(reqURI.lastIndexOf('/') + 1);
      String url = baseURL + "/v1/" + endpoint;
      // concatenate query params
      String queryStr = req.getQueryString();
      if (queryStr != null) {
        url += "?" + queryStr;
      }
      URI uri = new URI(url).normalize();
      logger.info("posting to " + url);

      Request newReq = Request.Post(uri);
      newReq.addHeader("Accept", "application/json");

      String metadata = req.getHeader("x-watson-metadata");
      if (metadata != null) {
        metadata += "client-ip:" + req.getRemoteAddr();
        newReq.addHeader("x-watson-metadata", metadata);
      }

      InputStreamEntity entity = new InputStreamEntity(req.getInputStream());
      newReq.bodyString(EntityUtils.toString(entity, "UTF-8"), ContentType.APPLICATION_JSON);

      Executor executor = this.buildExecutor(uri);
      Response response = executor.execute(newReq);
      HttpResponse httpResponse = response.returnResponse();
      resp.setStatus(httpResponse.getStatusLine().getStatusCode());

      ServletOutputStream servletOutputStream = resp.getOutputStream();
      httpResponse.getEntity().writeTo(servletOutputStream);
      servletOutputStream.flush();
      servletOutputStream.close();

      logger.info("post done");
    } catch (Exception e) {
      // Log something and return an error message
      logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
      resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
    }
  }
示例#3
0
  /**
   * @param <T>
   * @param responseType a descendant of CkanResponse
   * @param path something like 1/api/3/action/package_create
   * @param body the body of the POST
   * @param the content type, i.e.
   * @param params list of key, value parameters. They must be not be url encoded. i.e.
   *     "id","laghi-monitorati-trento"
   * @throws JackanException on error
   */
  <T extends CkanResponse> T postHttp(
      Class<T> responseType, String path, String body, ContentType contentType, Object... params) {
    checkNotNull(responseType);
    checkNotNull(path);
    checkNotNull(body);
    checkNotNull(contentType);

    String fullUrl = calcFullUrl(path, params);

    try {

      logger.log(Level.FINE, "posting to url {0}", fullUrl);
      Request request = Request.Post(fullUrl);
      if (proxy != null) {
        request.viaProxy(proxy);
      }
      Response response =
          request.bodyString(body, contentType).addHeader("Authorization", ckanToken).execute();

      Content out = response.returnContent();
      String json = out.asString();

      T dr = getObjectMapper().readValue(json, responseType);
      if (!dr.success) {
        // monkey patching error type
        throw new JackanException(
            "posting to catalog "
                + catalogURL
                + " was not successful. Reason: "
                + CkanError.read(getObjectMapper().readTree(json).get("error").asText()));
      }
      return dr;
    } catch (Exception ex) {
      throw new JackanException("Error while performing a POST! Request url is:" + fullUrl, ex);
    }
  }