protected String retrieveServerResponse(String text) {
    Request req = Request.Post(getTagMeServiceUrl().toString());

    req.addHeader("Content-Type", "application/x-www-form-urlencoded");
    req.bodyForm(
        Form.form()
            .add("text", text)
            .add("gcube-token", getApiKey())
            .add("lang", getLanguageCode())
            .add("tweet", getIsTweet().toString())
            .add("include_abstract", "false")
            .add("include_categories", "false")
            .add("include_all_spots", "false")
            .add("long_text", "0")
            .add("epsilon", getEpsilon().toString())
            .build(),
        Consts.UTF_8);
    logger.debug("Request is " + req);
    Response res = null;
    try {
      res = req.execute();
    } catch (Exception ex) {
      throw new GateRuntimeException("Problem executing HTTP request: " + req, ex);
    }
    Content cont = null;
    try {
      cont = res.returnContent();
    } catch (Exception ex) {
      throw new GateRuntimeException("Problem getting HTTP response content: " + res, ex);
    }
    String ret = cont.asString();
    logger.debug("TagMe server response " + ret);
    return ret;
  }
예제 #2
0
 private String loginWith(String username, String password) throws IOException {
   return Request.Post("http://localhost:8080/session")
       .bodyForm(Form.form().add("username", username).add("password", password).build())
       .execute()
       .returnContent()
       .asString();
 }
예제 #3
0
 @When("^\"([^\"]*)\" upload a content without content type$")
 public void userUploadContentWithoutContentType(String username) throws Throwable {
   AccessToken accessToken = userStepdefs.tokenByUser.get(username);
   Request request = Request.Post(uploadUri).bodyByteArray("some text".getBytes(Charsets.UTF_8));
   if (accessToken != null) {
     request.addHeader("Authorization", accessToken.serialize());
   }
   response = request.execute().returnResponse();
 }
예제 #4
0
 @When("^\"([^\"]*)\" upload a too big content$")
 public void userUploadTooBigContent(String username) throws Throwable {
   AccessToken accessToken = userStepdefs.tokenByUser.get(username);
   Request request =
       Request.Post(uploadUri)
           .bodyStream(
               new BufferedInputStream(new ZeroedInputStream(_10M), _10M),
               org.apache.http.entity.ContentType.DEFAULT_BINARY);
   if (accessToken != null) {
     request.addHeader("Authorization", accessToken.serialize());
   }
   response = request.execute().returnResponse();
 }
예제 #5
0
 @When("^\"([^\"]*)\" upload a content$")
 public void userUploadContent(String username) throws Throwable {
   AccessToken accessToken = userStepdefs.tokenByUser.get(username);
   Request request =
       Request.Post(uploadUri)
           .bodyStream(
               new BufferedInputStream(new ZeroedInputStream(_1M), _1M),
               org.apache.http.entity.ContentType.DEFAULT_BINARY);
   if (accessToken != null) {
     request.addHeader("Authorization", accessToken.serialize());
   }
   response =
       Executor.newInstance(HttpClientBuilder.create().disableAutomaticRetries().build())
           .execute(request)
           .returnResponse();
 }
예제 #6
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);
    }
  }
예제 #7
0
 public Object set4(String name, Object value, Boolean unset, Boolean sync)
     throws ClientProtocolException, IOException {
   Form form =
       Form.form().add("name", name).add("sync", sync.toString()).add("session", this.session);
   if (!unset) {
     form.add("value", mapper.writeValueAsString(value));
   }
   String reply =
       Request.Post(urlBase + "/set")
           .addHeader("Authorization", auth)
           .bodyForm(form.build())
           .execute()
           .returnContent()
           .asString();
   if (!reply.equals("ok")) {
     throw new RuntimeException(reply);
   }
   return value;
 }
예제 #8
0
  private void createMetadataAndTestData(String aggregationsMetadata) throws Exception {
    // get the collection etag

    String etag = getEtag(collectionTmpUri);

    // post some data
    String[] data =
        new String[] {
          "{\"name\":\"a\",\"age\":10}",
          "{\"name\":\"a\",\"age\":20}",
          "{\"name\":\"a\",\"age\":30}",
          "{\"name\":\"b\",\"age\":40}",
          "{\"name\":\"b\",\"age\":50}",
          "{\"name\":\"b\",\"age\":60}",
          "{\"obj\":{\"name\":\"x\",\"age\":10}}",
          "{\"obj\":{\"name\":\"x\",\"age\":20}}",
          "{\"obj\":{\"name\":\"y\",\"age\":10}}",
          "{\"obj\":{\"name\":\"y\",\"age\":20}}"
        };

    for (String datum : data) {
      Response resp =
          adminExecutor.execute(
              Request.Post(collectionTmpUri)
                  .bodyString(datum, halCT)
                  .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));

      check("check aggregation create test data", resp, HttpStatus.SC_CREATED);
    }

    Response resp =
        adminExecutor.execute(
            Request.Patch(collectionTmpUri)
                .bodyString(aggregationsMetadata, halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)
                .addHeader(Headers.IF_MATCH_STRING, etag));

    check("check update collection with aggregations metadata", resp, HttpStatus.SC_OK);
  }
예제 #9
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);
    }
  }
  @Test
  public void variableTest() throws Exception {
    String content = Request.Post(serverUrl() + "?one=three").execute().returnContent().asString();

    assertThat(content, is("Hello three!"));
  }
예제 #11
0
 public String postFile(String uri, String file) throws IOException {
   InputStream is = Resources.getResource(file).openStream();
   Content content = Request.Post(uri).bodyByteArray(toByteArray(is)).execute().returnContent();
   return content.asString();
 }
예제 #12
0
 public String postBytes(String uri, byte[] bytes) throws IOException {
   Content content = Request.Post(uri).bodyByteArray(bytes).execute().returnContent();
   return content.asString();
 }