/**
  * Share header settings for invocations.
  *
  * @param webTarget target web
  * @return
  */
 private Response post(WebTarget webTarget) {
   Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON_TYPE);
   if (null != authorization) {
     invocationBuilder.header(HEADER_AUTHORIZATION, authorization);
   }
   return invocationBuilder.post(Entity.text(""));
 }
  @Before
  public void setUp() {

    RegionCache regionCache = new RegionCache();
    regionCache.clear();
    openStackRegion = new OpenStackRegionImpl();
    Client client = mock(Client.class);
    WebTarget webResource = mock(WebTarget.class);
    builder = mock(Invocation.Builder.class);
    clientResponse = mock(Response.class);
    Response clientResponseAdmin = mock(Response.class);

    // when
    when(webResource.request(MediaType.APPLICATION_JSON)).thenReturn(builder);
    when(builder.accept(MediaType.APPLICATION_JSON)).thenReturn(builder);

    when(client.target(anyString())).thenReturn(webResource);
    openStackRegion.setClient(client);
    systemPropertiesProvider = mock(SystemPropertiesProvider.class);
    openStackRegion.setSystemPropertiesProvider(systemPropertiesProvider);

    String responseJSON =
        "{\"access\": {\"token\": {\"issued_at\": \"2014-01-13T14:00:10.103025\", \"expires\": \"2014-01-14T14:00:09Z\","
            + "\"id\": \"ec3ecab46f0c4830ad2a5837fd0ad0d7\", \"tenant\": { \"description\": null, \"enabled\": true, \"id\": \"08bed031f6c54c9d9b35b42aa06b51c0\","
            + "\"name\": \"admin\" } },         \"serviceCatalog\": []}}}";

    when(builder.post(Entity.entity(anyString(), MediaType.APPLICATION_JSON)))
        .thenReturn(clientResponseAdmin);
    when(clientResponseAdmin.getStatus()).thenReturn(200);
    when(clientResponseAdmin.readEntity(String.class)).thenReturn(responseJSON);
  }
  public Post fetch(Session session, NextRequest next) {
    LOGGER.debug(
        ((next == null) ? "Initial request" : "next request: " + next)
            + "/n Session: "
            + session.toString());
    WebTarget target = createInitialFetchTarget();

    if (next != null) {
      target = fillNextParameters(next, target);
    }

    Invocation.Builder request = target.request();

    request = appendCookies(session, request);

    Response response =
        request.post(
            Entity.entity(
                new NextToken.NextTokenBuilder().createNextToken(),
                MediaType.APPLICATION_JSON_TYPE));

    response.bufferEntity();
    try {
      String responseJson = response.readEntity(String.class);
      LOGGER.debug("Full response: " + responseJson);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    Post post = response.readEntity(Post.class);
    response.close();

    return post;
  }
  @Test
  public void testImplicitExplicitTemplate() throws IOException {
    final Invocation.Builder request = target("implicit-explicit").request();

    Properties p = new Properties();
    p.load(request.get(InputStream.class));
    assertEquals(
        "/org/glassfish/jersey/tests/e2e/server/mvc/FlatViewProcessorTest.ImplicitExplicitTemplate.index.testp",
        p.getProperty("path"));
    assertEquals("ImplicitExplicitTemplate", p.getProperty("model"));

    p = new Properties();
    p.load(request.post(Entity.entity("", MediaType.TEXT_PLAIN_TYPE), InputStream.class));
    assertEquals(
        "/org/glassfish/jersey/tests/e2e/server/mvc/FlatViewProcessorTest.ImplicitExplicitTemplate.show.testp",
        p.getProperty("path"));
    assertEquals("post", p.getProperty("model"));

    p = new Properties();
    p.load(target("implicit-explicit").path("sub").request().get(InputStream.class));
    assertEquals(
        "/org/glassfish/jersey/tests/e2e/server/mvc/FlatViewProcessorTest.ImplicitExplicitTemplate.show.testp",
        p.getProperty("path"));
    assertEquals("get", p.getProperty("model"));
  }
  private CallReturn prepareCall(
      String jsonString, String path, MultivaluedMap<String, Object> headers, CALL_TYPE callType)
      throws IOException {
    Entity<String> itemToSend = Entity.json(jsonString);
    // LOG.debug("sending\n" + jsonString + "\n");
    Invocation.Builder responseBuilder =
        getRestAudienceClient().getWebTarget().path(path).request(MediaType.APPLICATION_JSON);
    if (headers != null) {
      responseBuilder.headers(headers);
    }

    Response response = null;

    switch (callType) {
      case get:
        response = responseBuilder.get();

        break;
      case post:
        {
          response = responseBuilder.post(itemToSend);
        }
    }

    return createCallReturnFromResponse(response);
  }
  @Test
  public void testShouldReturnTwoRegionNamesInEssex() throws OpenStackException {
    // given
    OpenStackRegionImpl openStackRegion = new OpenStackRegionImpl();
    Client client = mock(Client.class);
    openStackRegion.setClient(client);
    SystemPropertiesProvider systemPropertiesProvider = mock(SystemPropertiesProvider.class);
    openStackRegion.setSystemPropertiesProvider(systemPropertiesProvider);
    String token = "123456789";
    String responseError =
        "{\n"
            + "    \"error\": {\n"
            + "        \"message\": \"The action you have requested has not been implemented.\",\n"
            + "        \"code\": 501,\n"
            + "        \"title\": null\n"
            + "    }\n"
            + "}";

    String url = "http://domain.com/v2.0/tokens/" + token + "/endpoints";

    String urlEssex = "http://domain.com/v2.0/tokens";

    WebTarget webResource = mock(WebTarget.class);
    WebTarget webResourceEssex = mock(WebTarget.class);
    Invocation.Builder builder = mock(Invocation.Builder.class);
    Invocation.Builder builderEssex = mock(Invocation.Builder.class);

    Response clientResponse = mock(Response.class);
    Response clientResponseEssex = mock(Response.class);

    // when

    when(systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_URL))
        .thenReturn("http://domain.com/v2.0/");
    when(client.target(url)).thenReturn(webResource);
    when(webResource.request(MediaType.APPLICATION_JSON)).thenReturn(builder);
    when(builder.get()).thenReturn(clientResponse);
    when(clientResponse.getStatus()).thenReturn(501);
    when(clientResponse.readEntity(String.class)).thenReturn(responseError);

    when(client.target(urlEssex)).thenReturn(webResourceEssex);
    when(webResourceEssex.request(MediaType.APPLICATION_JSON)).thenReturn(builderEssex);
    when(builderEssex.accept(MediaType.APPLICATION_JSON)).thenReturn(builderEssex);
    when(builderEssex.header("Content-type", MediaType.APPLICATION_JSON)).thenReturn(builderEssex);
    when(builderEssex.post(Entity.entity(anyString(), MediaType.APPLICATION_JSON)))
        .thenReturn(clientResponseEssex);
    when(clientResponseEssex.getStatus()).thenReturn(200);
    when(clientResponseEssex.readEntity(String.class)).thenReturn(RESPONSE_ESSEX);

    List<String> result = openStackRegion.getRegionNames(token);

    // then
    assertNotNull(result);
    assertEquals(2, result.size());
    assertEquals("RegionOne", result.get(0));
    assertEquals("RegionTwo", result.get(1));
  }
Exemple #7
0
 public Response postSequenceFile(
     String url, String recordId, EntryType entryType, String sequence) {
   WebTarget target = client.target("https://" + url).path("/rest/file/sequence");
   Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
   final FormDataMultiPart multiPart = new FormDataMultiPart();
   multiPart.field("file", IOUtils.toInputStream(sequence), MediaType.TEXT_PLAIN_TYPE);
   multiPart.field("entryRecordId", recordId);
   multiPart.field("entryType", entryType.name());
   return invocationBuilder.post(Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE));
 }
Exemple #8
0
  @Override
  public <T> T post(
      String url,
      String resourcePath,
      Object object,
      Class<T> responseClass,
      Map<String, Object> queryParams) {
    WebTarget target = client.target("https://" + url).path(resourcePath);
    if (queryParams != null) {
      for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
        target = target.queryParam(entry.getKey(), entry.getValue());
      }
    }

    Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    Response postResponse =
        invocationBuilder.post(Entity.entity(object, MediaType.APPLICATION_JSON_TYPE));
    if (postResponse.hasEntity() && postResponse.getStatus() == Response.Status.OK.getStatusCode())
      return postResponse.readEntity(responseClass);
    return null;
  }
  private Response getAPIResponse(
      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)
      throws ApiException {

    if (body != null && binaryBody != null) {
      throw new ApiException(500, "either body or binaryBody must be null");
    }

    Client client = getClient();
    Response response = null;

    StringBuilder b = new StringBuilder();
    b.append("?");
    if (queryParams != null) {
      for (Pair queryParam : queryParams) {
        if (!queryParam.getName().isEmpty()) {
          b.append(escapeString(queryParam.getName()));
          b.append("=");
          b.append(escapeString(queryParam.getValue()));
          b.append("&");
        }
      }
    }

    String querystring = b.substring(0, b.length() - 1);

    WebTarget target = client.target(basePath + path + querystring);

    if (debugging) {
      target.register(new LoggingFilter());
    }

    if (authentication != null) {
      authentication.setFilter(target);
    }

    Invocation.Builder builder;
    if (accept != null) {
      builder = target.request(accept);
    } else {
      builder = target.request();
    }

    for (Map.Entry<String, String> entry : headerParams.entrySet()) {
      builder = builder.header(entry.getKey(), entry.getValue());
    }
    for (Map.Entry<String, String> entry : defaultHeaderMap.entrySet()) {
      if (!headerParams.containsKey(entry.getKey())) {
        builder = builder.header(entry.getKey(), entry.getValue());
      }
    }

    if ("GET".equals(method)) {
      response = builder.get();
    } else if ("POST".equals(method)) {
      response = builder.post(Entity.entity(body, contentType));
    } else if ("PUT".equals(method)) {
      if (body != null) {
        response = builder.put(Entity.entity(body, contentType));
      } else {
        response = builder.put(Entity.text(""));
      }
    } else if ("DELETE".equals(method)) {
      response = builder.delete();
    } else {
      throw new ApiException(500, "unknown method type " + method);
    }

    return response;
  }
  /**
   * uploads zip file using the input HTTP URL
   *
   * @param httpURL
   * @param filePath
   * @param filename
   * @return
   * @throws Exception
   */
  public static String testUploadService(String httpURL, File filePath) throws Exception {

    // local variables
    ClientConfig clientConfig = null;
    Client client = null;
    WebTarget webTarget = null;
    Invocation.Builder invocationBuilder = null;
    Response response = null;
    FileDataBodyPart fileDataBodyPart = null;
    FormDataMultiPart formDataMultiPart = null;
    int responseCode;
    String responseMessageFromServer = null;
    String responseString = null;

    try {
      // invoke service after setting necessary parameters
      clientConfig = new ClientConfig();
      clientConfig.register(MultiPartFeature.class);
      client = ClientBuilder.newClient(clientConfig);
      webTarget = client.target(httpURL);

      // set file upload values
      fileDataBodyPart =
          new FileDataBodyPart("uploadFile", filePath, MediaType.APPLICATION_OCTET_STREAM_TYPE);
      formDataMultiPart = new FormDataMultiPart();
      formDataMultiPart.bodyPart(fileDataBodyPart);

      StreamDataBodyPart bodyPart = new StreamDataBodyPart();

      // invoke service
      invocationBuilder = webTarget.request();
      //          invocationBuilder.header("Authorization", "Basic " + authorization);
      response =
          invocationBuilder.post(Entity.entity(formDataMultiPart, MediaType.MULTIPART_FORM_DATA));

      // get response code
      responseCode = response.getStatus();
      System.out.println("Response code: " + responseCode);

      if (response.getStatus() != 200) {
        throw new RuntimeException("Failed with HTTP error code : " + responseCode);
      }

      // get response message
      responseMessageFromServer = response.getStatusInfo().getReasonPhrase();
      System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);

      // get response string
      responseString = response.readEntity(String.class);
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      // release resources, if any
      fileDataBodyPart.cleanup();
      formDataMultiPart.cleanup();
      formDataMultiPart.close();
      response.close();
      client.close();
    }
    return responseString;
  }