@Test
  public void test() throws Throwable {

    Response response = Request.Get("http://localhost:8080/test.json").execute();
    System.out.println(response.returnContent().asString());

    response = Request.Get("http://localhost:8080/test.html").execute();
    System.out.println(response.returnContent().asString());
  }
  public BpPagedResults<BpClass> findAllClassesInOntology(
      String ontology, int page, int pageSize, String apiKey) throws HTTPException, IOException {
    String url =
        BP_API_BASE
            + BP_ONTOLOGIES
            + ontology
            + "/"
            + BP_CLASSES
            + "?include=prefLabel,hasChildren,created,synonym,definition"
            + "&page="
            + page
            + "&pagesize="
            + pageSize;

    HttpResponse response =
        HttpUtil.makeHttpRequest(
            Request.Get(url)
                .addHeader("Authorization", Util.getBioPortalAuthHeader(apiKey))
                .connectTimeout(connectTimeout)
                .socketTimeout(socketTimeout));

    int statusCode = response.getStatusLine().getStatusCode();
    // The classes were successfully retrieved
    if (statusCode == 200) {
      ObjectMapper mapper = new ObjectMapper();
      JsonNode bpResult =
          mapper.readTree(new String(EntityUtils.toByteArray(response.getEntity())));
      return mapper.readValue(
          mapper.treeAsTokens(bpResult), new TypeReference<BpPagedResults<BpClass>>() {});
    } else {
      throw new HTTPException(statusCode);
    }
  }
  public BpClass find(String id, String ontology, String apiKey) throws HTTPException, IOException {
    String url =
        BP_API_BASE
            + BP_ONTOLOGIES
            + ontology
            + "/"
            + BP_CLASSES
            + id
            + "?include=prefLabel,hasChildren,created,synonym,definition";

    HttpResponse response =
        HttpUtil.makeHttpRequest(
            Request.Get(url)
                .addHeader("Authorization", Util.getBioPortalAuthHeader(apiKey))
                .connectTimeout(connectTimeout)
                .socketTimeout(socketTimeout));

    int statusCode = response.getStatusLine().getStatusCode();
    // The class was successfully retrieved
    if (statusCode == 200) {
      ObjectMapper mapper = new ObjectMapper();
      JsonNode bpResult =
          mapper.readTree(new String(EntityUtils.toByteArray(response.getEntity())));
      return mapper.convertValue(bpResult, BpClass.class);
    } else {
      throw new HTTPException(statusCode);
    }
  }
  public List<BpTreeNode> getTree(String id, String ontology, String apiKey) throws IOException {
    String url = BP_API_BASE + BP_ONTOLOGIES + ontology + "/" + BP_CLASSES + id + "/tree";

    HttpResponse response =
        HttpUtil.makeHttpRequest(
            Request.Get(url)
                .addHeader("Authorization", Util.getBioPortalAuthHeader(apiKey))
                .connectTimeout(connectTimeout)
                .socketTimeout(socketTimeout));

    int statusCode = response.getStatusLine().getStatusCode();
    // The tree was successfully retrieved
    if (statusCode == 200) {
      ObjectMapper mapper = new ObjectMapper();
      JsonNode bpResult =
          mapper.readTree(new String(EntityUtils.toByteArray(response.getEntity())));
      List<BpTreeNode> nodes = new ArrayList<>();
      for (JsonNode n : bpResult) {
        nodes.add(mapper.convertValue(n, BpTreeNode.class));
      }
      return nodes;
    } else {
      throw new HTTPException(statusCode);
    }
  }
  private static void sendRequest() {

    // Address API (GET )

    try {

      // Create request
      Content content =
          Request.Get(
                  "http://api.matchbox.io/address?addr_1=1600%20Pennsylvania%20Ave&city_state_zip=Washington%20DC%2020500")

              // Add headers
              .addHeader(
                  "Cookie",
                  "connect.sid=s%3Apxju73iJEdw8pbqqc9IYk8_HWt3owKfS.fmbhZBZR2ktoIKlAW5GHJPUYH2dMd3tb3KjzOPcRkqA")
              .addHeader("apikey", "YOUR-API-KEY")

              // Fetch request and return content
              .execute()
              .returnContent();

      // Print content
      System.out.println(content);
    } catch (IOException e) {
      System.out.println(e);
    }
  }
  public List<BpClass> getParents(String id, String ontology, String apiKey) throws IOException {
    String url =
        BP_API_BASE
            + BP_ONTOLOGIES
            + ontology
            + "/"
            + BP_CLASSES
            + id
            + "/parents"
            + "?include=prefLabel,hasChildren,created,synonym,definition";

    HttpResponse response =
        HttpUtil.makeHttpRequest(
            Request.Get(url)
                .addHeader("Authorization", Util.getBioPortalAuthHeader(apiKey))
                .connectTimeout(connectTimeout)
                .socketTimeout(socketTimeout));

    int statusCode = response.getStatusLine().getStatusCode();
    // Success
    if (statusCode == 200) {
      ObjectMapper mapper = new ObjectMapper();
      JsonNode bpResult =
          mapper.readTree(new String(EntityUtils.toByteArray(response.getEntity())));
      List<BpClass> children = new ArrayList<>();
      for (JsonNode n : bpResult) {
        children.add(mapper.convertValue(n, BpClass.class));
      }
      return children;
    } else {
      throw new HTTPException(statusCode);
    }
  }
Esempio n. 7
0
 public static String getByFluent(String uri) throws ClientProtocolException, IOException {
   Request req = Request.Get(uri);
   req.addHeader("User-Agent", "curl");
   Response res = req.execute();
   String back = res.returnContent().asString();
   return back;
 }
  public BpPagedResults<BpClass> findValueSetsByValueSetCollection(
      String vsCollection, int page, int pageSize, String apiKey) throws IOException {
    String url =
        BP_API_BASE
            + BP_SEARCH
            + "?also_search_provisional=true&valueset_roots_only=true&ontology_types=VALUE_SET_COLLECTION&ontologies="
            + vsCollection
            + "&page="
            + page
            + "&pagesize="
            + pageSize;

    HttpResponse response =
        HttpUtil.makeHttpRequest(
            Request.Get(url)
                .addHeader("Authorization", Util.getBioPortalAuthHeader(apiKey))
                .connectTimeout(connectTimeout)
                .socketTimeout(socketTimeout));

    int statusCode = response.getStatusLine().getStatusCode();
    // Success
    if (statusCode == 200) {
      ObjectMapper mapper = new ObjectMapper();
      JsonNode bpResult =
          mapper.readTree(new String(EntityUtils.toByteArray(response.getEntity())));
      return mapper.readValue(
          mapper.treeAsTokens(bpResult), new TypeReference<BpPagedResults<BpClass>>() {});
    } else {
      throw new HTTPException(statusCode);
    }
  }
Esempio n. 9
0
  /**
   * Method for http GET
   *
   * @param <T>
   * @param responseType a descendant of CkanResponse
   * @param path something like /api/3/package_show
   * @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 getHttp(Class<T> responseType, String path, Object... params) {
    checkNotNull(responseType);
    checkNotNull(path);

    String fullUrl = calcFullUrl(path, params);

    try {
      logger.log(Level.FINE, "getting {0}", fullUrl);
      Request request = Request.Get(fullUrl);
      if (ckanToken != null) {
        request.addHeader("Authorization", ckanToken);
      }
      if (proxy != null) {
        request.viaProxy(proxy);
      }
      String json = request.execute().returnContent().asString();
      T dr = getObjectMapper().readValue(json, responseType);
      if (!dr.success) {
        // monkey patching error type
        throw new JackanException(
            "Reading from 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 GET. Request url was: " + fullUrl, ex);
    }
  }
 private void whenThePracticeStatusQueueServiceIsCalled() throws IOException {
   String url = StringUtils.replace(STATUS_URL, "{practiceId}", "1");
   url = StringUtils.replace(url, "{username}", username);
   yatspec.log("STATUS_URL", url);
   Response response = Request.Get(url).connectTimeout(1000).socketTimeout(1000).execute();
   httpResponse = response.returnResponse();
   responseContent = EntityUtils.toString(httpResponse.getEntity());
 }
Esempio n. 11
0
 @Then("^\"([^\"]*)\" should be able to retrieve the content$")
 public void contentShouldBeRetrievable(String username) throws Exception {
   AccessToken accessToken = userStepdefs.tokenByUser.get(username);
   Request request =
       Request.Get(mainStepdefs.baseUri().setPath("/download/" + _1M_ZEROED_FILE_BLOB_ID).build());
   if (accessToken != null) {
     request.addHeader("Authorization", accessToken.serialize());
   }
   response = request.execute().returnResponse();
   httpAuthorizedStatus();
 }
Esempio n. 12
0
 /** Query the beaker server to get an available port. */
 protected int getPortFromCore() throws IOException {
   String password = System.getenv("beaker_core_password");
   String auth = Base64.encodeBase64String(("beaker:" + password).getBytes("ASCII"));
   String response =
       Request.Get("http://127.0.0.1:" + corePort + "/rest/plugin-services/getAvailablePort")
           .addHeader("Authorization", "Basic " + auth)
           .execute()
           .returnContent()
           .asString();
   return Integer.parseInt(response);
 }
Esempio n. 13
0
  @Test
  public void testUnboundVariable() throws Exception {
    String uri = "avg_ages";

    String aggregationsMetadata =
        "{\"aggrs\": ["
            + "{"
            + "\"type\":\"mapReduce\""
            + ","
            + "\"uri\": \""
            + uri
            + "\","
            + "\"map\": \"function() { emit(this.name, this.age) }\""
            + ","
            + "\"reduce\":\"function(key, values) { return Array.avg(values) }\""
            + ","
            + "\"query\":{\"name\":{\"_$var\":\"name\"}}"
            + "}]}";

    createTmpCollection();
    createMetadataAndTestData(aggregationsMetadata);

    Response resp;

    URI aggrUri =
        buildURI(
            "/"
                + dbTmpName
                + "/"
                + collectionTmpName
                + "/"
                + RequestContext._AGGREGATIONS
                + "/"
                + uri);

    resp = adminExecutor.execute(Request.Get(aggrUri));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);
    HttpEntity entity = httpResp.getEntity();
    assertNotNull(entity);
    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check status code", HttpStatus.SC_BAD_REQUEST, statusLine.getStatusCode());
    assertNotNull("content type not null", entity.getContentType());
    assertEquals(
        "check content type",
        Representation.HAL_JSON_MEDIA_TYPE,
        entity.getContentType().getValue());
  }
Esempio n. 14
0
 /**
  * Returns the latest api version supported by the catalog
  *
  * @throws JackanException on error
  */
 private synchronized int getApiVersion(int number) {
   String fullUrl = catalogURL + "/api/" + number;
   logger.log(Level.FINE, "getting {0}", fullUrl);
   try {
     Request request = Request.Get(fullUrl);
     if (proxy != null) {
       request.viaProxy(proxy);
     }
     String json = request.execute().returnContent().asString();
     return getObjectMapper().readValue(json, ApiVersionResponse.class).version;
   } catch (Exception ex) {
     throw new JackanException("Error while fetching api version!", this, ex);
   }
 }
Esempio n. 15
0
 public Object get(String name) throws ClientProtocolException, IOException {
   String args =
       "name="
           + URLEncoder.encode(name, "ISO-8859-1")
           + "&session="
           + URLEncoder.encode(this.session, "ISO-8859-1");
   String valueString =
       Request.Get(urlBase + "/get?" + args)
           .addHeader("Authorization", auth)
           .execute()
           .returnContent()
           .asString();
   NamespaceBinding binding = mapper.readValue(valueString, NamespaceBinding.class);
   if (!binding.getDefined()) {
     throw new RuntimeException("name not defined: " + name);
   }
   return binding.getValue();
 }
Esempio n. 16
0
  private String getEtag(URI uri) throws IOException {
    Response resp = adminExecutor.execute(Request.Get(uri));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);
    HttpEntity entity = httpResp.getEntity();
    assertNotNull(entity);
    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check status code", HttpStatus.SC_OK, statusLine.getStatusCode());
    assertNotNull("content type not null", entity.getContentType());
    assertEquals(
        "check content type",
        Representation.HAL_JSON_MEDIA_TYPE,
        entity.getContentType().getValue());

    String content = EntityUtils.toString(entity);

    assertNotNull("", content);

    JsonObject json = null;

    try {
      json = JsonObject.readFrom(content);
    } catch (Throwable t) {
      fail("parsing received json");
    }

    assertNotNull("check not null json", json);

    assertNotNull("check not null _etag", json.get("_etag"));
    assertTrue("check _etag is object", json.get("_etag").isObject());

    assertNotNull("check not null _etag.$oid", json.get("_etag").asObject().get("$oid"));

    assertNotNull(
        "check _etag.$oid is string", json.get("_etag").asObject().get("$oid").isString());

    return json.get("_etag").asObject().get("$oid").asString();
  }
Esempio n. 17
0
 private String getUrlContentAsString(
     URI uri, int connectTimeout, int socketTimeout, Charset charset) throws NbaException {
   Response response = null;
   try {
     response =
         Request.Get(uri).connectTimeout(connectTimeout).socketTimeout(socketTimeout).execute();
   } catch (ClientProtocolException e) {
     throw new NbaException(ExType.ER_0001, e);
   } catch (IOException e) {
     throw new NbaException(ExType.ER_0002, e);
   }
   String resp;
   try {
     resp = new String(response.returnContent().asBytes(), charset);
     return resp;
   } catch (ClientProtocolException e) {
     throw new NbaException(ExType.ER_0003, e);
   } catch (IOException e) {
     throw new NbaException(ExType.ER_0004, e);
   }
 }
Esempio n. 18
0
  @Override
  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
      throws ServletException, IOException {
    if (req.getParameter("text") == null || req.getParameter("voice") == null) {
      req.getRequestDispatcher("/index.jsp").forward(req, resp);
    } else {
      boolean download = false;
      if (req.getParameter("download") != null
          && req.getParameter("download").equalsIgnoreCase("true")) {
        download = true;
      }

      req.setCharacterEncoding("UTF-8");
      try {
        String queryStr = req.getQueryString();
        String url = baseURL + "/v1/synthesize";
        if (queryStr != null) {
          url += "?" + queryStr;
        }
        URI uri = new URI(url).normalize();

        Request newReq = Request.Get(uri);
        newReq.addHeader("Accept", "audio/ogg; codecs=opus");

        Executor executor = Executor.newInstance().auth(username, password);
        Response response = executor.execute(newReq);
        if (download) {
          resp.setHeader("content-disposition", "attachment; filename=transcript.ogg");
        }
        ServletOutputStream servletOutputStream = resp.getOutputStream();
        response.returnResponse().getEntity().writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();
      } 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);
      }
    }
  }
 public static String getDataAsStringFromUrl(String url) throws Exception {
   return Request.Get(url).execute().returnContent().asString();
 }
Esempio n. 20
0
  @Test
  public void testGetMapReduceWithVariable() throws Exception {
    String uri = "avg_ages";

    String aggregationsMetadata =
        "{\"aggrs\": ["
            + "{"
            + "\"type\":\"mapReduce\""
            + ","
            + "\"uri\": \""
            + uri
            + "\","
            + "\"map\": \"function() { var minage = JSON.parse($vars).minage; if (this.age > minage ) { emit(this.name, this.age); }; }\","
            + "\"reduce\":\"function(key, values) { return Array.avg(values); }\""
            + ","
            + "\"query\":{\"name\":{\"_$var\":\"name\"}}"
            + "}]}";

    createTmpCollection();
    createMetadataAndTestData(aggregationsMetadata);

    Response resp;

    URI aggrUri =
        buildURI(
            "/"
                + dbTmpName
                + "/"
                + collectionTmpName
                + "/"
                + RequestContext._AGGREGATIONS
                + "/"
                + uri,
            new NameValuePair[] {
              new BasicNameValuePair("avars", "{\"name\": \"a\", \"minage\": 20}")
            });

    resp = adminExecutor.execute(Request.Get(aggrUri));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);
    HttpEntity entity = httpResp.getEntity();
    assertNotNull(entity);
    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check status code", HttpStatus.SC_OK, statusLine.getStatusCode());
    assertNotNull("content type not null", entity.getContentType());
    assertEquals(
        "check content type",
        Representation.HAL_JSON_MEDIA_TYPE,
        entity.getContentType().getValue());

    String content = EntityUtils.toString(entity);

    assertNotNull("", content);

    JsonObject json = null;

    try {
      json = JsonObject.readFrom(content);
    } catch (Throwable t) {
      fail("parsing received json");
    }

    assertNotNull("check not null json response", json);
    assertNotNull("check not null _embedded", json.get("_embedded"));
    assertTrue("check _embedded", json.get("_embedded").isObject());

    assertNotNull("", json.get("_embedded").asObject().get("rh:result"));
    assertTrue(
        "check _embedded[\"rh:results\"]",
        json.get("_embedded").asObject().get("rh:result").isArray());

    JsonArray results = json.get("_embedded").asObject().get("rh:result").asArray();

    assertTrue("check we have 2 results", results.size() == 1);

    results
        .values()
        .stream()
        .map(
            (v) -> {
              assertNotNull("check not null _id property", v.asObject().get("_id"));
              return v;
            })
        .map(
            (v) -> {
              assertTrue(
                  "check results _id property is string", v.asObject().get("_id").isString());
              return v;
            })
        .map(
            (v) -> {
              assertTrue(
                  "check results _id property is a",
                  v.asObject().get("_id").asString().equals("a"));
              return v;
            })
        .map(
            (v) -> {
              assertNotNull("check not null value property", v.asObject().get("value"));
              return v;
            })
        .forEach(
            (v) -> {
              assertTrue(
                  "check results value property is number", v.asObject().get("value").isNumber());
            });
  }
Esempio n. 21
0
 public String get(String uri) throws IOException {
   Content content = Request.Get(uri).execute().returnContent();
   return content.asString();
 }
Esempio n. 22
0
 public int getForStatus(String uri) throws IOException {
   StatusLine statusLine = Request.Get(uri).execute().returnResponse().getStatusLine();
   return statusLine.getStatusCode();
 }
 private void resetAllQueues() throws IOException {
   Request.Get("http://localhost:8080/agilehackathon/rest/practices/resetAllQueues")
       .connectTimeout(1000)
       .socketTimeout(1000)
       .execute();
 }
 private void givenTheJoinPracticeQueueServiceIsCalled() throws IOException {
   String url = StringUtils.replace(JOIN_URL, "{practiceId}", "1");
   url = StringUtils.replace(url, "{username}", username);
   yatspec.log("JOIN_URL", url);
   Response response = Request.Get(url).connectTimeout(1000).socketTimeout(1000).execute();
 }
Esempio n. 25
0
  private void _testGetAggregation(String uri) throws Exception {
    Response resp;

    URI aggrUri =
        buildURI(
            "/"
                + dbTmpName
                + "/"
                + collectionTmpName
                + "/"
                + RequestContext._AGGREGATIONS
                + "/"
                + uri);

    resp = adminExecutor.execute(Request.Get(aggrUri));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);
    HttpEntity entity = httpResp.getEntity();
    assertNotNull(entity);
    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check status code", HttpStatus.SC_OK, statusLine.getStatusCode());
    assertNotNull("content type not null", entity.getContentType());
    assertEquals(
        "check content type",
        Representation.HAL_JSON_MEDIA_TYPE,
        entity.getContentType().getValue());

    String content = EntityUtils.toString(entity);

    assertNotNull("", content);

    JsonObject json = null;

    try {
      json = JsonObject.readFrom(content);
    } catch (Throwable t) {
      fail("parsing received json");
    }

    assertNotNull("check not null json response", json);
    assertNotNull("check not null _embedded", json.get("_embedded"));
    assertTrue("check _embedded", json.get("_embedded").isObject());

    assertNotNull("", json.get("_embedded").asObject().get("rh:result"));

    assertTrue(
        "check _embedded[\"rh:result\"]",
        json.get("_embedded").asObject().get("rh:result").isArray());

    JsonArray results = json.get("_embedded").asObject().get("rh:result").asArray();

    assertTrue("check we have 2 results", results.size() == 2);

    results
        .values()
        .stream()
        .map(
            (v) -> {
              assertNotNull("check not null _id property", v.asObject().get("_id"));
              return v;
            })
        .map(
            (v) -> {
              assertTrue(
                  "check results _id property is string", v.asObject().get("_id").isString());
              return v;
            })
        .map(
            (v) -> {
              assertNotNull("check not null value property", v.asObject().get("value"));
              return v;
            })
        .forEach(
            (v) -> {
              assertTrue(
                  "check results value property is number", v.asObject().get("value").isNumber());
            });
  }