Java Code Examples for javax.ws.rs.client.Invocation#invoke()

The following examples show how to use javax.ws.rs.client.Invocation#invoke() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaseClientUtils.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
protected Response expect(ResponseExpectation expectation, Invocation i) {
  try (Timer.TimedBlock b = Timer.time("request")) {
    Response response = i.invoke();
    response.bufferEntity();
    try {
      expectation.validate(response);
    } catch (AssertionError e) {
      // this will show the body of the response in the error message
      // if an error occurred it will show the server side error.
      // response.toString() does not show the content
      String body = response.readEntity(String.class);
      throw new AssertionError(String.format("%s\n%s\n%s", e.getMessage(), response.toString(), body), e);
    }
    return response;
  }
}
 
Example 2
Source File: Undeployer.java    From openscoring with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @return <code>null</code> If the operation was successful.
 */
public SimpleResponse undeploy() throws Exception {
	Operation<SimpleResponse> operation = new Operation<SimpleResponse>(){

		@Override
		public SimpleResponse perform(WebTarget target){
			Invocation invocation = target.request(MediaType.APPLICATION_JSON).buildDelete();

			Response response = invocation.invoke();

			return response.readEntity(SimpleResponse.class);
		}
	};

	return execute(operation);
}
 
Example 3
Source File: StreamMetaDataAuthFocusedTests.java    From pravega with Apache License 2.0 6 votes vote down vote up
@Test
public void testListScopesReturnsAllScopesForUserWithPermissionOnRootAndChildren() {
    // Arrange
    final String resourceURI = getURI() + "v1/scopes";
    when(mockControllerService.listScopes()).thenReturn(CompletableFuture.completedFuture(
            Arrays.asList("scopea", "scopeb", "scopec")));
    Invocation requestInvocation = this.invocationBuilder(resourceURI, USER_SCOPE_LISTER, DEFAULT_PASSWORD)
            .buildGet();

    // Act
    Response response = requestInvocation.invoke();
    ScopesList scopes = response.readEntity(ScopesList.class);

    // Assert
    assertEquals(3, scopes.getScopes().size());

    response.close();
}
 
Example 4
Source File: StreamMetaDataAuthFocusedTests.java    From pravega with Apache License 2.0 6 votes vote down vote up
@Test
public void testListScopesReturnsFilteredResults() throws ExecutionException, InterruptedException {
    // Arrange
    final String resourceURI = getURI() + "v1/scopes";
    when(mockControllerService.listScopes()).thenReturn(CompletableFuture.completedFuture(
            Arrays.asList("scope1", "scope2", "scope3")));
    Invocation requestInvocation = this.invocationBuilder(resourceURI, USER_ACCESS_TO_SUBSET_OF_SCOPES, DEFAULT_PASSWORD)
            .buildGet();

    // Act
    Response response = requestInvocation.invoke();
    ScopesList scopes = response.readEntity(ScopesList.class);

    // Assert
    assertEquals(1, scopes.getScopes().size());
    assertEquals("scope3", scopes.getScopes().get(0).getScopeName());

    response.close();
}
 
Example 5
Source File: StreamMetaDataAuthFocusedTests.java    From pravega with Apache License 2.0 6 votes vote down vote up
@Test
public void testListScopesReturnsUnauthorizedStatusForInvalidUser() {
    // Arrange
    final String resourceURI = getURI() + "v1/scopes";
    when(mockControllerService.listScopes()).thenReturn(CompletableFuture.completedFuture(
            Arrays.asList("scope1", "scope2", "scope3")));
    Invocation requestInvocation = this.invocationBuilder(resourceURI, "fictitiousUser", "whatever")
            .buildGet();

    // Act
    Response response = requestInvocation.invoke();

    // Assert
    assertEquals(HTTP_STATUS_UNAUTHORIZED, response.getStatus());

    response.close();
}
 
Example 6
Source File: StreamMetaDataAuthFocusedTests.java    From pravega with Apache License 2.0 6 votes vote down vote up
@Test
public void testListScopesIsForbiddenForValidButUnauthorizedUser() {
    // Arrange
    final String resourceURI = getURI() + "v1/scopes";
    when(mockControllerService.listScopes()).thenReturn(CompletableFuture.completedFuture(
            Arrays.asList("scope1", "scope2", "scope3")));
    Invocation requestInvocation = this.invocationBuilder(resourceURI,
            USER_WITH_NO_AUTHORIZATIONS, DEFAULT_PASSWORD)
            .buildGet();

    // Act
    Response response = requestInvocation.invoke();

    // Assert
    assertEquals(HTTP_STATUS_FORBIDDEN, response.getStatus());

    response.close();
}
 
Example 7
Source File: PersonsIT.java    From hibernate-demos with Apache License 2.0 6 votes vote down vote up
@Test
public void createAndGetPerson(@ArquillianResteasyResource( "hike-manager/persons" ) ResteasyWebTarget webTarget) throws Exception {
	// Create a person
	Invocation createPerson = invocationBuilder( webTarget ).buildPost(
			jsonEntity( "{ 'firstName' : 'Saundra', 'lastName' : 'Smith' } " )
	);

	Response response = createPerson.invoke();
	assertEquals( HttpStatus.SC_CREATED, response.getStatus() );

	String location = response.getHeaderString( "Location");
	assertNotNull( location );
	response.close();

	// Get the person
	Invocation getPerson = invocationBuilder( webTarget, "/" + getId( location ) ).buildGet();
	response = getPerson.invoke();
	assertEquals( HttpStatus.SC_OK, response.getStatus() );

	JSONAssert.assertEquals(
			"{ 'firstName' : 'Saundra', 'lastName' : 'Smith' }",
			response.readEntity( String.class ),
			false
	);
	response.close();
}
 
Example 8
Source File: SelfUpdate.java    From digdag with Apache License 2.0 6 votes vote down vote up
private Response getWithRedirect(Client client, Invocation req)
{
    while (true) {
        Response res = req.invoke();
        String location =  res.getHeaderString("Location");
        if (res.getStatus() / 100 != 3 || location == null) {
            return res;
        }
        res.readEntity(String.class);
        if (!location.startsWith("http")) {
            location = endpoint + location;
        }
        req = client.target(fromUri(location))
            .request()
            .buildGet();
    }
}
 
Example 9
Source File: RestDAO.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Send a GET request and get the plain text in the response
 * 
 * @param webResource
 *            a web resource
 * @return the text from the response
 * @throws BillingException
 *             if the GET request fails
 */
public String getTextResponse(WebTarget webResource)
        throws BillingException {

    Invocation invocation = webResource
            .request(MediaType.TEXT_PLAIN_TYPE).buildGet();
    try {
        return invocation.invoke(String.class);
    } catch (RuntimeException e) {
        throw new BillingException(
                "Error when processing response from File Billing Application",
                e);
    }
}
 
Example 10
Source File: BasicRESTClient.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Override
public Response deleteRequestWithHeaders(final URL url, final Map<String, Object> headers)
        throws MalformedURLException, URISyntaxException {
    if (sessionToken == null) {
        LOGGER.log(Level.SEVERE, String.format("Token is null in call to RESTClient for url: %s", url.toString()));
        return null;
    }
    Invocation.Builder builder = client.target(url.toURI()).request(MediaType.APPLICATION_JSON);
    builder = getCommonRequestBuilder(sessionToken, builder, headers);
    Invocation i = builder.buildDelete();
    return i.invoke();
}
 
Example 11
Source File: BasicRESTClient.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Override
public Response getRequestWithHeaders(final URL url, final Map<String, Object> headers) throws URISyntaxException {
    if (sessionToken == null) {
        LOGGER.log(Level.SEVERE, String.format("Token is null in call to RESTClient for url: %s", url.toString()));
        return null;
    }
    Invocation.Builder builder = client.target(url.toURI()).request(MediaType.APPLICATION_JSON);
    builder = getCommonRequestBuilder(sessionToken, builder, headers);
    Invocation i = builder.buildGet();
    return i.invoke();
}
 
Example 12
Source File: RemoteCarService.java    From microservices-comparison with Apache License 2.0 5 votes vote down vote up
@Override
public List<Car> getAllCars(String auth) {
    WebTarget target = client.target("https://localhost:8443/app/cars");
    Invocation invocation = target.request(MediaType.APPLICATION_JSON)
            .header("Authorization", "Bearer " + auth)
            .build(HttpMethod.GET);
    Car[] cars = invocation.invoke(Car[].class);
    return asList(cars);
}
 
Example 13
Source File: RestDAO.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Send a GET request and get the file content, which is contained in the
 * response as octet stream
 * 
 * @param webResource
 *            a web resource
 * @return the file content
 * @throws BillingException
 *             if the GET request fails
 */
public byte[] getFileResponse(WebTarget webResource)
        throws BillingException {

    Invocation invocation = webResource
        .request(MediaType.APPLICATION_OCTET_STREAM).buildGet();

    try {
        InputStream is = invocation.invoke(InputStream.class);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        int next = is.read();
        while (next > -1) {
            bos.write(next);
            next = is.read();
        }
        bos.flush();

        byte[] result = bos.toByteArray();
        if (result.length > 0) {
            return result;
        } else {
            return null;
        }
    } catch (Exception e) {
        throw new BillingException(
                "Error when processing file response from File Billing Application",
                e);
    }
}
 
Example 14
Source File: RequestManager.java    From Everest with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a JavaFX Task for processing the required kind of request.
 */
@Override
protected Task<EverestResponse> createTask() throws ProcessingException {
    return new Task<EverestResponse>() {
        @Override
        protected EverestResponse call() throws Exception {
            Response serverResponse = null;

            addAuthHeader();

            if (request.getClass().equals(GETRequest.class)) {
                initialTime = System.currentTimeMillis();
                serverResponse = requestBuilder.get();
                finalTime = System.currentTimeMillis();
            } else if (request.getClass().equals(DataRequest.class)) {
                DataRequest dataRequest = (DataRequest) request;

                Invocation invocation = appendBody(dataRequest);
                initialTime = System.currentTimeMillis();
                serverResponse = invocation.invoke();
                finalTime = System.currentTimeMillis();
            } else if (request.getClass().equals(DELETERequest.class)) {
                initialTime = System.currentTimeMillis();
                serverResponse = requestBuilder.delete();
                finalTime = System.currentTimeMillis();
            }

            processServerResponse(serverResponse);

            return response;
        }
    };
}
 
Example 15
Source File: StreamMetaDataAuthFocusedTests.java    From pravega with Apache License 2.0 5 votes vote down vote up
private ScopesList listScopes(List<String> scopeNames, String username, String password) {
    final String resourceURI = getURI() + "v1/scopes";
    when(mockControllerService.listScopes())
            .thenReturn(CompletableFuture.completedFuture(scopeNames));
    Invocation requestInvocation = this.invocationBuilder(resourceURI, username, password)
            .buildGet();

    Response response = requestInvocation.invoke();
    ScopesList scopes = response.readEntity(ScopesList.class);
    response.close();
    return scopes;
}
 
Example 16
Source File: ElasticConnectionPool.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public <T> T execute(ElasticAction2<T> action){
  final ContextListenerImpl listener = new ContextListenerImpl();
  final Invocation invocation = action.buildRequest(target, listener);
  try {
    return invocation.invoke(action.getResponseClass());
  } catch (Exception e){
    throw handleException(e, action, listener);
  }

}
 
Example 17
Source File: TestJobResource.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testDownloadSendsHeadersBeforeContent() {
  final SqlQuery query = new SqlQuery("select * from sys.version", Collections.emptyList(), SystemUser.SYSTEM_USERNAME);

  final JobId jobId = submitJobAndWaitUntilCompletion(
    JobRequest.newBuilder().setSqlQuery(query).setQueryType(QueryType.UI_RUN).build()
  );

  final Invocation invocation = getBuilder(
    getAPIv2()
      .path("testjob")
      .path(jobId.getId())
      .path("download")
      .queryParam("downloadFormat", "JSON"))
    .buildGet();

  final Response response = invocation.invoke();

  assertTrue(response.getHeaderString("Content-Disposition").startsWith("attachment;"));
  assertEquals("nosniff", response.getHeaderString("X-Content-Type-Options"));
  assertEquals(MediaType.APPLICATION_JSON, response.getMediaType().toString());

  final ChunkedInput<String> chunks = response.readEntity(new GenericType<ChunkedInput<String>>(){});
  String chunk;
  String readChunk = null;
  while ((chunk = chunks.read()) != null) {
    readChunk = chunk;
  }

  assertNotNull(readChunk);
}
 
Example 18
Source File: WebClient.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private <T> T readEntity(Class<T> entityClazz, Invocation invocation) throws IOException {
  Response response = invocation.invoke();
  try {
    response.bufferEntity();
    if (response.getStatus() != Response.Status.OK.getStatusCode()) {
      if (response.hasEntity()) {
        // Try to parse error message as generic error message JSON type
        try {
          GenericErrorMessage message = response.readEntity(GenericErrorMessage.class);
          throw new IOException(format("Status %d (%s): %s (more info: %s)",
            response.getStatus(),
            response.getStatusInfo().getReasonPhrase(),
            message.getErrorMessage(),
            message.getMoreInfo()));
        } catch (ProcessingException e) {
          // Fallback to String if unparsing is unsuccessful
          throw new IOException(format("Status %d (%s): %s",
            response.getStatus(),
            response.getStatusInfo().getReasonPhrase(),
            response.readEntity(String.class)));
        }
      }
      throw new IOException(format("Status %d (%s)",
        response.getStatus(),
        response.getStatusInfo().getReasonPhrase()));
    }
    return response.readEntity(entityClazz);
  } finally {
    response.close();
  }
}
 
Example 19
Source File: CsvEvaluator.java    From openscoring with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @return <code>null</code> If the operation was successful.
 */
public SimpleResponse evaluate() throws Exception {
	Operation<SimpleResponse> operation = new Operation<SimpleResponse>(){

		@Override
		public SimpleResponse perform(WebTarget target) throws Exception {
			String delimiterChar = getDelimiterChar();
			String quoteChar = getQuoteChar();

			if(delimiterChar != null){
				target = target.queryParam("delimiterChar", delimiterChar);

				if(quoteChar != null){
					target = target.queryParam("quoteChar", quoteChar);
				}
			}

			try(InputStream is = new FileInputStream(getInput())){

				try(OutputStream os = new FileOutputStream(getOutput())){
					Invocation invocation = target.request(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN).buildPost(Entity.text(is));

					Response response = invocation.invoke();

					Response.StatusType status = response.getStatusInfo();
					switch(status.getFamily()){
						case CLIENT_ERROR:
						case SERVER_ERROR:
							return response.readEntity(SimpleResponse.class);
						default:
							break;
					}

					try(InputStream result = response.readEntity(InputStream.class)){
						byte[] buffer = new byte[10 * 1024];

						while(true){
							int count = result.read(buffer);
							if(count < 0){
								break;
							}

							os.write(buffer, 0, count);
						}

						return null;
					}
				}
			}
		}
	};

	return execute(operation);
}
 
Example 20
Source File: YandexTranslate.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }

    final StopWatch stopWatch = new StopWatch(true);
    final String key = context.getProperty(KEY).getValue();
    final String sourceLanguage = context.getProperty(SOURCE_LANGUAGE).evaluateAttributeExpressions(flowFile).getValue();
    final String targetLanguage = context.getProperty(TARGET_LANGUAGE).evaluateAttributeExpressions(flowFile).getValue();
    final String encoding = context.getProperty(CHARACTER_SET).evaluateAttributeExpressions(flowFile).getValue();

    final List<String> attributeNames = new ArrayList<>();
    final List<String> textValues = new ArrayList<>();
    for (final PropertyDescriptor descriptor : context.getProperties().keySet()) {
        if (descriptor.isDynamic()) {
            attributeNames.add(descriptor.getName()); // add to list so that we know the order when the translations come back.
            textValues.add(context.getProperty(descriptor).evaluateAttributeExpressions(flowFile).getValue());
        }
    }

    if (context.getProperty(TRANSLATE_CONTENT).asBoolean()) {
        final byte[] buff = new byte[(int) flowFile.getSize()];
        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(final InputStream in) throws IOException {
                StreamUtils.fillBuffer(in, buff);
            }
        });
        final String content = new String(buff, Charset.forName(encoding));
        textValues.add(content);
    }

    final Invocation invocation = prepareResource(key, textValues, sourceLanguage, targetLanguage);

    final Response response;
    try {
        response = invocation.invoke();
    } catch (final Exception e) {
        getLogger().error("Failed to make request to Yandex to transate text for {} due to {}; routing to comms.failure", new Object[]{flowFile, e});
        session.transfer(flowFile, REL_COMMS_FAILURE);
        return;
    }

    if (response.getStatus() != Response.Status.OK.getStatusCode()) {
        getLogger().error("Failed to translate text using Yandex for {}; response was {}: {}; routing to {}", new Object[]{
                flowFile, response.getStatus(), response.getStatusInfo().getReasonPhrase(), REL_TRANSLATION_FAILED.getName()});
        flowFile = session.putAttribute(flowFile, "yandex.translate.failure.reason", response.getStatusInfo().getReasonPhrase());
        session.transfer(flowFile, REL_TRANSLATION_FAILED);
        return;
    }

    final Map<String, String> newAttributes = new HashMap<>();
    final Translation translation = response.readEntity(Translation.class);
    final List<String> texts = translation.getText();
    for (int i = 0; i < texts.size(); i++) {
        final String text = texts.get(i);
        if (i < attributeNames.size()) {
            final String attributeName = attributeNames.get(i);
            newAttributes.put(attributeName, text);
        } else {
            flowFile = session.write(flowFile, new OutputStreamCallback() {
                @Override
                public void process(final OutputStream out) throws IOException {
                    out.write(text.getBytes(encoding));
                }
            });

            newAttributes.put("language", targetLanguage);
        }
    }

    if (!newAttributes.isEmpty()) {
        flowFile = session.putAllAttributes(flowFile, newAttributes);
    }

    stopWatch.stop();
    session.transfer(flowFile, REL_SUCCESS);
    getLogger().info("Successfully translated {} items for {} from {} to {} in {}; routing to success",
            new Object[]{texts.size(), flowFile, sourceLanguage, targetLanguage, stopWatch.getDuration()});
}