Esempio n. 1
0
  /**
   * Further addresses the use of EJBs as JAX-RS components.
   *
   * @throws Exception
   */
  @Test
  public void testAsJaxRSResource() throws Exception {
    log.info("entering testAsJaxRSResource()");

    // Create book.
    ClientRequest request = new ClientRequest("http://localhost:8080/resteasy-ejb-test/create/");
    Book book1 = new Book("RESTEasy: the Sequel");
    request.body(Constants.MEDIA_TYPE_TEST_XML, book1);
    ClientResponse<?> response = request.post();
    log.info("Status: " + response.getStatus());
    assertEquals(200, response.getStatus());
    int id1 = response.getEntity(int.class);
    log.info("id: " + id1);
    Assert.assertEquals(Counter.INITIAL_VALUE, id1);

    // Create another book.
    request = new ClientRequest("http://localhost:8080/resteasy-ejb-test/create/");
    Book book2 = new Book("RESTEasy: It's Alive");
    request.body(Constants.MEDIA_TYPE_TEST_XML, book2);
    response = request.post();
    log.info("Status: " + response.getStatus());
    assertEquals(200, response.getStatus());
    int id2 = response.getEntity(int.class);
    log.info("id: " + id2);
    Assert.assertEquals(Counter.INITIAL_VALUE + 1, id2);

    // Retrieve first book.
    request = new ClientRequest("http://localhost:8080/resteasy-ejb-test/book/" + id1);
    request.accept(Constants.MEDIA_TYPE_TEST_XML);
    response = request.get();
    log.info("Status: " + response.getStatus());
    assertEquals(200, response.getStatus());
    Book result = response.getEntity(Book.class);
    log.info("book: " + book1);
    Assert.assertEquals(book1, result);

    // Retrieve second book.
    request = new ClientRequest("http://localhost:8080/resteasy-ejb-test/book/" + id2);
    request.accept(Constants.MEDIA_TYPE_TEST_XML);
    response = request.get();
    log.info("Status: " + response.getStatus());
    assertEquals(200, response.getStatus());
    result = response.getEntity(Book.class);
    log.info("book: " + book2);
    Assert.assertEquals(book2, result);

    // Verify that EJBBookReader and EJBBookWriter have been used, twice on each side.
    request = new ClientRequest("http://localhost:8080/resteasy-ejb-test/uses/4");
    response = request.get();
    log.info("Status: " + response.getStatus());
    assertEquals(200, response.getStatus());
    response.releaseConnection();

    // Reset counter.
    request = new ClientRequest("http://localhost:8080/resteasy-ejb-test/reset");
    response = request.get();
    log.info("Status: " + response.getStatus());
    assertEquals(204, response.getStatus());
    response.releaseConnection();
  }
Esempio n. 2
0
 /**
  * Verify that EJBBookReader and EJBBookWriterImpl are correctly injected into EJBBookResource.
  *
  * @throws Exception
  */
 @Test
 public void testVerifyInjectionJaxRs() throws Exception {
   log.info("starting testVerifyInjectionJaxRs()");
   ClientRequest request =
       new ClientRequest("http://localhost:8080/resteasy-ejb-test/verifyInjection/");
   ClientResponse<?> response = request.get();
   log.info("result: " + response.getEntity(Integer.class));
   assertEquals(200, response.getStatus());
   assertEquals(200, response.getEntity(Integer.class).intValue());
 }
Esempio n. 3
0
  // @Test
  public void testInheritance() throws Exception {
    ResteasyDeployment dep = deployment;
    ClientRequest request = new ClientRequest(generateURL("/datacenters/1"));
    ClientResponse res = request.get();
    Assert.assertEquals(200, res.getStatus());
    DataCenter dc = (DataCenter) res.getEntity(DataCenter.class);
    Assert.assertEquals(dc.getName(), "Bill");
    request = new ClientRequest(generateURL("/datacenters/1"));

    res = request.body("application/xml", dc).put();
    Assert.assertEquals(200, res.getStatus());
    dc = (DataCenter) res.getEntity(DataCenter.class);
    Assert.assertEquals(dc.getName(), "Bill");
  }
Esempio n. 4
0
 /**
  * Gets a list of custom deployers from the dtgov server.
  *
  * @throws DtgovApiClientException
  */
 @SuppressWarnings({"unchecked", "rawtypes"})
 public List<Deployer> getCustomDeployers() throws DtgovApiClientException {
   try {
     String url =
         String.format("%1$s/system/config/deployers/custom", this.endpoint); // $NON-NLS-1$
     ClientRequest request = createClientRequest(url);
     request.accept(MediaType.APPLICATION_XML);
     ClientResponse<List> response = request.get(new GenericType<List<Deployer>>() {});
     response.getEntity();
     List<Deployer> deployers = response.getEntity();
     return deployers;
   } catch (Throwable e) {
     throw new DtgovApiClientException(e);
   }
 }
 private void checkResponse(ClientResponse<?> responseObj) throws Exception {
   ClientResponse<?> test = BaseClientResponse.copyFromError(responseObj);
   responseObj.resetStream();
   if (test.getResponseStatus() == javax.ws.rs.core.Response.Status.BAD_REQUEST) {
     throw new BadRequestException(test.getEntity(String.class));
   } else if (test.getResponseStatus() != javax.ws.rs.core.Response.Status.OK) {
     throw new Exception(
         "Request operation failed. Response status = "
             + test.getResponseStatus()
             + "\n\n"
             + test.getEntity(String.class));
   } else {
     logger.debug("Response: " + test.getEntity(String.class));
   }
 }
Esempio n. 6
0
 /**
  * Handles the possibility of an error found in the response.
  *
  * @param response
  * @throws Exception
  */
 private <T> void handlePotentialServerError(ClientResponse<T> response) throws Exception {
   String contentType =
       String.valueOf(response.getMetadata().getFirst(HttpHeaderNames.CONTENT_TYPE));
   if (response.getStatus() == 500) {
     Exception error = new Exception(Messages.i18n.format("UNKNOWN_SRAMP_ERROR")); // $NON-NLS-1$
     if (MediaType.APPLICATION_SRAMP_ATOM_EXCEPTION.equals(contentType)) {
       try {
         SrampAtomException entity = response.getEntity(SrampAtomException.class);
         if (entity != null) error = entity;
       } catch (Throwable t) {
         t.printStackTrace();
       }
     }
     throw error;
   }
   if (response.getStatus() == 404 || response.getStatus() == 415) {
     SrampAtomException error =
         new SrampAtomException(Messages.i18n.format("ENDPOINT_NOT_FOUND")); // $NON-NLS-1$
     throw error;
   }
   if (response.getStatus() == 403) {
     SrampAtomException error =
         new SrampAtomException(Messages.i18n.format("AUTHORIZATION_FAILED")); // $NON-NLS-1$
     throw error;
   }
   if (response.getStatus() == 401) {
     SrampAtomException error =
         new SrampAtomException(Messages.i18n.format("AUTHENTICATION_FAILED")); // $NON-NLS-1$
     throw error;
   }
 }
  @Test
  @RunAsClient
  public void putJsonProjectIteration() throws Exception {
    final ProjectIteration newIteration = new ProjectIteration("new-iteration");

    new ResourceRequest(
        getRestEndpointUrl("/projects/p/sample-project/iterations/i/" + newIteration.getId()),
        "PUT",
        getAuthorizedEnvironment()) {
      @Override
      protected void prepareRequest(ClientRequest request) {
        request.body(
            MediaTypes.APPLICATION_ZANATA_PROJECT_ITERATION_JSON, jsonMarshal(newIteration));
      };

      @Override
      protected void onResponse(ClientResponse response) {
        assertThat(response.getStatus(), is(Status.CREATED.getStatusCode())); // 201
      }
    }.run();

    // Retreive it again
    IProjectIterationResource iterationClient =
        super.createProxy(
            createClientProxyFactory(TRANSLATOR, TRANSLATOR_KEY),
            IProjectIterationResource.class,
            "/projects/p/sample-project/iterations/i/" + newIteration.getId());

    ClientResponse<ProjectIteration> getResponse = iterationClient.get();

    assertThat(getResponse.getStatus(), is(Status.OK.getStatusCode())); // 200

    ProjectIteration it = getResponse.getEntity();
    assertThat(it.getId(), is("new-iteration"));
  }
  /**
   * Creates a WSDL artifact in the s-ramp repository.
   *
   * @return the new artifact
   * @throws Exception
   */
  private XmlDocument createXmlArtifact() throws Exception {
    String artifactFileName = "PO.xml";
    InputStream contentStream =
        this.getClass().getResourceAsStream("/sample-files/core/" + artifactFileName);
    try {
      ClientRequest request = clientRequest("/s-ramp/core/XmlDocument");
      request.header("Slug", artifactFileName);
      request.body("application/xml", contentStream);

      ClientResponse<Entry> response = request.post(Entry.class);

      Entry entry = response.getEntity();
      Assert.assertEquals(artifactFileName, entry.getTitle());
      BaseArtifactType arty = ArtificerAtomUtils.unwrapSrampArtifact(entry);
      Assert.assertTrue(arty instanceof XmlDocument);
      XmlDocument doc = (XmlDocument) arty;
      Assert.assertEquals(artifactFileName, doc.getName());
      Long size = doc.getContentSize();
      Assert.assertTrue(size >= 825L);
      Assert.assertEquals("application/xml", doc.getContentType());
      return doc;
    } finally {
      IOUtils.closeQuietly(contentStream);
    }
  }
  private JaxbCommandResponse<?> executeTaskCommand(String deploymentId, Command<?> command)
      throws Exception {
    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(command);

    String urlString =
        new URL(
                deploymentUrl,
                deploymentUrl.getPath() + "rest/runtime/" + DEPLOYMENT_ID + "/execute")
            .toExternalForm();
    logger.info("Client request to: " + urlString);
    ClientRequest restRequest = new ClientRequest(urlString);

    JaxbCommandsRequest commandMessage = new JaxbCommandsRequest(commands);
    assertNotNull("Commands are null!", commandMessage.getCommands());
    assertTrue("Commands are empty!", commandMessage.getCommands().size() > 0);

    String body = JaxbSerializationProvider.convertJaxbObjectToString(commandMessage);
    restRequest.body(MediaType.APPLICATION_XML, body);

    ClientResponse<JaxbCommandsResponse> responseObj = restRequest.post(JaxbCommandsResponse.class);
    checkResponse(responseObj);

    JaxbCommandsResponse cmdsResp = responseObj.getEntity();
    return cmdsResp.getResponses().get(0);
  }
 @Test
 public void testAsync() throws Exception {
   ClientRequest request = new ClientRequest("http://localhost:8080/");
   ClientResponse<String> response = request.get(String.class);
   Assert.assertEquals(200, response.getStatus());
   Assert.assertEquals("hello", response.getEntity());
 }
  @Test
  public void testFailure() throws Exception {
    try {
      String testName = "testFailure";
      startup();
      deployTopic(testName);

      ClientRequest request = new ClientRequest(generateURL("/topics/" + testName));

      ClientResponse<?> response = request.head();
      response.releaseConnection();
      Assert.assertEquals(200, response.getStatus());
      Link sender =
          MessageTestBase.getLinkByTitle(
              manager.getQueueManager().getLinkStrategy(), response, "create");
      System.out.println("create: " + sender);
      Link pushSubscriptions =
          MessageTestBase.getLinkByTitle(
              manager.getQueueManager().getLinkStrategy(), response, "push-subscriptions");
      System.out.println("push subscriptions: " + pushSubscriptions);

      PushTopicRegistration reg = new PushTopicRegistration();
      reg.setDurable(true);
      XmlLink target = new XmlLink();
      target.setHref("http://localhost:3333/error");
      target.setRelationship("uri");
      reg.setTarget(target);
      reg.setDisableOnFailure(true);
      reg.setMaxRetries(3);
      reg.setRetryWaitMillis(10);
      response = pushSubscriptions.request().body("application/xml", reg).post();
      Assert.assertEquals(201, response.getStatus());
      Link pushSubscription = response.getLocationLink();
      response.releaseConnection();

      ClientResponse<?> res = sender.request().body("text/plain", Integer.toString(1)).post();
      res.releaseConnection();
      Assert.assertEquals(201, res.getStatus());

      Thread.sleep(5000);

      response = pushSubscription.request().get();
      PushTopicRegistration reg2 = response.getEntity(PushTopicRegistration.class);
      response.releaseConnection();
      Assert.assertEquals(reg.isDurable(), reg2.isDurable());
      Assert.assertEquals(reg.getTarget().getHref(), reg2.getTarget().getHref());
      Assert.assertFalse(reg2.isEnabled());
      response.releaseConnection();

      String destination = reg2.getDestination();
      ClientSession session =
          manager.getQueueManager().getSessionFactory().createSession(false, false, false);
      ClientSession.QueueQuery query = session.queueQuery(new SimpleString(destination));
      Assert.assertFalse(query.isExists());

      manager.getQueueManager().getPushStore().removeAll();
    } finally {
      shutdown();
    }
  }
 public <T> T execute(Command<T> command) {
   ClientRequest restRequest = new ClientRequest(url);
   try {
     restRequest.body(MediaType.APPLICATION_XML, new JaxbCommandsRequest(deploymentId, command));
     ClientResponse<Object> response = restRequest.post(Object.class);
     if (response.getResponseStatus() == Status.OK) {
       JaxbCommandsResponse commandResponse = response.getEntity(JaxbCommandsResponse.class);
       List<JaxbCommandResponse<?>> responses = commandResponse.getResponses();
       if (responses.size() == 0) {
         return null;
       } else if (responses.size() == 1) {
         JaxbCommandResponse<?> responseObject = responses.get(0);
         if (responseObject instanceof JaxbExceptionResponse) {
           JaxbExceptionResponse exceptionResponse = (JaxbExceptionResponse) responseObject;
           String causeMessage = exceptionResponse.getCauseMessage();
           throw new RuntimeException(
               exceptionResponse.getMessage()
                   + (causeMessage == null ? "" : " Caused by: " + causeMessage));
         } else {
           return (T) responseObject.getResult();
         }
       } else {
         throw new RuntimeException("Unexpected number of results: " + responses.size());
       }
     } else {
       // TODO error handling
       throw new RuntimeException("REST request error code " + response.getResponseStatus());
     }
   } catch (Exception e) {
     throw new RuntimeException("Unable to execute REST request: " + e.getMessage(), e);
   }
 }
 private JsonNode sendRequest() throws Exception {
   final ClientRequest clientRequest = new ClientRequest(SEARCH_URI);
   // For capturing Response
   final ClientResponse<String> clientResponse = clientRequest.get(String.class);
   // Collecting response in JsonNode
   final JsonNode jsonReply = new ObjectMapper().readTree(clientResponse.getEntity());
   return jsonReply;
 }
  @Test
  public void testGetCustomerByIdUsingClientRequest() throws Exception {
    // deploymentUrl = new URL("http://localhost:8180/test/");
    // GET http://localhost:8080/test/rest/customer/1
    ClientRequest request =
        new ClientRequest(deploymentUrl.toString() + RESOURCE_PREFIX + "/customer/1");
    request.header("Accept", MediaType.APPLICATION_XML);

    // we're expecting a String back
    ClientResponse<String> responseObj = request.get(String.class);

    Assert.assertEquals(200, responseObj.getStatus());
    System.out.println("GET /customer/1 HTTP/1.1\n\n" + responseObj.getEntity());

    String response = responseObj.getEntity().replaceAll("<\\?xml.*\\?>", "").trim();
    Assert.assertEquals("<customer><id>1</id><name>Acme Corporation</name></customer>", response);
  }
  @Test
  public void testRestUrlStartHumanTaskProcess() throws Exception {
    // create REST request
    String urlString =
        new URL(
                deploymentUrl,
                deploymentUrl.getPath() + "rest/runtime/test/process/org.jbpm.humantask/start")
            .toExternalForm();
    ClientRequest restRequest = new ClientRequest(urlString);

    // Get and check response
    logger.debug(">> [org.jbpm.humantask/start]" + urlString);
    ClientResponse responseObj = restRequest.post();
    assertEquals(200, responseObj.getStatus());
    JaxbProcessInstanceResponse processInstance =
        (JaxbProcessInstanceResponse) responseObj.getEntity(JaxbProcessInstanceResponse.class);
    long procInstId = processInstance.getId();

    urlString =
        new URL(deploymentUrl, deploymentUrl.getPath() + "rest/task/query?taskOwner=" + USER_ID)
            .toExternalForm();
    restRequest = new ClientRequest(urlString);
    logger.debug(">> [task/query]" + urlString);
    responseObj = restRequest.get();
    assertEquals(200, responseObj.getStatus());

    JaxbTaskSummaryListResponse taskSumlistResponse =
        (JaxbTaskSummaryListResponse) responseObj.getEntity(JaxbTaskSummaryListResponse.class);
    long taskId = findTaskId(procInstId, taskSumlistResponse.getResult());

    urlString =
        new URL(
                deploymentUrl,
                deploymentUrl.getPath() + "rest/task/" + taskId + "/start?userId=" + USER_ID)
            .toExternalForm();
    restRequest = new ClientRequest(urlString);

    // Get response
    logger.debug(">> [task/?/start] " + urlString);
    responseObj = restRequest.post();

    // Check response
    checkResponse(responseObj);
  }
  // Success outcomes
  @Test(
      dataProvider = "testName",
      dataProviderClass = AbstractServiceTestImpl.class,
      dependsOnMethods = {"createIntakeWithAuthRefs"})
  public void readAndCheckAuthRefDocs(String testName) throws Exception {
    // Perform setup.
    testSetup(STATUS_OK, ServiceRequestType.READ);

    // Get the auth ref docs and check them
    OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
    ClientResponse<AuthorityRefDocList> refDocListResp =
        orgAuthClient.getReferencingObjects(orgAuthCSID, currentOwnerOrgCSID);
    AuthorityRefDocList list = null;
    try {
      assertStatusCode(refDocListResp, testName);
      list = refDocListResp.getEntity();
      Assert.assertNotNull(list);
    } finally {
      if (refDocListResp != null) {
        refDocListResp.releaseConnection();
      }
    }

    // Optionally output additional data about list members for debugging.
    boolean iterateThroughList = true;
    int nIntakesFound = 0;
    if (iterateThroughList && logger.isDebugEnabled()) {
      List<AuthorityRefDocList.AuthorityRefDocItem> items = list.getAuthorityRefDocItem();
      int i = 0;
      logger.debug(testName + ": Docs that use: " + currentOwnerRefName);
      for (AuthorityRefDocList.AuthorityRefDocItem item : items) {
        logger.debug(
            testName
                + ": list-item["
                + i
                + "] "
                + item.getDocType()
                + "("
                + item.getDocId()
                + ") Name:["
                + item.getDocName()
                + "] Number:["
                + item.getDocNumber()
                + "] in field:["
                + item.getSourceField()
                + "]");
        if (knownIntakeId.equalsIgnoreCase(item.getDocId())) {
          nIntakesFound++;
        }
        i++;
      }
      //
      Assert.assertTrue((nIntakesFound == 2), "Did not find Intake (twice) with authref!");
    }
  }
  @Test
  public void testRestHistoryLogs() throws Exception {
    String urlString =
        new URL(
                deploymentUrl,
                deploymentUrl.getPath() + "rest/runtime/test/process/var-proc/start?map_x=initVal")
            .toExternalForm();
    ClientRequest restRequest = new ClientRequest(urlString);

    // Get and check response
    logger.debug(">> " + urlString);
    ClientResponse responseObj = restRequest.post();
    assertEquals(200, responseObj.getStatus());
    JaxbProcessInstanceResponse processInstance =
        (JaxbProcessInstanceResponse) responseObj.getEntity(JaxbProcessInstanceResponse.class);
    long procInstId = processInstance.getId();

    urlString =
        new URL(
                deploymentUrl,
                deploymentUrl.getPath()
                    + "rest/runtime/test/history/instance/"
                    + procInstId
                    + "/variable/x")
            .toExternalForm();
    restRequest = new ClientRequest(urlString);
    logger.debug(">> [history/variables]" + urlString);
    responseObj = restRequest.get();
    assertEquals(200, responseObj.getStatus());
    JaxbHistoryLogList logList =
        (JaxbHistoryLogList) responseObj.getEntity(JaxbHistoryLogList.class);
    List<AbstractJaxbHistoryObject> varLogList = logList.getHistoryLogList();
    assertEquals("Incorrect number of variable logs", 4, varLogList.size());

    for (AbstractJaxbHistoryObject<?> log : logList.getHistoryLogList()) {
      JaxbVariableInstanceLog varLog = (JaxbVariableInstanceLog) log;
      assertEquals("Incorrect variable id", "x", varLog.getVariableId());
      assertEquals("Incorrect process id", "var-proc", varLog.getProcessId());
      assertEquals("Incorrect process instance id", "var-proc", varLog.getProcessId());
    }
  }
  @Test
  public void showUser() {
    ObjectMapper m = new ObjectMapper();
    ObjectNode body = m.createObjectNode();

    ClientResponse<JsonNode> response =
        client.showUser(
            (String) properties.getProperty(PROPERTY_NAME_CKAN_AUTHORIZATION_KEY), body);
    if (response.getStatus() == Response.Status.OK.getStatusCode()) {
      log.info(response.getEntity().toString());
    }
  }
  @Ignore("needs mock connection to test with")
  @Test
  public void connect() {
    CandlepinConnection conn = new CandlepinConnection(new CandlepinCommonTestConfig());
    Credentials creds = new UsernamePasswordCredentials("admin", "admin");
    OwnerClient client = conn.connect(OwnerClient.class, creds, "http://localhost:8080/candlepin/");
    ClientResponse<Owner> resp = client.replicateOwner("admin");

    assertNotNull(resp);
    assertEquals(200, resp.getStatus());
    Owner o = resp.getEntity();
    assertNotNull(o);
    System.out.println(o);
  }
  @Test(dependsOnMethods = {"createCollectionObject"})
  public void updateCollectionObject() {
    ClientResponse<CollectionObject> res = collectionObjectClient.getCollectionObject(updateId);
    CollectionObject collectionObject = res.getEntity();
    verbose(
        "Got CollectionObject to update with ID: " + updateId,
        collectionObject,
        CollectionObject.class);

    // collectionObject.setCsid("updated-" + updateId);
    collectionObject.setObjectNumber("updated-" + collectionObject.getObjectNumber());
    collectionObject.setObjectName("updated-" + collectionObject.getObjectName());

    // make call to update service
    res = collectionObjectClient.updateCollectionObject(updateId, collectionObject);

    // check the response
    CollectionObject updatedCollectionObject = res.getEntity();
    Assert.assertEquals(updatedCollectionObject.getObjectName(), collectionObject.getObjectName());
    verbose("updateCollectionObject: ", updatedCollectionObject, CollectionObject.class);

    return;
  }
  @BeforeClass
  public static void deployServer() throws InterruptedException {
    System.out.println("server default charset: " + Charset.defaultCharset());
    Map<String, Charset> charsets = Charset.availableCharsets();
    Charset charset = null;
    for (Iterator<String> it = charsets.keySet().iterator(); it.hasNext(); ) {
      String cs = it.next();
      if (!cs.equals(Charset.defaultCharset().name())) {
        charset = charsets.get(cs);
        break;
      }
    }
    System.out.println("server using charset: " + charset);

    System.out.println(TestServerExpand.class.getCanonicalName());
    String separator = System.getProperty("file.separator");
    String classpath = System.getProperty("java.class.path");
    String path = System.getProperty("java.home") + separator + "bin" + separator + "java";
    System.out.println("classpath: " + classpath);
    System.out.println("path: " + path);
    ProcessBuilder processBuilder =
        new ProcessBuilder(path, "-cp", classpath, TestServerNoExpand.class.getCanonicalName());

    try {
      System.out.println("Starting server JVM");
      process = processBuilder.start();
      System.out.println("Started server JVM");
    } catch (IOException e1) {
      e1.printStackTrace();
    }

    ClientRequest request = new ClientRequest(generateURL("/junk"));
    ClientResponse<?> response = null;
    while (true) {
      try {
        response = request.get();
        if (response.getStatus() == 200) {
          System.out.println("Server started: " + response.getEntity(String.class));
          break;
        }
        System.out.println("Waiting on server ...");
      } catch (Exception e) {
        // keep trying
      }
      System.out.println("Waiting for server");
      Thread.sleep(1000);
    }
  }
Esempio n. 22
0
  /**
   * The purpose of this method is to run the external REST request.
   *
   * @param url The url of the RESTful service
   * @param mediaType The mediatype of the RESTful service
   */
  private String runRequest(String url, MediaType mediaType) {
    String result = null;

    System.out.println("===============================================");
    System.out.println("URL: " + url);
    System.out.println("MediaType: " + mediaType.toString());

    try {
      // Using the RESTEasy libraries, initiate a client request
      // using the url as a parameter
      ClientRequest request = new ClientRequest(url);

      // Be sure to set the mediatype of the request
      request.accept(mediaType);

      // Request has been made, now let's get the response
      ClientResponse<String> response = request.get(String.class);

      // Check the HTTP status of the request
      // HTTP 200 indicates the request is OK
      if (response.getStatus() != 200) {
        throw new RuntimeException("Failed request with HTTP status: " + response.getStatus());
      }

      // We have a good response, let's now read it
      BufferedReader br =
          new BufferedReader(
              new InputStreamReader(new ByteArrayInputStream(response.getEntity().getBytes())));

      // Loop over the br in order to print out the contents
      System.out.println("\n*** Response from Server ***\n");
      String output = null;
      while ((output = br.readLine()) != null) {
        System.out.println(output);
        result = output;
      }
    } catch (ClientProtocolException cpe) {
      System.err.println(cpe);
    } catch (IOException ioe) {
      System.err.println(ioe);
    } catch (Exception e) {
      System.err.println(e);
    }

    System.out.println("\n===============================================");

    return result;
  }
  @Test
  public void testContentType() throws Exception {
    String message =
        "--boo\r\n"
            + "Content-Disposition: form-data; name=\"foo\"\r\n"
            + "Content-Transfer-Encoding: 8bit\r\n\r\n"
            + "bar\r\n"
            + "--boo--\r\n";

    ClientRequest request = new ClientRequest(TEST_URI + "/mime");
    request.body("multipart/form-data; boundary=boo", message.getBytes());
    ClientResponse<String> response = request.post(String.class);
    Assert.assertEquals("Status code is wrong.", 20, response.getStatus() / 10);
    Assert.assertEquals(
        "Response text is wrong",
        MediaType.valueOf(TEXT_PLAIN_WITH_CHARSET_UTF_8),
        MediaType.valueOf(response.getEntity()));
  }
Esempio n. 24
0
 public Status doGet(String url, MediaType mediaType) throws Exception {
   ClientRequest request = createClientRequest(url);
   ClientResponse<String> result = null;
   try {
     if (mediaType != null) {
       request.accept(mediaType);
     }
     addParams(request);
     result = request.get(String.class);
     LOGGER.info("O servico '{}' respondeu com a seguinte mensagem: {}.", url, result.getEntity());
     return result.getResponseStatus();
   } catch (Exception e) {
     LOGGER.warn("Erro durante chamada ao metodo GET da URL: {}.", url, e);
     throw e;
   } finally {
     releaseConnection(result);
   }
 }
Esempio n. 25
0
 private Link consumeOrder(Order order, Link consumeNext) throws Exception {
   ClientResponse<?> response =
       consumeNext
           .request()
           .header("Accept-Wait", "4")
           .accept("application/xml")
           .post(String.class);
   Assert.assertEquals(200, response.getStatus());
   Assert.assertEquals(
       "application/xml", response.getHeaders().getFirst("Content-Type").toString().toLowerCase());
   Order order2 = (Order) response.getEntity(Order.class);
   Assert.assertEquals(order, order2);
   consumeNext =
       MessageTestBase.getLinkByTitle(
           manager.getQueueManager().getLinkStrategy(), response, "consume-next");
   Assert.assertNotNull(consumeNext);
   response.releaseConnection();
   return consumeNext;
 }
  public void retrieveCity() throws Exception {
    ClientRequest request = new ClientRequest("http://api.geonames.org/postalCodeSearchJSON");
    request.queryParameter("postalcode", order.getZip());
    request.queryParameter("country", "DE");
    request.queryParameter("username", "camunda");
    request.accept("application/json");
    ClientResponse<String> response = request.get(String.class);

    JSONObject jsonObject = new JSONObject(response.getEntity());
    JSONArray jsonArray = jsonObject.getJSONArray("postalCodes");

    if (jsonArray.length() == 0) {
      throw new BpmnError("CITY_NOT_FOUND");
    }

    String city = jsonArray.getJSONObject(0).getString("placeName");

    log.info("### city retrieved: " + city);

    order.setCity(city);
  }
Esempio n. 27
0
 public Status doPut(String url, MediaType mediaType) throws Exception {
   ClientRequest request = createClientRequest(url);
   ClientResponse<String> result = null;
   try {
     addParams(request);
     String type;
     if (mediaType != null) {
       LOGGER.info(String.format("Content-Type:%s", type = mediaType.toString()));
     } else {
       LOGGER.info(String.format("Content-Type:%s", type = "text/plain"));
     }
     addBody(request, type);
     result = request.put(String.class);
     LOGGER.info("O servico '{}' respondeu com a seguinte mensagem: {}.", url, result.getEntity());
     return result.getResponseStatus();
   } catch (Exception e) {
     LOGGER.warn("Erro durante chamada ao metodo PUT da URL: {}.", url, e);
     throw e;
   } finally {
     releaseConnection(result);
   }
 }
Esempio n. 28
0
 private <T> T doHttpMethod(String url, Class<T> clazz, MediaType accept, HTTPCommand<T> command) {
   ClientRequest request = createClientRequest(url);
   request.accept(accept);
   ClientResponse<T> result = null;
   try {
     addParams(request);
     result = command.execute(request, clazz);
     if (result.getResponseStatus() == Response.Status.OK
         || result.getResponseStatus() == Response.Status.ACCEPTED) {
       T entity;
       LOGGER.info(
           "O servico '{}' respondeu com a seguinte mensagem: {}",
           url,
           (entity = result.getEntity(clazz)).toString());
       return entity;
     }
   } catch (Exception e) {
     LOGGER.warn("Erro durante chamada na URL: {}.", url, e);
   } finally {
     releaseConnection(result);
   }
   return null;
 }
Esempio n. 29
0
  @Test
  public void testMetadata() throws Exception {
    TransformationMetadata metadata =
        RealMetadataFactory.fromDDL(
            ObjectConverterUtil.convertFileToString(UnitTestUtil.getTestDataFile("northwind.ddl")),
            "northwind",
            "nw");
    EdmDataServices eds = ODataEntitySchemaBuilder.buildMetadata(metadata.getMetadataStore());
    Client client = mock(Client.class);
    stub(client.getMetadataStore()).toReturn(metadata.getMetadataStore());
    stub(client.getMetadata()).toReturn(eds);
    MockProvider.CLIENT = client;

    StringWriter sw = new StringWriter();

    EdmxFormatWriter.write(eds, sw);

    ClientRequest request =
        new ClientRequest(TestPortProvider.generateURL("/odata/northwind/$metadata"));
    ClientResponse<String> response = request.get(String.class);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals(sw.toString(), response.getEntity());
  }
  @Test
  public void testSuccessFirst() throws Exception {
    String testName = "AutoAckTopicTest.testSuccessFirst";
    TopicDeployment deployment = new TopicDeployment();
    deployment.setDuplicatesAllowed(true);
    deployment.setDurableSend(false);
    deployment.setName(testName);
    manager.getTopicManager().deploy(deployment);

    ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/topics/" + testName));

    ClientResponse<?> response = request.head();
    response.releaseConnection();
    Assert.assertEquals(200, response.getStatus());
    Link sender = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "create");
    Link subscriptions =
        getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "pull-subscriptions");

    ClientResponse<?> res = subscriptions.request().post();
    res.releaseConnection();
    Assert.assertEquals(201, res.getStatus());
    Link sub1 = res.getLocationLink();
    Assert.assertNotNull(sub1);
    Link consumeNext1 =
        getLinkByTitle(manager.getTopicManager().getLinkStrategy(), res, "consume-next");
    Assert.assertNotNull(consumeNext1);
    System.out.println("consumeNext1: " + consumeNext1);

    res = subscriptions.request().post();
    res.releaseConnection();
    Assert.assertEquals(201, res.getStatus());
    Link sub2 = res.getLocationLink();
    Assert.assertNotNull(sub2);
    Link consumeNext2 =
        getLinkByTitle(manager.getTopicManager().getLinkStrategy(), res, "consume-next");
    Assert.assertNotNull(consumeNext2);
    System.out.println("consumeNext2: " + consumeNext2);

    res = sender.request().body("text/plain", "1").post();
    res.releaseConnection();
    Assert.assertEquals(201, res.getStatus());
    res = sender.request().body("text/plain", "2").post();
    res.releaseConnection();
    Assert.assertEquals(201, res.getStatus());

    res = consumeNext1.request().post(String.class);
    Assert.assertEquals(200, res.getStatus());
    Assert.assertEquals("1", res.getEntity(String.class));
    res.releaseConnection();
    consumeNext1 = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), res, "consume-next");

    res = consumeNext1.request().post(String.class);
    Assert.assertEquals(200, res.getStatus());
    Assert.assertEquals("2", res.getEntity(String.class));
    res.releaseConnection();
    consumeNext1 = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), res, "consume-next");

    res = consumeNext2.request().post(String.class);
    Assert.assertEquals(200, res.getStatus());
    Assert.assertEquals("1", res.getEntity(String.class));
    res.releaseConnection();
    consumeNext2 = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), res, "consume-next");

    res = consumeNext2.request().post(String.class);
    Assert.assertEquals(200, res.getStatus());
    Assert.assertEquals("2", res.getEntity(String.class));
    res.releaseConnection();
    consumeNext2 = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), res, "consume-next");
    Assert.assertEquals(204, sub1.request().delete().getStatus());
    Assert.assertEquals(204, sub2.request().delete().getStatus());
  }