protected ThingStatusDetail authenticate(String username, String password) {

    TokenRequest token = new TokenRequest(username, password);
    String payLoad = gson.toJson(token);

    Response response =
        tokenTarget.request().post(Entity.entity(payLoad, MediaType.APPLICATION_JSON_TYPE));

    logger.trace("Authenticating : Response : {}", response.getStatusInfo());

    if (response != null) {
      if (response.getStatus() == 200 && response.hasEntity()) {

        String responsePayLoad = response.readEntity(String.class);
        JsonObject readObject = parser.parse(responsePayLoad).getAsJsonObject();

        for (Entry<String, JsonElement> entry : readObject.entrySet()) {
          switch (entry.getKey()) {
            case "access_token":
              {
                accessToken = entry.getValue().getAsString();
                logger.trace("Authenticating : Setting access code to : {}", accessToken);
                return ThingStatusDetail.NONE;
              }
          }
        }
      } else if (response.getStatus() == 401) {
        return ThingStatusDetail.CONFIGURATION_ERROR;
      } else if (response.getStatus() == 503) {
        return ThingStatusDetail.COMMUNICATION_ERROR;
      }
    }
    return ThingStatusDetail.CONFIGURATION_ERROR;
  }
  @Test
  public void testMappedConfig_Override() throws Exception {

    MappedFilter mappedFilter =
        new MappedFilter(mockFilter, new HashSet<>(Arrays.asList("/a/*", "/b/*")), "f1", 0);

    app.start(
        binder -> {
          JettyModule.contributeMappedFilters(binder).addBinding().toInstance(mappedFilter);
        },
        "--config=classpath:io/bootique/jetty/MappedFilterIT1.yml");

    WebTarget base = ClientBuilder.newClient().target("http://localhost:8080");

    Response r1 = base.path("/a").request().get();
    assertEquals(Status.NOT_FOUND.getStatusCode(), r1.getStatus());

    Response r2 = base.path("/b").request().get();
    assertEquals(Status.NOT_FOUND.getStatusCode(), r2.getStatus());

    Response r3 = base.path("/c").request().get();
    assertEquals(Status.OK.getStatusCode(), r3.getStatus());

    verify(mockFilter, times(1)).doFilter(any(), any(), any());
  }
 private static void removeBook() {
   ResteasyClient client = new ResteasyClientBuilder().build();
   Response response =
       client
           .target("http://localhost:8080/v1/api")
           .path("bookstore/book")
           .path("1")
           .request()
           .header("Authorization", "Basic " + getBasicAuthenticationEncoding())
           .accept(MediaType.APPLICATION_JSON)
           .delete();
   System.out.println(response.getStatus());
   System.out.println(response.readEntity(String.class));
   System.out.println("---------------------------------------");
   response =
       client
           .target("http://localhost:8080/v1/api")
           .path("bookstore/book")
           .path("1")
           .request()
           .header("Authorization", "Basic " + getBasicAuthenticationEncoding())
           .accept(MediaType.APPLICATION_XML)
           .delete();
   System.out.println(response.getStatus());
   System.out.println(response.readEntity(String.class));
 }
 private static void updateBook() {
   ResteasyClient client = new ResteasyClientBuilder().build();
   Publisher publisher = new Publisher(1, "陕西师范大学出版社");
   Book book = new Book(1, "金庸", "987634556", "书剑恩仇录", publisher);
   Response response =
       client
           .target("http://localhost:8080/v1/api")
           .path("bookstore/book")
           .request()
           .header("Authorization", "Basic " + getBasicAuthenticationEncoding())
           .accept(MediaType.APPLICATION_JSON)
           .put(Entity.entity(book, MediaType.APPLICATION_JSON));
   System.out.println(response.getStatus());
   System.out.println(response.readEntity(String.class));
   System.out.println("---------------------------------------");
   response =
       client
           .target("http://localhost:8080/v1/api")
           .path("bookstore/book")
           .request()
           .header("Authorization", "Basic " + getBasicAuthenticationEncoding())
           .accept(MediaType.APPLICATION_XML)
           .put(Entity.entity(book, MediaType.APPLICATION_XML));
   System.out.println(response.getStatus());
   System.out.println(response.readEntity(String.class));
 }
 private static void getBooksSet() {
   ResteasyClient client = new ResteasyClientBuilder().build();
   System.out.println("----------------JSON-----------------------");
   Response response =
       client
           .target("http://localhost:8080/v1/api")
           .path("bookstore/set")
           .request()
           .accept(MediaType.APPLICATION_JSON)
           .get();
   System.out.println(response.getStatus());
   System.out.println(response.readEntity(String.class));
   System.out.println("----------------JSNOP-----------------------");
   response =
       client
           .target("http://localhost:8080/v1/api")
           .path("bookstore/set")
           .queryParam("callback", "books")
           .request()
           .accept(MediaType.APPLICATION_JSON)
           .get();
   System.out.println(response.getStatus());
   System.out.println(response.readEntity(String.class));
   System.out.println("----------------XML-----------------------");
   response =
       client
           .target("http://localhost:8080/v1/api")
           .path("bookstore/set")
           .request()
           .accept(MediaType.APPLICATION_XML)
           .get();
   System.out.println(response.getStatus());
   System.out.println(response.readEntity(String.class));
 }
 private static void addBooksMap() {
   ResteasyClient client = new ResteasyClientBuilder().build();
   Publisher publisher = new Publisher(1, "陕西师范大学出版社");
   Map<String, Book> books = new HashMap<String, Book>();
   Book book;
   for (int i = 1; i <= 20; i++) {
     book = new Book(i, "金庸", "987634556", "书剑恩仇录", publisher);
     books.put(String.valueOf(i), book);
   }
   Response response =
       client
           .target("http://localhost:8080/v1/api")
           .path("bookstore/map")
           .request()
           .header("Authorization", "Basic " + getBasicAuthenticationEncoding())
           .accept(MediaType.APPLICATION_JSON)
           .post(Entity.entity(books, MediaType.APPLICATION_JSON));
   System.out.println(response.getStatus());
   System.out.println(response.readEntity(String.class));
   System.out.println("---------------------------------------");
   response =
       client
           .target("http://localhost:8080/v1/api")
           .path("bookstore/map")
           .request()
           .header("Authorization", "Basic " + getBasicAuthenticationEncoding())
           .accept(MediaType.APPLICATION_XML)
           .post(Entity.entity(books, MediaType.APPLICATION_JSON));
   System.out.println(response.getStatus());
   System.out.println(response.readEntity(String.class));
 }
Exemple #7
0
  @Test
  public void testHead() throws Exception {
    startServer(Resource.class);

    Client client = ClientFactory.newClient();
    WebTarget r = client.target(getUri().path("/").build());

    Response cr = r.path("string").request("text/plain").head();
    assertEquals(200, cr.getStatus());
    assertEquals(MediaType.TEXT_PLAIN_TYPE, cr.getMediaType());
    assertFalse(cr.hasEntity());

    cr = r.path("byte").request("application/octet-stream").head();
    assertEquals(200, cr.getStatus());
    int length = cr.getLength();
    assertNotNull(length);
    // org.glassfish.jersey.server.model.HeadTest
    // TODO Uncomment once we implement outbound message payload buffering for determining proper
    // Content-Length value.
    //        assertEquals(3, length);
    assertEquals(MediaType.APPLICATION_OCTET_STREAM_TYPE, cr.getMediaType());
    assertFalse(cr.hasEntity());

    cr = r.path("ByteArrayInputStream").request("application/octet-stream").head();
    assertEquals(200, cr.getStatus());
    length = cr.getLength();
    assertNotNull(length);
    //        assertEquals(3, length);
    assertEquals(MediaType.APPLICATION_OCTET_STREAM_TYPE, cr.getMediaType());
    assertFalse(cr.hasEntity());
  }
  // TEIID-3914 - test the olingo-patch work
  public void testCompositeKeyTimestamp() throws Exception {

    String vdb =
        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
            + "<vdb name=\"northwind\" version=\"1\">\n"
            + "    <model name=\"m\">\n"
            + "        <source name=\"x1\" translator-name=\"loopback\" />\n"
            + "         <metadata type=\"DDL\"><![CDATA[\n"
            + "                CREATE FOREIGN TABLE x (a string, b timestamp, c integer, primary key (a, b)) options (updatable true);\n"
            + "        ]]> </metadata>\n"
            + "    </model>\n"
            + "</vdb>";

    admin.deploy(
        "loopy-vdb.xml", new ReaderInputStream(new StringReader(vdb), Charset.forName("UTF-8")));
    assertTrue(AdminUtil.waitForVDBLoad(admin, "Loopy", 1, 3));

    WebClient client =
        WebClient.create("http://localhost:8080/odata4/m/x(a='a',b=2011-09-11T00:00:00Z)");
    client.header(
        "Authorization",
        "Basic " + Base64.encodeBytes(("user:user").getBytes())); // $NON-NLS-1$ //$NON-NLS-2$
    Response response = client.invoke("GET", null);
    assertEquals(200, response.getStatus());

    client = WebClient.create("http://localhost:8080/odata4/m/x");
    client.header(
        "Authorization",
        "Basic " + Base64.encodeBytes(("user:user").getBytes())); // $NON-NLS-1$ //$NON-NLS-2$
    response = client.post("{\"a\":\"b\", \"b\":\"2000-02-02T22:22:22Z\"}");
    assertEquals(204, response.getStatus());

    admin.undeploy("loopy-vdb.xml");
  }
  public void sendMessages(
      String source, long sourceDeviceId, String destination, IncomingMessageList messages)
      throws IOException {
    Response response = null;

    try {
      response =
          client
              .target(peer.getUrl())
              .path(String.format(RELAY_MESSAGE_PATH, source, sourceDeviceId, destination))
              .request()
              .put(Entity.json(messages));

      if (response.getStatus() != 200 && response.getStatus() != 204) {
        if (response.getStatus() == 411)
          throw new WebApplicationException(Response.status(413).build());
        else throw new WebApplicationException(Response.status(response.getStatusInfo()).build());
      }

    } catch (ProcessingException e) {
      logger.warn("sendMessage", e);
      throw new IOException(e);
    } finally {
      if (response != null) response.close();
    }
  }
  @Test
  public void testStoreGetRemoveDocument() throws Exception {
    final JsonObject document = documents.get(0);

    // Store.
    final Response response =
        target("document").request(MediaType.APPLICATION_JSON).post(Entity.json(document));
    assertEquals(200, response.getStatus());

    final List<JsonNumber> ids = response.readEntity(JsonArray.class).getValuesAs(JsonNumber.class);
    assertEquals(1, ids.size());

    // Get.
    final String id = ids.get(0).toString();
    final WebTarget documentTarget = target("document").path(id);
    final JsonObject storedDocument =
        documentTarget.request(MediaType.APPLICATION_JSON).get(JsonObject.class);
    assertEquals(document, storedDocument);

    // Remove.
    final JsonObject removedDocument =
        documentTarget.request(MediaType.APPLICATION_JSON).delete(JsonObject.class);
    assertEquals(document, removedDocument);

    // Get.
    final Response errorResponse = documentTarget.request(MediaType.APPLICATION_JSON).get();
    assertEquals(204, errorResponse.getStatus());
  }
  private void testResumeException(final String path, final String entity) throws Exception {
    final WebTarget errorResource = target("errorResource");

    final Future<Response> suspended = errorResource.path("suspend").request().async().get();
    final Response response = errorResource.path(path).request().get();

    assertThat(response.getStatus(), equalTo(200));
    assertThat(response.readEntity(String.class), equalTo("ok"));

    final Response suspendedResponse = suspended.get();

    assertThat(suspendedResponse.getStatus(), equalTo(500));
    if (entity != null) {
      assertThat(suspendedResponse.readEntity(String.class), equalTo(entity));
    }

    suspendedResponse.close();

    // Check there is no NPE.
    for (final LogRecord record : getLoggedRecords()) {
      final Throwable thrown = record.getThrown();
      if (thrown != null && thrown instanceof NullPointerException) {
        fail("Unexpected NPE.");
      }
    }
  }
 /** {@inheritDoc} */
 public void clear() {
   WebTarget wr = client.target(url).path(RESOURCE_PROPERTYSTORE).path(STORE_CLEAR);
   Response cRes = post(wr);
   if (Status.OK.getStatusCode() != cRes.getStatus()) {
     throw new PropertyAccessException("Cannot clear property store - " + cRes.getStatus());
   }
 }
Exemple #13
0
 @Test
 public void testNotAuthenticated() {
   {
     // assuming @RolesAllowed is on class level. Too lazy to test it all!
     String newUser =
         "******"user\" : { \"username\" : \"wburke\", \"name\" : \"Bill Burke\", \"email\" : \"[email protected]\", \"enabled\" : true, \"credentials\" : { \"password\" : \"geheim\" }} }";
     ResteasyClient client = new ResteasyClient(deployment.getProviderFactory());
     Response response = client.target(generateURL("/users")).request().post(Entity.json(newUser));
     Assert.assertEquals(response.getStatus(), 403);
     response.close();
   }
   {
     String newRole = "{ \"role\" : { \"name\" : \"admin\"} }";
     ResteasyClient client = new ResteasyClient(deployment.getProviderFactory());
     Response response = client.target(generateURL("/roles")).request().post(Entity.json(newRole));
     Assert.assertEquals(response.getStatus(), 403);
     response.close();
   }
   {
     String newProject =
         "{ \"project\" : { \"id\" : \"5\", \"name\" : \"Resteasy\", \"description\" : \"The Best of REST\", \"enabled\" : true } }";
     ResteasyClient client = new ResteasyClient(deployment.getProviderFactory());
     Response response =
         client.target(generateURL("/projects")).request().post(Entity.json(newProject));
     Assert.assertEquals(response.getStatus(), 403);
     response.close();
   }
 }
Exemple #14
0
  public <T> T putWor(
      String url,
      String resourcePath,
      Object object,
      Class<T> responseClass,
      Map<String, Object> queryParams,
      String worToken) {
    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);
    setHeaders(invocationBuilder, worToken);
    Response putResponse =
        invocationBuilder.put(Entity.entity(object, MediaType.APPLICATION_JSON_TYPE));
    if (putResponse.getStatus() != Response.Status.OK.getStatusCode()) {
      Logger.error(
          "PUT call to "
              + url
              + "/"
              + resourcePath
              + " returned status of "
              + putResponse.getStatus());
      return null;
    }

    if (responseClass != null
        && putResponse.hasEntity()
        && putResponse.getStatus() == Response.Status.OK.getStatusCode())
      return putResponse.readEntity(responseClass);
    return null;
  }
  public static void main(String[] args) {

    URI uriAmazon =
        UriBuilder.fromUri("http://free.apisigning.com/onca/xml")
            .queryParam("Service", "AWSECommerceService")
            .queryParam("AWSAccessKeyId", "AKIAIYNLC7WME6YSY66A")
            .build();
    URI uriSearch = UriBuilder.fromUri(uriAmazon).queryParam("Operation", "ItemSearch").build();
    URI uriSearchBooks = UriBuilder.fromUri(uriSearch).queryParam("SearchIndex", "Books").build();
    Client client = ClientBuilder.newClient();

    URI uriSearchBooksByKeyword =
        UriBuilder.fromUri(uriSearchBooks).queryParam("Keywords", "Java EE 7").build();
    URI uriSearchBooksWithImages =
        UriBuilder.fromUri(uriSearchBooks)
            .queryParam("Condition", "All")
            .queryParam("ResponseGroup", "Images")
            .queryParam("Title", "Java EE 7")
            .build();

    System.out.println(uriSearchBooksByKeyword.toString());
    System.out.println(uriSearchBooksWithImages.toString());

    Response response = client.target(uriSearchBooksByKeyword).request().get();
    System.out.println(response.getStatus());
    response = client.target(uriSearchBooksWithImages).request().get();
    System.out.println(response.getStatus());
  }
  public String uploadImage(Part file) throws IOException {
    String imageURL = null;
    final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();
    final StreamDataBodyPart stream = new StreamDataBodyPart("file", file.getInputStream());
    FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
    final MultiPart multiPart =
        formDataMultiPart.field("fileName", file.getSubmittedFileName()).bodyPart(stream);
    if (multiPart instanceof FormDataMultiPart) {
      final FormDataMultiPart dataMultiPart = (FormDataMultiPart) multiPart;
      final WebTarget target = client.target(configuration.getFileUploadServiceEP());
      LOGGER.info("Connecting to file service on " + configuration.getFileUploadServiceEP());
      final Response response =
          target
              .request()
              .header(LoginBean.X_JWT_ASSERTION, getJWTToken())
              .post(Entity.entity(dataMultiPart, dataMultiPart.getMediaType()));
      LOGGER.info("Returned from file service " + configuration.getFileUploadServiceEP());
      if (Response.Status.OK.getStatusCode() == response.getStatus()) {
        imageURL = response.readEntity(String.class);
      } else {
        LOGGER.log(
            Level.SEVERE,
            "TXN service return code is  "
                + response.getStatus()
                + " , "
                + "hence can't proceed with the response");
      }
      formDataMultiPart.close();
      dataMultiPart.close();
      return imageURL;
    }

    return imageURL;
  }
  public static <T> T post(Object requestObject, Class<T> responseClass, String path) {
    try {

      jerseyWebTarget.path(path);

      Response response =
          jerseyWebTarget
              .request(MediaType.APPLICATION_JSON_TYPE)
              .post(Entity.entity(requestObject, MediaType.APPLICATION_JSON_TYPE));

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

      System.out.println("Output from Service for path " + path + " .... \n");
      T output = response.readEntity(responseClass);
      System.out.println(ToStringBuilder.reflectionToString(output));

      return output;
    } catch (Exception e) {

      e.printStackTrace();
      return null;
    }
  }
  @Test
  public void testBadRegistrationOfDataCenterInfo() throws Exception {
    try {
      // test 400 when configured to return client error
      ConfigurationManager.getConfigInstance()
          .setProperty("eureka.experimental.registration.validation.dataCenterInfoId", "true");
      InstanceInfo instanceInfo = spy(InstanceInfoGenerator.takeOne());
      when(instanceInfo.getDataCenterInfo()).thenReturn(new TestDataCenterInfo());
      Response response = applicationResource.addInstance(instanceInfo, false + "");
      assertThat(response.getStatus(), is(400));

      // test backfill of data for AmazonInfo
      ConfigurationManager.getConfigInstance()
          .setProperty("eureka.experimental.registration.validation.dataCenterInfoId", "false");
      instanceInfo = spy(InstanceInfoGenerator.takeOne());
      assertThat(instanceInfo.getDataCenterInfo(), instanceOf(AmazonInfo.class));
      ((AmazonInfo) instanceInfo.getDataCenterInfo())
          .getMetadata()
          .remove(AmazonInfo.MetaDataKey.instanceId.getName()); // clear the Id
      response = applicationResource.addInstance(instanceInfo, false + "");
      assertThat(response.getStatus(), is(204));

    } finally {
      ConfigurationManager.getConfigInstance()
          .clearProperty("eureka.experimental.registration.validation.dataCenterInfoId");
    }
  }
  @Test
  public void testException() throws Exception {
    LocalAtlasClient atlasClient = new LocalAtlasClient(serviceState, entityResource);

    Response response = mock(Response.class);
    when(entityResource.submit(any(HttpServletRequest.class)))
        .thenThrow(new WebApplicationException(response));
    when(response.getEntity())
        .thenReturn(
            new JSONObject() {
              {
                put("stackTrace", "stackTrace");
              }
            });
    when(response.getStatus()).thenReturn(Response.Status.BAD_REQUEST.getStatusCode());
    try {
      atlasClient.createEntity(new Referenceable(random()));
      fail("Expected AtlasServiceException");
    } catch (AtlasServiceException e) {
      assertEquals(e.getStatus(), ClientResponse.Status.BAD_REQUEST);
    }

    when(entityResource.updateByUniqueAttribute(
            anyString(), anyString(), anyString(), any(HttpServletRequest.class)))
        .thenThrow(new WebApplicationException(response));
    when(response.getStatus()).thenReturn(Response.Status.NOT_FOUND.getStatusCode());
    try {
      atlasClient.updateEntity(random(), random(), random(), new Referenceable(random()));
      fail("Expected AtlasServiceException");
    } catch (AtlasServiceException e) {
      assertEquals(e.getStatus(), ClientResponse.Status.NOT_FOUND);
    }
  }
  public void sendDeliveryReceipt(
      String source, long sourceDeviceId, String destination, long messageId) throws IOException {
    Response response = null;

    try {
      response =
          client
              .target(peer.getUrl())
              .path(String.format(RECEIPT_PATH, source, sourceDeviceId, destination, messageId))
              .request()
              .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true)
              .put(Entity.entity("", MediaType.APPLICATION_JSON_TYPE));

      if (response.getStatus() != 200 && response.getStatus() != 204) {
        if (response.getStatus() == 411)
          throw new WebApplicationException(Response.status(413).build());
        else throw new WebApplicationException(Response.status(response.getStatusInfo()).build());
      }
    } catch (ProcessingException e) {
      logger.warn("sendMessage", e);
      throw new IOException(e);
    } finally {
      if (response != null) response.close();
    }
  }
  private void onException(Throwable e, Response r, boolean mapped) {
    if (request.isTracingEnabled()) {
      Response.Status s = Response.Status.fromStatusCode(r.getStatus());
      if (s != null) {
        request.trace(
            String.format(
                "mapped exception to response: %s -> %d (%s)",
                ReflectionHelper.objectToString(e), r.getStatus(), s.getReasonPhrase()));
      } else {
        request.trace(
            String.format(
                "mapped exception to response: %s -> %d",
                ReflectionHelper.objectToString(e), r.getStatus()));
      }
    }

    if (!mapped && r.getStatus() >= 500) {
      logException(e, r, Level.SEVERE);
    } else if (LOGGER.isLoggable(Level.FINE)) {
      logException(e, r, Level.FINE);
    }

    setResponse(r);

    this.mappedThrowable = e;

    if (getEntity() != null && getHttpHeaders().getFirst(HttpHeaders.CONTENT_TYPE) == null) {
      Object m = request.getProperties().get(HttpMethodRule.CONTENT_TYPE_PROPERTY);
      if (m != null) {
        request.getProperties().remove(HttpMethodRule.CONTENT_TYPE_PROPERTY);
        getHttpHeaders().putSingle(HttpHeaders.CONTENT_TYPE, m);
      }
    }
  }
  private static void pedirEstadisticas() {

    System.out.println("Solicitando saldos al server");
    Client client = ClientBuilder.newClient();
    WebTarget target =
        client.target("http://localhost:8080").path("/tp2/apirest/calcular/estadisticas");

    Response response = target.request().get();

    if (response.getStatus() != 200) {
      System.out.println("ERROR - Al solicitar estadísticas - status: " + response.getStatus());
    }
    List<Estadistica> estadisticas = (List<Estadistica>) response.getEntity();
    System.out.println("Se obtuvieron " + estadisticas.size() + " estadísticas");

    for (Estadistica estaditica : estadisticas) {

      System.out.println(
          "UUID: "
              + estaditica.getUuid()
              + " - Créditos: "
              + estaditica.getCreditos()
              + " - Débitos: "
              + estaditica.getDebitos());
    }

    System.out.println("Fin de pedido de estdísticas");
  }
  @Test
  public void UpdateIfMatch() {
    EntityTag entityTag = target("books").path(book1_id).request().get().getEntityTag();

    HashMap<String, Object> updates = new HashMap<String, Object>();
    updates.put("author", "updatedAuthor");
    Entity<HashMap<String, Object>> updateEntity =
        Entity.entity(updates, MediaType.APPLICATION_JSON);
    Response updateResponse =
        target("books")
            .path(book1_id)
            .request()
            .header("If-Match", entityTag)
            .build("PATCH", updateEntity)
            .invoke();

    assertEquals(200, updateResponse.getStatus());

    Response updateResponse2 =
        target("books")
            .path(book1_id)
            .request()
            .header("If-Match", entityTag)
            .build("PATCH", updateEntity)
            .invoke();

    assertEquals(412, updateResponse2.getStatus());
  }
  @Test
  public void testPostEmployee() {
    if (null == cookie) {
      fail("cannot login!!!");
    }
    Employee ep1 = generateEmployee();

    try {
      ResteasyClient client = new ResteasyClientBuilder().build();

      WebTarget target = client.target(baseUrl + "/rest/ag/employee");
      client.register(new CookieRequestFilter(cookie));

      Response response = target.request().post(Entity.entity(ep1, "application/json"));

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

      Employee value = response.readEntity(Employee.class);
      System.out.println("Server response : \n");
      System.out.println(value.toString());

      assertEquals("same first name", "Special", value.getFirstName());

      client.close();

    } catch (Exception e) {

      e.printStackTrace();
    }
  }
Exemple #25
0
 @Test
 public void testPostFailUniquePK() throws IOException, SQLException {
   Entity<String> entity = Entity.json(getJson("Row"));
   Response response = target(path).request().post(entity);
   assertEquals(204, response.getStatus());
   response = target(path).request().post(entity);
   assertEquals(500, response.getStatus());
 }
  @Test
  public void testOdata() throws Exception {
    String vdb =
        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
            + "<vdb name=\"Loopy\" version=\"1\">\n"
            + "    <model name=\"MarketData\">\n"
            + "        <source name=\"text-connector2\" translator-name=\"loopback\" />\n"
            + "         <metadata type=\"DDL\"><![CDATA[\n"
            + "                CREATE FOREIGN TABLE G1 (e1 string, e2 integer PRIMARY KEY);\n"
            + "                CREATE FOREIGN TABLE G2 (e1 string, e2 integer PRIMARY KEY) OPTIONS (UPDATABLE 'true');\n"
            + "        ]]> </metadata>\n"
            + "    </model>\n"
            + "</vdb>";

    admin.deploy(
        "loopy-vdb.xml", new ReaderInputStream(new StringReader(vdb), Charset.forName("UTF-8")));

    assertTrue(AdminUtil.waitForVDBLoad(admin, "Loopy", 1, 3));

    WebClient client =
        WebClient.create("http://*****:*****@mm://localhost:31000;user=user;password=user", null);

    PreparedStatement ps =
        conn.prepareCall(
            "select t.* from xmltable('/*:Edmx/*:DataServices/*:Schema[@Alias=\"MarketData\"]' passing xmlparse(document cast(? as clob))) as t");
    ps.setAsciiStream(1, (InputStream) response.getEntity());

    ResultSet rs = ps.executeQuery();
    rs.next();

    assertEquals(
        ObjectConverterUtil.convertFileToString(
            UnitTestUtil.getTestDataFile("loopy-metadata4-results.txt")),
        rs.getString(1));

    conn.close();

    // try an invalid url
    client = WebClient.create("http://localhost:8080/odata/x/y$metadata");
    client.header(
        "Authorization",
        "Basic " + Base64.encodeBytes(("user:user").getBytes())); // $NON-NLS-1$ //$NON-NLS-2$
    response = client.invoke("GET", null);
    assertEquals(500, response.getStatus());

    admin.undeploy("loopy-vdb.xml");
  }
  @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 #28
0
  public void testPie1() {
    try {

      String url = baseURL + "/rest/Pie/search;id=*/utensilCollection";

      WebClient client = WebClient.create(url);
      client.type("application/xml").accept("application/xml");
      Response response = client.get();

      if (response.getStatus() == Status.NOT_ACCEPTABLE.getStatusCode()) {
        InputStream is = (InputStream) response.getEntity();
        org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false);
        org.jdom.Document jDoc = builder.build(is);
        assertEquals(jDoc.getRootElement().getName(), "response");
      } else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
        InputStream is = (InputStream) response.getEntity();
        org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false);
        org.jdom.Document jDoc = builder.build(is);
        assertEquals(jDoc.getRootElement().getName(), "response");
      } else if (response.getStatus() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
      }

      File myFile = new File("Pie_Search" + "XML.xml");
      System.out.println("writing data to file " + myFile.getAbsolutePath());
      FileWriter myWriter = new FileWriter(myFile);

      BufferedReader br =
          new BufferedReader(new InputStreamReader(((InputStream) response.getEntity())));

      String output;
      System.out.println("Output from Server .... \n");
      while ((output = br.readLine()) != null) {
        myWriter.write(output);
        System.out.println(output);
      }

      myWriter.flush();
      myWriter.close();

    } catch (Exception e) {
      e.printStackTrace();
      ResponseBuilder builder = Response.status(Status.INTERNAL_SERVER_ERROR);
      builder.type("application/xml");
      StringBuffer buffer = new StringBuffer();
      buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
      buffer.append("<response>");
      buffer.append("<type>ERROR</type>");
      buffer.append("<code>INTERNAL_ERROR_4</code>");
      buffer.append("<message>Failed to Query due to: " + e.getMessage() + "</message>");
      buffer.append("</response>");
      builder.entity(buffer.toString());
      throw new WebApplicationException(builder.build());
    }
  }
Exemple #29
0
  private void assertIfNoneMatchFailed(String method, ResponseBuilder responseBuilder) {
    Assert.assertNotNull(responseBuilder, "Expected a response builder");
    Response response = responseBuilder.build();

    // not modified only applies to GET and HEAD; otherwise it is a precondition failed
    if ("GET".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method)) {
      Assert.assertEquals(response.getStatus(), Status.NOT_MODIFIED.getStatusCode());
    } else {
      Assert.assertEquals(response.getStatus(), Status.PRECONDITION_FAILED.getStatusCode());
    }
  }
 /** {@inheritDoc} */
 public void deleteProperty(String name) {
   Util.assertHasLength(name);
   Response cRes = getStore().path(name).request().delete();
   if (Status.NOT_FOUND.getStatusCode() == cRes.getStatus()) {
     throw new PropertyNotFoundException(name);
   }
   if (Status.NO_CONTENT.getStatusCode() != cRes.getStatus()) {
     throw new PropertyAccessException(
         "Cannot delete property, an HTTP error " + cRes.getStatus() + " occured.");
   }
 }