Java Examples for org.jboss.resteasy.client.jaxrs.ResteasyWebTarget

The following java examples will help you to understand the usage of org.jboss.resteasy.client.jaxrs.ResteasyWebTarget. These source code samples are taken from different open source projects.

Example 1
Project: aplikator-master  File: ExampleErraiClient.java View source code
public static void main(String[] args) {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(URL);
    ResteasyWebTarget rtarget = (ResteasyWebTarget) target;
    rtarget.register(ErraiProvider.class);
    AplikatorService proxyObject = rtarget.proxy(AplikatorService.class);
    // Proxy object call
    ApplicationDTO application = proxyObject.getApplication();
    System.out.println("Application - brand: " + application.getBrand());
}
Example 2
Project: Resteasy-master  File: SigningTest.java View source code
/**
     * @tpTestDetails Proxy test with bad signature
     * @tpSince RESTEasy 3.0.16
     */
@Test
public void testBadSignatureProxy() throws Exception {
    ResteasyWebTarget target = client.target(generateURL("/"));
    target.property(KeyRepository.class.getName(), repository);
    SigningProxy proxy = target.proxy(SigningProxy.class);
    try {
        proxy.bad();
        Assert.fail("Signing error excepted");
    } catch (ResponseProcessingException e) {
        logger.info("ResponseProcessingException cause: " + e.getCause().getClass().getName());
    }
}
Example 3
Project: OpenDolphin-master  File: PHRProxy.java View source code
private String getIdentityToken(String nonce, String userId) {
    String json = Json.createObjectBuilder().add("nonce", nonce).add("user", userId).build().toString();
    ResteasyClient client = new ResteasyClientBuilder().build();
    ResteasyWebTarget target = client.target(IDENTITY_SERVER_URI);
    Response response = target.request().post(Entity.text(json));
    int status = response.getStatus();
    String entity = response.readEntity(String.class);
    log(status, entity);
    return entity;
}
Example 4
Project: gov2go-master  File: UsuarioEndpointTest.java View source code
@Test
public void deveCadastrarCorretamente(@ArquillianResteasyResource(USUARIO_CONTEXT) ResteasyWebTarget webTarget) throws Exception {
    Usuario build = Usuario.novo().comNome("Taís").comEmail("tais@monique.com").build();
    Response response = webTarget.request().accept(MediaType.APPLICATION_JSON).buildPost(Entity.json(build)).invoke();
    assertEquals(201, response.getStatus());
//Usuario entity = (Usuario) response.getEntity();
//assertEquals(deploymentURL.toString().concat(USUARIO_CONTEXT).concat("/").concat(String.valueOf(entity.getId())), response.getHeaderString(LOCATION));
}
Example 5
Project: fabric8-master  File: ResteasyGitRepoClient.java View source code
/**
     * Creates a JAXRS web client for the given JAXRS client
     */
protected <T> T createWebClient(Class<T> clientType) {
    String address = getAddress();
    ResteasyProviderFactory providerFactory = ResteasyProviderFactory.getInstance();
    providerFactory.register(ResteasyJackson2Provider.class);
    providerFactory.register(Jackson2JsonpInterceptor.class);
    providerFactory.register(StringTextStar.class);
    providerFactory.register(DefaultTextPlain.class);
    providerFactory.register(FileProvider.class);
    providerFactory.register(InputStreamProvider.class);
    providerFactory.register(new Authenticator());
    providerFactory.register(clientType);
    ResteasyClientBuilder builder = new ResteasyClientBuilder();
    builder.providerFactory(providerFactory);
    builder.connectionPoolSize(3);
    Client client = builder.build();
    ResteasyWebTarget target = (ResteasyWebTarget) client.target(address);
    return target.proxy(clientType);
}
Example 6
Project: guvnor-master  File: PipelineEndpointsTestIT.java View source code
@Test
public void checkService() {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(APP_URL);
    ResteasyWebTarget restEasyTarget = (ResteasyWebTarget) target;
    PipelineService proxyPipeline = restEasyTarget.proxy(PipelineService.class);
    RuntimeProvisioningService proxyRuntime = restEasyTarget.proxy(RuntimeProvisioningService.class);
    ProviderTypeList allProviderTypes = proxyRuntime.getProviderTypes(0, 10, "", true);
    assertNotNull(allProviderTypes);
    assertEquals(2, allProviderTypes.getItems().size());
    DockerProviderConfig dockerProviderConfig = new DockerProviderConfigImpl();
    proxyRuntime.registerProvider(dockerProviderConfig);
    ProviderList allProviders = proxyRuntime.getProviders(0, 10, "", true);
    assertEquals(1, allProviders.getItems().size());
    assertTrue(allProviders.getItems().get(0) instanceof DockerProvider);
    PipelineConfigsList allPipelines = proxyPipeline.getPipelineConfigs(0, 10, "", true);
    assertNotNull(allPipelines);
    assertEquals(0, allPipelines.getItems().size());
    List<Config> configs = new ArrayList<>();
    configs.add(new GitConfigImpl());
    configs.add(new MavenProjectConfigImpl());
    configs.add(new MavenBuildConfigImpl());
    configs.add(new DockerBuildConfigImpl());
    configs.add(new MavenBuildExecConfigImpl());
    configs.add(new DockerProviderConfigImpl());
    configs.add(new ContextAwareDockerProvisioningConfig());
    configs.add(new ContextAwareDockerRuntimeExecConfig());
    String newPipeline = proxyPipeline.newPipeline(new PipelineConfigImpl("mypipe", configs));
    Input input = new Input();
    input.put("repo-name", "drools-workshop");
    input.put("create-repo", "true");
    input.put("branch", "master");
    input.put("out-dir", tempPath.getAbsolutePath());
    input.put("origin", "https://github.com/kiegroup/drools-workshop");
    input.put("project-dir", "drools-webapp-example");
    proxyPipeline.runPipeline("mypipe", input);
    RuntimeList allRuntimes = proxyRuntime.getRuntimes(0, 10, "", true);
    assertEquals(1, allRuntimes.getItems().size());
    proxyRuntime.destroyRuntime(allRuntimes.getItems().get(0).getId());
    allRuntimes = proxyRuntime.getRuntimes(0, 10, "", true);
    assertEquals(0, allRuntimes.getItems().size());
}
Example 7
Project: arquillian-extension-rest-master  File: RestClientTestCase.java View source code
/**
     * We can inject either proxy or a ResteasyWebTarget for low level manipulations and assertions.
     *
     * @param webTarget
     *     configured resource ready for use, injected by Arquillian
     */
@Test
public void createCustomerBareRsource(@ArquillianResteasyResource("rest/customer") ResteasyWebTarget webTarget) {
    //        Given
    final Invocation.Builder invocationBuilder = webTarget.request();
    final Invocation invocation = invocationBuilder.buildPost(Entity.entity(new Customer(), MediaType.APPLICATION_JSON_TYPE));
    //        When
    final Response response = invocation.invoke();
    //        Then
    assertEquals(deploymentURL + "rest/customer", webTarget.getUri().toASCIIString());
    assertEquals(MediaType.APPLICATION_JSON, response.getMediaType().toString());
    assertEquals(HttpStatus.SC_OK, response.getStatus());
}
Example 8
Project: wildfly-swarm-master  File: ProxyBuilder.java View source code
@SuppressWarnings("unchecked")
public static <T> T proxy(final Class<T> iface, WebTarget base, final ProxyConfig config) {
    if (iface.isAnnotationPresent(Path.class)) {
        Path path = iface.getAnnotation(Path.class);
        if (!path.value().equals("") && !path.value().equals("/")) {
            base = base.path(path.value());
        }
    }
    HashMap<Method, MethodInvoker> methodMap = new HashMap<Method, MethodInvoker>();
    for (Method method : iface.getMethods()) {
        // ignore the as method to allow declaration in client interfaces
        if ("as".equals(method.getName()) && Arrays.equals(method.getParameterTypes(), cClassArgArray)) {
            continue;
        }
        // Ignore default methods
        if (method.isDefault()) {
            continue;
        }
        MethodInvoker invoker;
        Set<String> httpMethods = IsHttpMethod.getHttpMethods(method);
        if ((httpMethods == null || httpMethods.size() == 0) && method.isAnnotationPresent(Path.class) && method.getReturnType().isInterface()) {
            invoker = new SubResourceInvoker((ResteasyWebTarget) base, method, config);
        } else {
            invoker = createClientInvoker(iface, method, (ResteasyWebTarget) base, config);
        }
        methodMap.put(method, invoker);
    }
    Class<?>[] intfs = { iface, ResteasyClientProxy.class };
    ClientProxy clientProxy = new ClientProxy(methodMap, base, config);
    // this is done so that equals and hashCode work ok. Adding the proxy to a
    // Collection will cause equals and hashCode to be invoked. The Spring
    // infrastructure had some problems without this.
    clientProxy.setClazz(iface);
    return (T) Proxy.newProxyInstance(config.getLoader(), intfs, clientProxy);
}
Example 9
Project: hibernate-demos-master  File: PersonsIT.java View source code
@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 10
Project: scheduling-master  File: SchedulerStateRest.java View source code
@Consumes(MediaType.APPLICATION_JSON)
@POST
@Path("{path:plannings}")
@Produces("application/json")
@Override
public String submitPlannings(@HeaderParam("sessionid") String sessionId, @PathParam("path") PathSegment pathSegment, Map<String, String> jobContentXmlString) throws JobCreationRestException, NotConnectedRestException, PermissionRestException, SubmissionClosedRestException, IOException {
    checkAccess(sessionId, "plannings");
    Map<String, String> jobVariables = workflowVariablesTransformer.getWorkflowVariablesFromPathSegment(pathSegment);
    if (jobContentXmlString == null || jobContentXmlString.size() != 1) {
        throw new JobCreationRestException("Cannot find job body: code " + HttpURLConnection.HTTP_BAD_REQUEST);
    }
    Map<String, Object> requestBody = new HashMap<>(2);
    requestBody.put("variables", jobVariables);
    requestBody.put("xmlContentString", jobContentXmlString.entrySet().iterator().next().getValue());
    Response response = null;
    try {
        ResteasyClient client = new ResteasyClientBuilder().build();
        ResteasyWebTarget target = client.target(PortalConfiguration.JOBPLANNER_URL.getValueAsString());
        response = target.request().header("sessionid", sessionId).post(Entity.entity(requestBody, "application/json"));
        if (HttpURLConnection.HTTP_OK != response.getStatus()) {
            throw new IOException(String.format("Cannot access resource %s: code %d", PortalConfiguration.JOBPLANNER_URL.getValueAsString(), response.getStatus()));
        }
        return response.readEntity(String.class);
    } finally {
        if (response != null) {
            response.close();
        }
    }
}
Example 11
Project: joreman-master  File: ForemanClientFactory.java View source code
public static ForemanAPI createAPI(String url, String userName, String password) {
    // parse given url and determine which port should be used
    URL parsedUrl;
    try {
        parsedUrl = new URL(url);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    int port = parsedUrl.getPort();
    if (port == -1) {
        logger.debug("Port was omitted, using a default port for given protocol");
        port = parsedUrl.getDefaultPort();
    }
    logger.info("Creating a new proxy - host: {}, port: {}, protocol: {}, user: {}", parsedUrl.getHost(), port, parsedUrl.getProtocol(), userName);
    // Configure HttpClient to authenticate preemptively by prepopulating the authentication data cache.
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    AuthScheme basicAuth = new BasicScheme();
    authCache.put(new HttpHost(parsedUrl.getHost(), port, parsedUrl.getProtocol()), basicAuth);
    // Add AuthCache to the execution context
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    // Create client executor and proxy
    ClientConnectionManager cm = new PoolingClientConnectionManager();
    // this is ugly hack to ignore certification validation
    if (parsedUrl.getProtocol().equalsIgnoreCase("https")) {
        HTTPHelper.makeConnManagerTrustful(cm);
    }
    DefaultHttpClient httpClient = new DefaultHttpClient(cm);
    httpClient.getCredentialsProvider().setCredentials(org.apache.http.auth.AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient, localContext);
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    client.register(ClientErrorResponseFilter.class);
    client.register(JacksonJaxbJsonProvider.class);
    client.register(JacksonContextResolver.class);
    client.register(AddVersionHeaderRequestFilter.class);
    ResteasyWebTarget target = client.target(url);
    return target.proxy(ForemanAPI.class);
}
Example 12
Project: bugsnag-logback-master  File: Sender.java View source code
/**
     * Sends the given {@code notification}, but no-ops when the sender was not yet started.
     *
     * @param notification the {@link NotificationVO} to send
     */
public void send(final NotificationVO notification) {
    if (isStopped()) {
        return;
    }
    Response response = null;
    try {
        final ResteasyWebTarget resteasyWebTarget = (ResteasyWebTarget) client.target(endpoint);
        final NotifierResource notifierResource = resteasyWebTarget.proxy(NotifierResource.class);
        response = notifierResource.sendNotification(notification);
        final int statusCode = response.getStatus();
        final boolean isOk = StatusCode.OK == statusCode;
        if (isOk) {
            contextAware.addInfo("Successfully delivered notification to bugsnag.");
        } else if (isExpectedErrorCode(statusCode)) {
            contextAware.addError("Could not deliver notification to bugsnag, got http status code: " + statusCode);
        } else {
            contextAware.addError("Unexpected http status code: " + statusCode);
        }
    } catch (final Throwable throwable) {
        contextAware.addError("Could not deliver notification, unexpected exception occurred.", throwable);
    }
    if (response != null) {
        response.close();
    }
}
Example 13
Project: capedwarf-blue-master  File: OAuthLoginProductionAuthHandler.java View source code
private Urls getUrls() {
    if (urls == null) {
        synchronized (this) {
            if (urls == null) {
                ResteasyClient client = new ResteasyClientBuilder().build();
                ResteasyWebTarget target = client.target(URLS_ENDPOINT);
                Response response = target.request().accept("application/json").get();
                urls = response.readEntity(Urls.class);
            }
        }
    }
    return urls;
}
Example 14
Project: quickstart-master  File: JaxRsClient.java View source code
/**
     * 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());
    // Using the RESTEasy libraries, initiate a client request
    ResteasyClient client = new ResteasyClientBuilder().build();
    // Set url as target
    ResteasyWebTarget target = client.target(url);
    // Be sure to set the mediatype of the request
    target.request(mediaType);
    // Request has been made, now let's get the response
    Response response = target.request().get();
    result = response.readEntity(String.class);
    response.close();
    // 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
    System.out.println("\n*** Response from Server ***\n");
    System.out.println(result);
    System.out.println("\n===============================================");
    return result;
}
Example 15
Project: DevNation2014-master  File: NSPClient.java View source code
/**
    * Factory method to create the INSP interface proxy
    * @param baseURL - the NSP server base rest url
    * @return INSP proxy implementation
    */
public static INSP buildINSPProxy(String baseURL) {
    ResteasyClientBuilder rsb = new ResteasyClientBuilder();
    ResteasyClient rsc = rsb.disableTrustManager().build();
    ResteasyWebTarget target = rsc.target(baseURL);
    if (basicAuth != null)
        target.register(basicAuth);
    target.register(new ClientLoggingFilter());
    final INSP proxy = target.proxy(INSP.class);
    /* Wrap the generated proxy in our own implementation to override the following methods where uri encoding does
      not work:
         queryEndpointResourceValue
         subscribeEndpointResource
      */
    INSP wrapper = new INSP() {

        @GET
        @Path("/")
        @Produces("text/plain")
        public String getServerInfo() {
            return proxy.getServerInfo();
        }

        @GET
        @Path("/{domain}/endpoints")
        @Produces("application/json")
        public List<Endpoint> queryEndpoints(String domain, @DefaultValue("true") boolean stale) {
            return proxy.queryEndpoints(domain, stale);
        }

        @GET
        @Path("/{domain}/endpoints")
        @Produces("application/json")
        public String queryEndpointsByType(String domain, String endptType, @DefaultValue("true") boolean stale) {
            return proxy.queryEndpointsByType(domain, endptType, stale);
        }

        @GET
        @Path("/{domain}/endpoints/{endpoint}")
        @Produces("application/json")
        public List<EndpointResource> queryEndpointResources(String domain, String endpoint) {
            return proxy.queryEndpointResources(domain, endpoint);
        }

        @GET
        @Path("/{domain}/endpoints/{endpoint}{resourcePath}")
        @Produces("application/json")
        public String queryEndpointResourceValue(String domain, String endpoint, String resourcePath, @DefaultValue("false") boolean sync, @DefaultValue("false") boolean cacheOnly) {
            try {
                return NSPClient.queryEndpointResourceValue(domain, endpoint, resourcePath, sync, cacheOnly, 10, TimeUnit.SECONDS);
            } catch (InterruptedExceptionExecutionException | TimeoutException |  e) {
                throw new ProcessingException("", e);
            }
        }

        @PUT
        @Path("/{domain}/subscriptions/{endpoint}{resourcePath}")
        @Produces("application/json")
        public String subscribeEndpointResource(String domain, String endpoint, String resourcePath) {
            try {
                return NSPClient.subscribeEndpointResource(domain, endpoint, resourcePath, 10, TimeUnit.SECONDS);
            } catch (InterruptedExceptionExecutionException | TimeoutException |  e) {
                throw new ProcessingException("", e);
            }
        }

        @PUT
        @Path("/{domain}/notification/push-url")
        @Consumes("text/plain")
        public String setNotificationHandler(String domain, String pushURL) {
            return proxy.setNotificationHandler(domain, pushURL);
        }

        @GET
        @Path("{domain}/notification/push-url")
        @Produces("text/plain")
        public String getNotificationHandler(String domain) {
            return proxy.getNotificationHandler(domain);
        }
    };
    return wrapper;
}
Example 16
Project: Repository-master  File: EchoIT.java View source code
@Test
public void basic() throws Exception {
    WebTarget target = client().target(url());
    Echo echo = ((ResteasyWebTarget) target).proxy(Echo.class);
    List<String> result = echo.get("hi");
    assertThat(result, notNullValue());
    assertThat(result, hasItem("foo=hi"));
}
Example 17
Project: StocksAPI-master  File: PseClientITCase.java View source code
@Before
public void setUp() {
    Client client = new ResteasyClientBuilder().httpEngine(new URLConnectionEngine()).register(StocksProvider.class).build();
    ResteasyWebTarget target = (ResteasyWebTarget) client.target("http://www.pse.com.ph/stockMarket");
    pseClient = target.proxy(PseClient.class);
}