@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"));
  }
 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);
   }
 }
 /**
  * Deletes all resources created by tests, after all tests have been run.
  *
  * <p>This cleanup method will always be run, even if one or more tests fail. For this reason, it
  * attempts to remove all resources created at any point during testing, even if some of those
  * resources may be expected to be deleted by certain tests.
  */
 @AfterClass(alwaysRun = true)
 public void cleanUp() {
   String noTest = System.getProperty("noTestCleanup");
   if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
     if (logger.isDebugEnabled()) {
       logger.debug("Skipping Cleanup phase ...");
     }
     return;
   }
   if (logger.isDebugEnabled()) {
     logger.debug("Cleaning up temporary resources created for testing ...");
   }
   IntakeClient intakeClient = new IntakeClient();
   // Note: Any non-success responses are ignored and not reported.
   for (String resourceId : intakeIdsCreated) {
     ClientResponse<Response> res = intakeClient.delete(resourceId);
     res.releaseConnection();
   }
   // Delete persons before PersonAuth
   OrgAuthorityClient personAuthClient = new OrgAuthorityClient();
   for (String resourceId : orgIdsCreated) {
     ClientResponse<Response> res = personAuthClient.deleteItem(orgAuthCSID, resourceId);
     res.releaseConnection();
   }
   if (orgAuthCSID != null) {
     personAuthClient.delete(orgAuthCSID).releaseConnection();
   }
 }
 @Test
 public void testTimeout() throws Exception {
   ClientRequest request = new ClientRequest("http://localhost:8080/timeout");
   ClientResponse<String> response = request.get(String.class);
   Assert.assertEquals(
       408, response.getStatus()); // exception mapper from another test overrides 503 to 408
 }
 @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 testSuccessFirst() throws Exception {
    try {
      String testName = "testSuccessFirst";
      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.getTopicManager().getLinkStrategy(), response, "create");
      System.out.println("create: " + sender);
      Link pushSubscriptions =
          MessageTestBase.getLinkByTitle(
              manager.getTopicManager().getLinkStrategy(), response, "push-subscriptions");
      System.out.println("push subscriptions: " + pushSubscriptions);

      String sub1 = generateURL("/subscribers/1");
      String sub2 = generateURL("/subscribers/2");

      PushTopicRegistration reg = new PushTopicRegistration();
      reg.setDurable(true);
      XmlLink target = new XmlLink();
      target.setHref(sub1);
      reg.setTarget(target);
      response = pushSubscriptions.request().body("application/xml", reg).post();
      response.releaseConnection();
      Assert.assertEquals(201, response.getStatus());

      reg = new PushTopicRegistration();
      reg.setDurable(true);
      target = new XmlLink();
      target.setHref(sub2);
      reg.setTarget(target);
      response = pushSubscriptions.request().body("application/xml", reg).post();
      response.releaseConnection();
      Assert.assertEquals(201, response.getStatus());

      shutdown();
      startup();
      deployTopic(testName);

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

      Receiver.latch.await(1, TimeUnit.SECONDS);

      Assert.assertEquals("1", Receiver.subscriber1);
      Assert.assertEquals("1", Receiver.subscriber2);

      manager.getTopicManager().getPushStore().removeAll();
    } finally {
      shutdown();
    }
  }
 @Test(dependsOnMethods = {"updateCollectionObject"})
 public void deleteCollectionObject() {
   ClientResponse<Response> res = collectionObjectClient.deleteCollectionObject(deleteId);
   verbose("deleteCollectionObject: csid=" + deleteId);
   verbose("deleteCollectionObject: status = " + res.getStatus());
   Assert.assertEquals(res.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
 }
  private ClientResponse<?> buildClientResponse() {
    @SuppressWarnings("unchecked")
    final ClientResponse<String> response = mock(ClientResponse.class);
    when(response.getStatus()).thenReturn(OK_STATUS);

    return response;
  }
Exemplo n.º 9
0
  public static void main(String[] args) throws Exception {
    // get the push consumers factory resource
    ClientRequest request = new ClientRequest("http://localhost:9095/queues/jms.queue.orders");
    ClientResponse res = request.head();
    Link pushConsumers = res.getHeaderAsLink("msg-push-consumers");

    // next create the XML document that represents the registration
    // Really, just create a link with the shipping URL and the type you want posted
    PushRegistration reg = new PushRegistration();
    BasicAuth authType = new BasicAuth();
    authType.setUsername("guest");
    authType.setPassword("guest");
    Authentication auth = new Authentication();
    auth.setType(authType);
    reg.setAuthenticationMechanism(auth);
    XmlLink target = new XmlLink();
    target.setHref("http://localhost:9095/queues/jms.queue.shipping");
    target.setType("application/xml");
    target.setRelationship("destination");
    reg.setTarget(target);

    res = pushConsumers.request().body("application/xml", reg).post();
    System.out.println(
        "Create push registration.  Resource URL: " + res.getLocationLink().getHref());
  }
Exemplo n.º 10
0
  /**
   * 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);
  }
 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;
 }
Exemplo n.º 13
0
 protected ClientResponse handleExpired(
     ClientExecutionContext ctx, ClientRequest request, BrowserCache.Entry entry)
     throws Exception {
   ClientResponse response = ctx.proceed();
   if (response.getStatus() == Response.Status.NOT_MODIFIED.getStatusCode()) {
     return updateOnNotModified(request, entry, (BaseClientResponse) response);
   }
   return cache(request, response);
 }
  // ---------------------------------------------------------------
  // CRUD tests : CREATE tests
  // ---------------------------------------------------------------
  // Success outcomes
  @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class)
  public void createIntakeWithAuthRefs(String testName) throws Exception {
    testSetup(STATUS_CREATED, ServiceRequestType.CREATE);

    // Submit the request to the service and store the response.
    String identifier = createIdentifier();

    // Create all the organization refs and entities
    createOrgRefs();

    IntakeClient intakeClient = new IntakeClient();
    PoxPayloadOut multipart =
        createIntakeInstance(
            "entryNumber-" + identifier,
            CURRENT_DATE_UTC,
            currentOwnerRefName,
            // Use currentOwnerRefName twice to test fix for CSPACE-2863
            currentOwnerRefName, // depositorRefName,
            conditionCheckerAssessorRefName,
            insurerRefName,
            valuerRefName);

    ClientResponse<Response> res = intakeClient.create(multipart);
    try {
      int statusCode = res.getStatus();

      // Check the status code of the response: does it match
      // the expected response(s)?
      //
      // Specifically:
      // Does it fall within the set of valid status codes?
      // Does it exactly match the expected status code?
      if (logger.isDebugEnabled()) {
        logger.debug(testName + ": status = " + statusCode);
      }
      Assert.assertTrue(
          testRequestType.isValidStatusCode(statusCode),
          invalidStatusCodeMessage(testRequestType, statusCode));
      Assert.assertEquals(statusCode, testExpectedStatusCode);
    } finally {
      res.releaseConnection();
    }

    // Store the ID returned from the first resource created
    // for additional tests below.
    if (knownIntakeId == null) {
      knownIntakeId = extractId(res);
      if (logger.isDebugEnabled()) {
        logger.debug(testName + ": knownIntakeId=" + knownIntakeId);
      }
    }

    // Store the IDs from every resource created by tests,
    // so they can be deleted after tests have been run.
    intakeIdsCreated.add(extractId(res));
  }
Exemplo n.º 15
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());
 }
  // 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!");
    }
  }
  @Ignore("needs mock connection to test with")
  @Test
  public void doesnotexist() {
    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("doesnotexist");

    assertNotNull(resp);
    assertEquals(404, resp.getStatus());
  }
 public void run() {
   try {
     ClientRequest req = new ClientRequest(url);
     req.header("Accept-Wait", acceptWaitTime);
     ClientResponse<?> response = req.post();
     response.releaseConnection();
     isFinished = true;
   } catch (Exception e) {
     failed = true;
   }
 }
  @Test
  public void createCollectionObject() {
    long identifier = this.createIdentifier();

    CollectionObject collectionObject = createCollectionObject(identifier);
    ClientResponse<Response> res = collectionObjectClient.createCollectionObject(collectionObject);
    Assert.assertEquals(res.getStatus(), Response.Status.CREATED.getStatusCode());

    // store updateId locally for "update" test
    if (updateId == null) updateId = extractId(res);
    else deleteId = extractId(res);
  }
Exemplo n.º 20
0
  @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());
    }
  }
  /** Creates the organization refs. */
  protected void createOrgRefs() {
    OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
    // orgAuthRefName =
    //	OrgAuthorityClientUtils.createOrgAuthRefName(ORGANIZATION_AUTHORITY_NAME, null);
    PoxPayloadOut multipart =
        OrgAuthorityClientUtils.createOrgAuthorityInstance(
            ORGANIZATION_AUTHORITY_NAME,
            ORGANIZATION_AUTHORITY_NAME,
            orgAuthClient.getCommonPartName());
    ClientResponse<Response> res = orgAuthClient.create(multipart);
    int statusCode = res.getStatus();

    Assert.assertTrue(
        testRequestType.isValidStatusCode(statusCode),
        invalidStatusCodeMessage(testRequestType, statusCode));
    Assert.assertEquals(statusCode, STATUS_CREATED);
    orgAuthCSID = extractId(res);

    currentOwnerOrgCSID =
        createOrganization("olivierOwnerCompany", "Olivier Owner Company", "Olivier Owner Company");
    orgIdsCreated.add(currentOwnerOrgCSID);
    currentOwnerRefName =
        OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, currentOwnerOrgCSID, orgAuthClient);

    String newOrgCSID =
        createOrganization(
            "debbieDepositorAssocs",
            "Debbie Depositor & Associates",
            "Debbie Depositor & Associates");
    depositorRefName =
        OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, newOrgCSID, orgAuthClient);
    orgIdsCreated.add(newOrgCSID);

    newOrgCSID =
        createOrganization(
            "andrewCheckerAssessorLtd",
            "Andrew Checker-Assessor Ltd.",
            "Andrew Checker-Assessor Ltd.");
    conditionCheckerAssessorRefName =
        OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, newOrgCSID, orgAuthClient);
    orgIdsCreated.add(newOrgCSID);

    newOrgCSID =
        createOrganization("ingridInsurerBureau", "Ingrid Insurer Bureau", "Ingrid Insurer Bureau");
    insurerRefName = OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, newOrgCSID, orgAuthClient);
    orgIdsCreated.add(newOrgCSID);

    newOrgCSID = createOrganization("vinceValuerLLC", "Vince Valuer LLC", "Vince Valuer LLC");
    valuerRefName = OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, newOrgCSID, orgAuthClient);
    orgIdsCreated.add(newOrgCSID);
  }
Exemplo n.º 22
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");
  }
 public void run() {
   try {
     isFinished = false;
     ClientRequest request = new ClientRequest(url);
     ClientResponse<?> response = request.post();
     response.releaseConnection();
     System.out.println("NPS response: " + response.getStatus());
     Assert.assertEquals(201, response.getStatus());
     isFinished = true;
   } catch (Exception e) {
     System.out.println("Exception " + e);
     failed = true;
   }
 }
Exemplo n.º 24
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);
   }
 }
Exemplo n.º 25
0
  @Ignore
  public void testDeleteMember() throws Exception {
    final String Path = "/members/1";
    ClientRequest webResource = new ClientRequest(BASE_URI + Path);

    ClientResponse response = null;

    ClientRequest resource = webResource;

    resource.queryParameter("auth_token", AUTH_TOKEN);

    response = resource.delete(ClientResponse.class);

    assertTrue(response.getStatus() == HTTP_STATUS_OK);
  }
Exemplo n.º 26
0
 private void _test(ClientRequest request, UriBuilder uriBuilder, String path) {
   request.clear();
   uriBuilder.replacePath(generateURL(path));
   try {
     ClientResponse<String> response = request.get(String.class);
     Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
     MultivaluedMap<String, String> headers = response.getHeaders();
     for (Object key : headers.keySet()) {
       System.out.println(key + ": " + headers.get(key));
     }
     response.releaseConnection();
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
  @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);
    }
  }
Exemplo n.º 28
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 testExecuteHttpCodeNoSuccess() throws Exception {

    final SpanId mockSpanId = mock(SpanId.class);
    when(mockSpanId.getTraceId()).thenReturn(TRACE_ID);
    when(mockSpanId.getSpanId()).thenReturn(SPAN_ID);
    when(mockSpanId.getParentSpanId()).thenReturn(PARENT_SPAN_ID);

    when(mockClientTracer.startNewSpan(PATH)).thenReturn(mockSpanId);
    when(mockClientResponse.getStatus()).thenReturn(SERVER_ERROR_STATUS);

    assertSame(mockClientResponse, interceptor.execute(mockExecutionContext));

    final InOrder inOrder = inOrder(mockClientTracer, mockClientRequest, mockExecutionContext);

    inOrder.verify(mockClientTracer).startNewSpan(PATH);
    inOrder.verify(mockClientRequest).header(BraveHttpHeaders.Sampled.getName(), "true");
    inOrder.verify(mockClientRequest).header(BraveHttpHeaders.TraceId.getName(), TRACE_ID_HEX);
    inOrder.verify(mockClientRequest).header(BraveHttpHeaders.SpanId.getName(), SPAN_ID_HEX);
    inOrder
        .verify(mockClientRequest)
        .header(BraveHttpHeaders.ParentSpanId.getName(), PARENT_SPAN_ID_HEX);
    inOrder.verify(mockClientTracer).setCurrentClientServiceName(CONTEXT_PATH);
    inOrder
        .verify(mockClientTracer)
        .submitBinaryAnnotation(REQUEST_ANNOTATION, HTTP_METHOD + " " + URI);
    inOrder.verify(mockClientTracer).setClientSent();
    inOrder.verify(mockExecutionContext).proceed();
    inOrder
        .verify(mockClientTracer)
        .submitBinaryAnnotation("http.responsecode", SERVER_ERROR_STATUS);
    inOrder.verify(mockClientTracer).submitAnnotation("failure");
    inOrder.verify(mockClientTracer).setClientReceived();
    verifyNoMoreInteractions(mockClientTracer);
  }
Exemplo n.º 30
0
 @SuppressWarnings("rawtypes")
 public void handle(ClientResponse response) throws RuntimeException {
   try {
     BaseClientResponse r = (BaseClientResponse) response;
     String message = "SomeApplikationException. Status Code: " + response.getStatus();
     InputStream stream = r.getStreamFactory().getInputStream();
     stream.reset();
     if (response.getStatus() == 523) {
       System.out.println(
           "ClientExceptionmapper: Mapped Stauscode 523 to SomeApplicationException");
       throw new SomeApplicationException(message);
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
 }