Java Code Examples for javax.ws.rs.client.Invocation#Builder

The following examples show how to use javax.ws.rs.client.Invocation#Builder . 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: AdminServlet.java    From sample.microservices.12factorapp with Apache License 2.0 7 votes vote down vote up
@Override
    public void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
        String authorizationHeaderName = "Authorization";
        String authorizationHeaderValue = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary("kate:password".getBytes("UTF-8"));
        String url = "";
        String requestURI = httpRequest.getRequestURI().toString();
        String requestUrl = httpRequest.getRequestURL().toString();
        String subUrl = requestUrl.substring(0, requestUrl.indexOf(requestURI));
        url = subUrl + statsExtension;

        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(url);
        Invocation.Builder invoBuild = target.request(MediaType.APPLICATION_JSON).header(authorizationHeaderName, authorizationHeaderValue);
        Response response = invoBuild.get();
        String resp = response.readEntity(String.class);
        response.close();
//		String stats = parse(resp);
        String stats = resp;
        PrintWriter out = httpResponse.getWriter();
        out.println("Stats: " + stats + " Status: " + httpResponse.getStatus());
    }
 
Example 2
Source File: ParcelServiceTest.java    From cloudbreak with Apache License 2.0 7 votes vote down vote up
@Test
void testFilterParcelsByBlueprintWhenNoManifest() {
    Client client = mock(Client.class);
    WebTarget webTarget = mock(WebTarget.class);
    Invocation.Builder request = mock(Invocation.Builder.class);
    Response response = mock(Response.class);

    Blueprint blueprint = new Blueprint();
    blueprint.setBlueprintText("bpText");

    SupportedServices supportedServices = getSupportedServices("serv1");

    when(clusterTemplateGeneratorService.getServicesByBlueprint("bpText")).thenReturn(supportedServices);
    when(restClientFactory.getOrCreateDefault()).thenReturn(client);
    when(client.target("http://parcel1.com/manifest.json")).thenReturn(webTarget);
    when(webTarget.request()).thenReturn(request);
    when(request.get()).thenReturn(response);
    when(response.getStatusInfo()).thenReturn(Response.Status.OK);
    when(response.readEntity(String.class)).thenReturn(null);

    List<ClouderaManagerProduct> parcels = getParcels("http://parcel1.com/", "http://parcel2.com/");
    Set<ClouderaManagerProduct> actual = underTest.filterParcelsByBlueprint(parcels, blueprint);

    Assertions.assertEquals(2, actual.size());
    Assertions.assertEquals(actual, new HashSet<>(parcels));
}
 
Example 3
Source File: JWTOrFormAuthenticationFilterTest.java    From shiro-jwt with MIT License 6 votes vote down vote up
@Test(expected = NotAuthorizedException.class)
@InSequence(4)
public void securedTokenExpired() throws IOException {
    try {
        Thread.sleep(5000);
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    Invocation.Builder invocationBuilder = target.path("/secured").request().accept(MediaType.APPLICATION_JSON);
    invocationBuilder.header("Authorization", token);
    invocationBuilder.get(JsonObject.class);
}
 
Example 4
Source File: IntegrationTest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
private Invocation.Builder call(String path) {
  String server;
  if (path.startsWith("http://") || path.startsWith("https://")) {
    server = path;
  } else {
    int localPort = APP.getLocalPort();
    // int localPort = 8080;
    server = format("http://localhost:%d" + path, localPort);
  }
  return client
    .target(server)
    .register(MultiPartFeature.class)
    // .register(new LoggingFilter(Logger.getLogger(LoggingFilter.class.getName()), true))
    .request()
    .header("Authorization", AUTH);
}
 
Example 5
Source File: BxCodegenClient.java    From tool.accelerate.core with Apache License 2.0 5 votes vote down vote up
protected String checkStatus(String id) {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(URL + "api/generator/" + id + "/status");
    Invocation.Builder invoBuild = target.request();
    Response response = invoBuild.accept(MediaType.APPLICATION_JSON_TYPE).get();
    JsonObject responseObject = response.readEntity(JsonObject.class);
    String responseStatus = responseObject.getString("status");
    System.out.println("Received response status : " + responseStatus);
    return responseStatus;
}
 
Example 6
Source File: AlchemyClient.java    From alchemy with MIT License 5 votes vote down vote up
@Nullable
@Override
public List<ExperimentDto> apply(@Nullable GetExperimentsRequest request) {
    if (request == null) {
        return null;
    }

    final ListMultimap<String, Object> queryParams = ArrayListMultimap.create();

    if (request.getFilter() != null) {
        queryParams.put("filter", request.getFilter());
    }

    if (request.getOffset() != null) {
        queryParams.put("offset", request.getOffset());
    }

    if (request.getLimit() != null) {
        queryParams.put("limit", request.getLimit());
    }

    if (request.getSort() != null) {
        queryParams.put("sort", request.getSort());
    }

    final Invocation.Builder builder = resource(ENDPOINT_EXPERIMENTS, queryParams);
    return builder.get(list(ExperimentDto.class));
}
 
Example 7
Source File: Keycloak.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
private Invocation.Builder rest(String path) {
    if(token == null)
        throw new RuntimeException("Have to login first.");

    Client client = ClientBuilder.newClient(); // TODO cache this?
    return client.target(baseUrl + "/auth/admin").path(path)
            .request(MediaType.APPLICATION_JSON_TYPE)
            .header("Authorization", "bearer " + token);
}
 
Example 8
Source File: RESTApiClusterManager.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Issues a command (e.g. starting or stopping a role).
 * @return the commandId of a successfully submitted asynchronous command.
 */
private long doRoleCommand(String serviceName, String roleName, RoleCommand roleCommand) {
  URI uri = UriBuilder.fromUri(serverHostname)
      .path("api")
      .path(API_VERSION)
      .path("clusters")
      .path(clusterName)
      .path("services")
      .path(serviceName)
      .path("roleCommands")
      .path(roleCommand.toString())
      .build();
  String body = "{ \"items\": [ \"" + roleName + "\" ] }";
  LOG.trace("Executing POST against {} with body {} ...", uri, body);
  WebTarget webTarget = client.target(uri);
  Invocation.Builder invocationBuilder =  webTarget.request(MediaType.APPLICATION_JSON);
  Response response = invocationBuilder.post(Entity.json(body));
  final int statusCode = response.getStatus();
  final String responseBody = response.readEntity(String.class);
  if (statusCode != Response.Status.OK.getStatusCode()) {
    LOG.warn(
      "RoleCommand failed with status code {} and response body {}", statusCode, responseBody);
    throw new HTTPException(statusCode);
  }

  LOG.trace("POST against {} completed with status code {} and response body {}",
    uri, statusCode, responseBody);
  return parser.parse(responseBody)
    .getAsJsonObject()
    .get("items")
    .getAsJsonArray()
    .get(0)
    .getAsJsonObject()
    .get("id")
    .getAsLong();
}
 
Example 9
Source File: NiFiTestUser.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to create a token with the specified username and password.
 *
 * @param url the url
 * @param username the username
 * @param password the password
 * @return response
 * @throws Exception ex
 */
public Response testCreateToken(String url, String username, String password) throws Exception {
    // convert the form data
    MultivaluedHashMap<String, String> entity = new MultivaluedHashMap();
    entity.add("username", username);
    entity.add("password", password);

    // get the resource
    Invocation.Builder resourceBuilder = addProxiedEntities(client.target(url).request().accept(MediaType.TEXT_PLAIN));

    // perform the request
    return resourceBuilder.post(Entity.form(entity));
}
 
Example 10
Source File: WebClient.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private final <TResult, TRequest> TResult buildPost(Class<TResult> outputType, String path,
  TRequest requestBody, boolean includeAuthToken) throws IOException {
  Invocation.Builder builder =  target.path(path).request(MediaType.APPLICATION_JSON_TYPE);

  if (includeAuthToken) {
    builder = builder.header(HttpHeader.AUTHORIZATION.toString(),
      TokenUtils.AUTH_HEADER_PREFIX + userSession.getToken());
  }

  return readEntity(outputType, builder.buildPost(Entity.json(requestBody)));
}
 
Example 11
Source File: EndpointTest.java    From tool.accelerate.core with Apache License 2.0 5 votes vote down vote up
public Response sendRequest(String url, String requestType) {
    Client client = ClientBuilder.newClient();
    System.out.println("Testing " + url);
    WebTarget target = client.target(url);
    Invocation.Builder invoBuild = target.request();
    Response response = invoBuild.build(requestType).invoke();
    return response;
}
 
Example 12
Source File: NiFiTestUser.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Performs a DELETE using the specified url and entity.
 *
 * @param url url
 * @param headers http headers
 * @return response
 * @throws java.lang.Exception ex
 */
public Response testDeleteWithHeaders(String url, Map<String, String> headers) throws Exception {
    // get the resource
    Invocation.Builder builder = addProxiedEntities(client.target(url).request());

    // append any headers
    if (headers != null && !headers.isEmpty()) {
        for (String key : headers.keySet()) {
            builder = builder.header(key, headers.get(key));
        }
    }

    // perform the query
    return builder.delete();
}
 
Example 13
Source File: EndpointClient.java    From sample-room-java with Apache License 2.0 5 votes vote down vote up
public Response sendRequest(String url, String requestType) {
    Client client = ClientBuilder.newClient();
    System.out.println("Testing " + url);
    WebTarget target = client.target(url);
    Invocation.Builder invoBuild = target.request();
    Response response = invoBuild.build(requestType).invoke();
    return response;
}
 
Example 14
Source File: MockWebTarget.java    From tessera with Apache License 2.0 4 votes vote down vote up
public Invocation.Builder getMockInvocationBuilder() {
    return mockInvocationBuilder;
}
 
Example 15
Source File: RestUtils.java    From tessera with Apache License 2.0 4 votes vote down vote up
public Response sendRaw(Party sender, byte[] transactionData, Party... recipients) {

        Objects.requireNonNull(sender);

        String recipientString = Stream.of(recipients)
            .map(Party::getPublicKey)
            .collect(Collectors.joining(","));


        LOGGER.debug("Sending txn  to {}",recipientString);
        
        Invocation.Builder invocationBuilder = sender.getRestClientWebTarget()
            .path("sendraw")
            .request()
            .header(SENDER, sender.getPublicKey());




        Optional.of(recipientString)
            .filter(s -> !Objects.equals("", s))
            .ifPresent(s -> invocationBuilder.header(RECIPIENTS, s));

        return invocationBuilder
            .post(Entity.entity(transactionData, MediaType.APPLICATION_OCTET_STREAM));
    }
 
Example 16
Source File: BaseTestServer.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
protected Invocation.Builder getBuilder(WebTarget webTarget) {
  return webTarget.request(JSON).header(getAuthHeaderName(), getAuthHeaderValue());
}
 
Example 17
Source File: GitLabApiClient.java    From choerodon-starters with Apache License 2.0 4 votes vote down vote up
protected Invocation.Builder invocation(URL url, MultivaluedMap<String, String> queryParams) {
    return (invocation(url, queryParams, MediaType.APPLICATION_JSON));
}
 
Example 18
Source File: CheckingWebTarget.java    From raml-tester with Apache License 2.0 4 votes vote down vote up
@Override
public Invocation.Builder request() {
    return target.request();
}
 
Example 19
Source File: GitLabApiClient.java    From gitlab4j-api with MIT License 4 votes vote down vote up
protected Invocation.Builder invocation(URL url, MultivaluedMap<String, String> queryParams) {
    return (invocation(url, queryParams, MediaType.APPLICATION_JSON));
}
 
Example 20
Source File: Authentication.java    From datacollector with Apache License 2.0 votes vote down vote up
void setHeader(Invocation.Builder builder, String userAuthToken);