コード例 #1
0
  /**
   * Invoke API by sending HTTP request with the given options.
   *
   * @param path The sub-path of the HTTP URL
   * @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
   * @param queryParams The query parameters
   * @param body The request body object - if it is not binary, otherwise null
   * @param binaryBody The request body object - if it is binary, otherwise null
   * @param headerParams The header parameters
   * @param formParams The form parameters
   * @param accept The request's Accept header
   * @param contentType The request's Content-Type header
   * @param authNames The authentications to apply
   * @return The response body in type of string
   */
  public <T> T invokeAPI(
      String path,
      String method,
      List<Pair> queryParams,
      Object body,
      byte[] binaryBody,
      Map<String, String> headerParams,
      Map<String, Object> formParams,
      String accept,
      String contentType,
      String[] authNames,
      TypeRef returnType)
      throws ApiException {

    Response response =
        getAPIResponse(
            path,
            method,
            queryParams,
            body,
            binaryBody,
            headerParams,
            formParams,
            accept,
            contentType,
            authNames);

    statusCode = response.getStatusInfo().getStatusCode();
    responseHeaders = response.getHeaders();

    if (statusCode == 401) {
      throw new ApiException(
          response.getStatusInfo().getStatusCode(),
          "HTTP Error 401 - Unauthorized: Access is denied due to invalid credentials.",
          response.getHeaders(),
          null);
    } else if (response.getStatusInfo() == Response.Status.NO_CONTENT) {
      return null;
    } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      if (returnType == null) return null;
      else return deserialize(response, returnType);
    } else {
      String message = "error";
      String respBody = null;
      if (response.hasEntity()) {
        try {
          respBody = response.readEntity(String.class);
          message = respBody;
        } catch (RuntimeException e) {
          // e.printStackTrace();
        }
      }
      throw new ApiException(
          response.getStatusInfo().getStatusCode(), message, response.getHeaders(), respBody);
    }
  }
コード例 #2
0
    @Test
    public void testLastModifiedGET() {
      final WebTarget target = target("/application.wadl");

      final Response r =
          target
              .queryParam(WadlUtils.DETAILED_WADL_QUERY_PARAM, "true")
              .request()
              .get(Response.class);
      assertTrue(r.getHeaders().containsKey("Last-modified"));
    }
コード例 #3
0
    @Test
    public void testLastModifiedOPTIONS() {
      final WebTarget target = target("/widgets/3/verbose");

      final Response r =
          target
              .queryParam(WadlUtils.DETAILED_WADL_QUERY_PARAM, "true")
              .request(MediaTypes.WADL_TYPE)
              .options();
      System.out.println(r.readEntity(String.class));
      assertTrue(r.getHeaders().containsKey("Last-modified"));
    }
コード例 #4
0
  @Test
  public void testGetTask() throws Exception {
    final long taskId = 42;
    Response response = target("/tasks/" + taskId).request().get();
    assertResponseStatus(response, Response.Status.OK);
    assertHeader(
        response.getHeaders(), HttpHeaders.CONTENT_TYPE, JsonApiMediaType.APPLICATION_JSON_API);

    JsonNode data = mapper.readTree((InputStream) response.getEntity()).get("data");
    final Task task = getTaskFromJson(data);
    assertThat(task.getId(), is(taskId));
    assertThat(task.getName(), is("Some task"));
    assertThat(task.getProject(), is(nullValue()));
  }
コード例 #5
0
ファイル: SendEventTest.java プロジェクト: Lambeaux/ddf
  @Before
  public void setUp() throws Exception {
    System.setProperty("ddf.home", ".");
    callbackURI = new URL("https://localhost:12345/services/csw/subscription/event");
    ObjectFactory objectFactory = new ObjectFactory();
    request = new GetRecordsType();
    request.setOutputSchema(CswConstants.CSW_OUTPUT_SCHEMA);
    request.setResultType(ResultType.RESULTS);
    request.getResponseHandler().add(callbackURI.toString());
    queryType = new QueryType();
    elementSetNameType = new ElementSetNameType();
    elementSetNameType.setValue(ElementSetType.BRIEF);
    queryType.setElementSetName(elementSetNameType);
    request.setAbstractQuery(objectFactory.createAbstractQuery(queryType));
    transformerManager = mock(TransformerManager.class);
    transformer = mock(QueryResponseTransformer.class);
    binaryContent = mock(BinaryContent.class);
    when(transformerManager.getTransformerBySchema(
            Matchers.contains(CswConstants.CSW_OUTPUT_SCHEMA)))
        .thenReturn(transformer);
    when(transformer.transform(any(SourceResponse.class), anyMap())).thenReturn(binaryContent);
    when(binaryContent.getByteArray()).thenReturn("byte array with message contents".getBytes());
    query = mock(QueryRequest.class);

    metacard = mock(Metacard.class);
    webclient = mock(WebClient.class);
    mockCxfClientFactory = mock(SecureCxfClientFactory.class);
    response = mock(Response.class);
    subject = mock(Subject.class);

    mockSecurity = mock(Security.class);
    headers.put(Subject.class.toString(), Arrays.asList(new Subject[] {subject}));
    AccessPlugin accessPlugin = mock(AccessPlugin.class);
    accessPlugins.add(accessPlugin);
    when(mockCxfClientFactory.getWebClient()).thenReturn(webclient);
    //        when(webclient.head()).thenReturn(response);
    when(webclient.invoke(anyString(), any(QueryResponse.class))).thenReturn(response);
    when(response.getHeaders()).thenReturn(headers);
    when(accessPlugin.processPostQuery(any(QueryResponse.class)))
        .thenAnswer(
            new Answer<QueryResponse>() {
              @Override
              public QueryResponse answer(InvocationOnMock invocationOnMock) throws Throwable {
                return (QueryResponse) invocationOnMock.getArguments()[0];
              }
            });

    sendEvent = new SendEventExtension(transformerManager, request, query, mockCxfClientFactory);
    sendEvent.setSubject(subject);
  }
コード例 #6
0
  /** Deserialize response body to Java object according to the Content-Type. */
  public <T> T deserialize(Response response, TypeRef returnType) throws ApiException {
    String contentType = null;
    List<Object> contentTypes = response.getHeaders().get("Content-Type");
    if (contentTypes != null && !contentTypes.isEmpty()) contentType = (String) contentTypes.get(0);
    if (contentType == null) throw new ApiException(500, "missing Content-Type in response");

    String body;
    if (response.hasEntity()) body = (String) response.readEntity(String.class);
    else body = "";

    if (contentType.startsWith("application/json")) {
      return json.deserialize(body, returnType);
    } else {
      throw new ApiException(500, "can not deserialize Content-Type: " + contentType);
    }
  }
コード例 #7
0
  @Test
  public void testGetTasks() throws Exception {
    Response response = target("/tasks").request().get();
    assertResponseStatus(response, Response.Status.OK);
    assertHeader(
        response.getHeaders(), HttpHeaders.CONTENT_TYPE, JsonApiMediaType.APPLICATION_JSON_API);

    JsonNode data = mapper.readTree((InputStream) response.getEntity()).get("data");
    assertThat(data.getNodeType(), is(JsonNodeType.ARRAY));
    List<Task> tasks = new ArrayList<>();
    for (JsonNode node : data) {
      tasks.add(getTaskFromJson(node));
    }
    assertThat(tasks, hasSize(1));
    final Task task = tasks.get(0);
    assertThat(task.getId(), is(1L));
    assertThat(task.getName(), is("First task"));
    assertThat(task.getProject(), is(nullValue()));
  }
コード例 #8
0
  public Session login(final UserCredential userCredential) {
    WebTarget target =
        client
            .target("http://auth.getprismatic.com")
            .path("auth")
            .path("login")
            .queryParam("api-version", "1.2")
            .queryParam("ignore", "true")
            .queryParam("whitelist_url", "http%3A%2F%2Fgetprismatic.com%2Fnews%2Fhome")
            .queryParam("soon_url", "http%3A%2F%2Fgetprismatic.com%2Fwelcome")
            .queryParam("create_url", "http%3A%2F%2Fgetprismatic.com%2Fcreateaccount")
            .queryParam("resetpassword_url", "http%3A%2F%2Fgetprismatic.com%2Fresetpassword");

    Response response =
        target.request().post(Entity.entity(userCredential, MediaType.APPLICATION_JSON_TYPE));

    checkResponseStatus(response);

    return Session.parseFromHeaders(response.getHeaders().get("Set-Cookie"));
  }
コード例 #9
0
ファイル: WebClient.java プロジェクト: faireprogram/CS549
 private void processResponseTimestamp(Response cr) {
   Time.advanceTime(Long.parseLong(cr.getHeaders().getFirst(Time.TIME_STAMP).toString()));
 }
コード例 #10
0
 /**
  * Gets the query results.
  *
  * @param qh the qh
  * @return the query results
  */
 @CliCommand(
     value = "query results",
     help =
         "get results of query with query handle <query_handle>. "
             + DEFAULT_QUERY_HANDLE_DESCRIPTION
             + "If async is false then wait till the query execution is completed, it's by default true. "
             + "Can optionally save the results to a file by providing <save_location>.")
 public String getQueryResults(
     @CliOption(
             key = {"", "query_handle"},
             mandatory = false,
             help = "<query_handle>")
         String qh,
     @CliOption(
             key = {"save_location"},
             mandatory = false,
             help = "<save_location>")
         final File path,
     @CliOption(
             key = {"async"},
             mandatory = false,
             unspecifiedDefaultValue = "true",
             help = "<async>")
         boolean async) {
   qh = getOrDefaultQueryHandleString(qh);
   QueryHandle queryHandle = new QueryHandle(UUID.fromString(qh));
   LensClient.LensClientResultSetWithStats results;
   String location = path != null ? path.getPath() : null;
   try {
     if (StringUtils.isNotBlank(location)) {
       location = getValidPath(path, true, true);
       Response response = getClient().getHttpResults(queryHandle);
       if (response.getStatus() == Response.Status.OK.getStatusCode()) {
         String disposition = (String) response.getHeaders().get("content-disposition").get(0);
         String fileName = disposition.split("=")[1].trim();
         location = getValidPath(new File(location + File.separator + fileName), false, false);
         try (InputStream stream = response.readEntity(InputStream.class);
             FileOutputStream outStream = new FileOutputStream(new File(location))) {
           IOUtils.copy(stream, outStream);
         }
         return "Saved to " + location;
       } else {
         if (async) {
           results = getClient().getAsyncResults(queryHandle);
         } else {
           results = getClient().getSyncResults(queryHandle);
         }
         if (results.getResultSet() == null) {
           return "Resultset not yet available";
         } else if (results.getResultSet().getResult() instanceof InMemoryQueryResult) {
           location =
               getValidPath(new File(location + File.separator + qh + ".csv"), false, false);
           try (OutputStreamWriter osw =
               new OutputStreamWriter(new FileOutputStream(location), Charset.defaultCharset())) {
             osw.write(formatResultSet(results));
           }
           return "Saved to " + location;
         } else {
           return "Can't download the result because it's available in driver's persistence.\n"
               + formatResultSet(results);
         }
       }
     } else if (async) {
       return formatResultSet(getClient().getAsyncResults(queryHandle));
     } else {
       return formatResultSet(getClient().getSyncResults(queryHandle));
     }
   } catch (Throwable t) {
     return t.getMessage();
   }
 }