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

The following examples show how to use org.jboss.resteasy.client.jaxrs.ResteasyWebTarget. 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: RestClientTransport.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
protected Object buildProxy(ClientTransportConfig transportConfig) throws SofaRpcException {
    SofaResteasyClientBuilder builder = new SofaResteasyClientBuilder();

    ResteasyClient client = builder
        .registerProvider().logProviders()
        .establishConnectionTimeout(transportConfig.getConnectTimeout(), TimeUnit.MILLISECONDS)
        .socketTimeout(transportConfig.getInvokeTimeout(), TimeUnit.MILLISECONDS)
        .connectionPoolSize(Math.max(transportConfig.getConnectionNum(), MIN_CONNECTION_POOL_SIZE))
        .build();

    ProviderInfo provider = transportConfig.getProviderInfo();
    String url = "http://" + provider.getHost() + ":" + provider.getPort()
        + StringUtils.CONTEXT_SEP + StringUtils.trimToEmpty(provider.getPath());
    ResteasyWebTarget target = client.target(url);
    return target.proxy(ClassUtils.forName(transportConfig.getConsumerConfig().getInterfaceId()));
}
 
Example #2
Source File: UmaClientFactory.java    From oxAuth with MIT License 6 votes vote down vote up
public UmaPermissionService createPermissionService(UmaMetadata metadata, ClientHttpEngine engine) {
    ResteasyWebTarget target = newClient(engine).target(new ResteasyUriBuilder().uri(metadata.getPermissionEndpoint()));
    return target.proxy(UmaPermissionService.class);
}
 
Example #3
Source File: UmaClientFactory.java    From oxAuth with MIT License 6 votes vote down vote up
public UmaTokenService createTokenService(UmaMetadata metadata, ClientHttpEngine engine) {
    ResteasyWebTarget target = newClient(engine).target(new ResteasyUriBuilder().uri(metadata.getTokenEndpoint()));
    return target.proxy(UmaTokenService.class);
}
 
Example #4
Source File: CompactDiscsDatabaseClient.java    From maven-framework-project with MIT License 6 votes vote down vote up
public static List<String> getCompactDiscs() {

		ResteasyClient rsClient = new ResteasyClientBuilder().disableTrustManager().build();

		Form form = new Form().param("grant_type", "client_credentials");
		ResteasyWebTarget resourceTarget = rsClient.target(urlAuth);
		resourceTarget.register(new BasicAuthentication("andres", "andres"));
		AccessTokenResponse accessToken = resourceTarget.request().post(Entity.form(form),
				AccessTokenResponse.class);
		try {
			String bearerToken = "Bearer " + accessToken.getToken();
			Response response = rsClient.target(urlDiscs).request()
					.header(HttpHeaders.AUTHORIZATION, bearerToken).get();
			return response.readEntity(new GenericType<List<String>>() {
			});
		} finally {
			rsClient.close();
		}

	}
 
Example #5
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 #6
Source File: RestEasyClientLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void testAddMovie() {

    final ResteasyClient client = new ResteasyClientBuilder().build();
    final ResteasyWebTarget target = client.target(FULL_PATH);
    final ServicesInterface proxy = target.proxy(ServicesInterface.class);

    Response moviesResponse = proxy.addMovie(batmanMovie);
    moviesResponse.close();
    moviesResponse = proxy.addMovie(transformerMovie);

    if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) {
        System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus());
    }

    moviesResponse.close();
    System.out.println("Response Code: " + moviesResponse.getStatus());
}
 
Example #7
Source File: RestEasyClientLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void testAddMovieMultiConnection() {

    final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
    final ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
    final ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    final ResteasyWebTarget target = client.target(FULL_PATH);
    final ServicesInterface proxy = target.proxy(ServicesInterface.class);

    final Response batmanResponse = proxy.addMovie(batmanMovie);
    final Response transformerResponse = proxy.addMovie(transformerMovie);

    if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) {
        System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus());
    }
    if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) {
        System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus());
    }

    batmanResponse.close();
    transformerResponse.close();
    cm.close();

}
 
Example #8
Source File: RestEasyClientLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void testDeleteMovie() {

    final ResteasyClient client = new ResteasyClientBuilder().build();
    final ResteasyWebTarget target = client.target(FULL_PATH);
    final ServicesInterface proxy = target.proxy(ServicesInterface.class);

    Response moviesResponse = proxy.addMovie(batmanMovie);
    moviesResponse.close();
    moviesResponse = proxy.deleteMovie(batmanMovie.getImdbId());

    if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) {
        System.out.println(moviesResponse.readEntity(String.class));
        throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus());
    }

    moviesResponse.close();
    System.out.println("Response Code: " + moviesResponse.getStatus());
}
 
Example #9
Source File: RestEasyClientLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void testUpdateMovie() {

    final ResteasyClient client = new ResteasyClientBuilder().build();
    final ResteasyWebTarget target = client.target(FULL_PATH);
    final ServicesInterface proxy = target.proxy(ServicesInterface.class);

    Response moviesResponse = proxy.addMovie(batmanMovie);
    moviesResponse.close();
    batmanMovie.setTitle("Batman Begins");
    moviesResponse = proxy.updateMovie(batmanMovie);

    if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) {
        System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus());
    }

    moviesResponse.close();
    System.out.println("Response Code: " + moviesResponse.getStatus());
}
 
Example #10
Source File: SchedulerStateRest.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String submitPlannings(String sessionId, PathSegment pathSegment, Map<String, String> jobContentXmlString)
        throws JobCreationRestException, NotConnectedRestException, 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 {
        ResteasyProviderFactory providerFactory = ResteasyProviderFactory.getInstance();
        SchedulerRestClient.registerGzipEncoding(providerFactory);
        ResteasyClient client = new ResteasyClientBuilder().providerFactory(providerFactory).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
Source File: SchedulerRestClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public boolean delete(String sessionId, String dataspacePath, String path, List<String> includes,
        List<String> excludes) throws Exception {
    StringBuffer uriTmpl = (new StringBuffer()).append(restEndpointURL)
                                               .append(addSlashIfMissing(restEndpointURL))
                                               .append("data/")
                                               .append(dataspacePath)
                                               .append('/');

    ResteasyClient client = buildResteasyClient(providerFactory);

    ResteasyWebTarget target = client.target(uriTmpl.toString()).path(path);
    if (includes != null && !includes.isEmpty()) {
        target = target.queryParam("includes", includes.toArray(new Object[includes.size()]));
    }
    if (excludes != null && !excludes.isEmpty()) {
        target = target.queryParam("excludes", excludes.toArray(new Object[excludes.size()]));
    }
    Response response = null;
    try {
        response = target.request().header("sessionid", sessionId).delete();
        if (response.getStatus() != HttpURLConnection.HTTP_NO_CONTENT) {
            if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new NotConnectedRestException("User not authenticated or session timeout.");
            } else {
                throwException(String.format("Cannot delete file(s). Status code: %s", response.getStatus()),
                               response);
            }
        }
        return true;
    } finally {
        if (response != null) {
            response.close();
        }
    }
}
 
Example #12
Source File: SchedulerRestClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public ListFile list(String sessionId, String dataspacePath, String pathname) throws Exception {
    StringBuffer uriTmpl = (new StringBuffer()).append(restEndpointURL)
                                               .append(addSlashIfMissing(restEndpointURL))
                                               .append("data/")
                                               .append(dataspacePath)
                                               .append('/');

    ResteasyClient client = buildResteasyClient(providerFactory);

    ResteasyWebTarget target = client.target(uriTmpl.toString()).path(pathname).queryParam("comp", "list");
    Response response = null;
    try {
        response = target.request().header("sessionid", sessionId).get();
        if (response.getStatus() != HttpURLConnection.HTTP_OK) {
            if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new NotConnectedRestException("User not authenticated or session timeout.");
            } else {
                throwException(String.format("Cannot list the specified location: %s", pathname), response);
            }
        }
        return response.readEntity(ListFile.class);
    } finally {
        if (response != null) {
            response.close();
        }
    }
}
 
Example #13
Source File: SchedulerRestClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public Map<String, Object> metadata(String sessionId, String dataspacePath, String pathname) throws Exception {
    StringBuffer uriTmpl = (new StringBuffer()).append(restEndpointURL)
                                               .append(addSlashIfMissing(restEndpointURL))
                                               .append("data/")
                                               .append(dataspacePath)
                                               .append(escapeUrlPathSegment(pathname));

    ResteasyClient client = buildResteasyClient(providerFactory);

    ResteasyWebTarget target = client.target(uriTmpl.toString());
    Response response = null;
    try {
        response = target.request().header("sessionid", sessionId).head();
        if (response.getStatus() != HttpURLConnection.HTTP_OK) {
            if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new NotConnectedRestException("User not authenticated or session timeout.");
            } else {
                throwException(String.format("Cannot get metadata from %s in %s.", pathname, dataspacePath),
                               response);
            }
        }
        MultivaluedMap<String, Object> headers = response.getHeaders();
        Map<String, Object> metaMap = Maps.newHashMap();
        if (headers.containsKey(HttpHeaders.LAST_MODIFIED)) {
            metaMap.put(HttpHeaders.LAST_MODIFIED, headers.getFirst(HttpHeaders.LAST_MODIFIED));
        }
        return metaMap;
    } finally {
        if (response != null) {
            response.close();
        }
    }
}
 
Example #14
Source File: SchedulerRestClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private static SchedulerRestInterface createRestProxy(ResteasyProviderFactory provider, String restEndpointURL,
        ClientHttpEngine httpEngine) {
    ResteasyClient client = buildResteasyClient(provider);
    ResteasyWebTarget target = client.target(restEndpointURL);
    SchedulerRestInterface schedulerRestClient = target.proxy(SchedulerRestInterface.class);
    return createExceptionProxy(schedulerRestClient);
}
 
Example #15
Source File: RMRestClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private static RMRestInterface createRestProxy(ResteasyProviderFactory provider, String restEndpointURL,
        ClientHttpEngine httpEngine) {
    ResteasyClient client = buildResteasyClient(provider);
    ResteasyWebTarget target = client.target(restEndpointURL);
    RMRestInterface rmRestInterface = target.proxy(RMRestInterface.class);
    return createExceptionProxy(rmRestInterface);
}
 
Example #16
Source File: AbstractScimClient.java    From SCIM-Client with Apache License 2.0 5 votes vote down vote up
AbstractScimClient(String domain, Class<T> serviceClass) {
    /*
     Configures a proxy to interact with the service using the new JAX-RS 2.0 Client API, see section
     "Resteasy Proxy Framework" of RESTEasy JAX-RS user guide
     */
    if (System.getProperty("httpclient.multithreaded") == null) {
        client = new ResteasyClientBuilder().build();
    } else {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        //Change defaults if supplied
        getIntegerProperty("httpclient.multithreaded.maxtotal").ifPresent(cm::setMaxTotal);
        getIntegerProperty("httpclient.multithreaded.maxperroute").ifPresent(cm::setDefaultMaxPerRoute);
        getIntegerProperty("httpclient.multithreaded.validateafterinactivity").ifPresent(cm::setValidateAfterInactivity);

        logger.debug("Using multithreaded support with maxTotalConnections={} and maxPerRoutConnections={}", cm.getMaxTotal(), cm.getDefaultMaxPerRoute());
        logger.warn("Ensure your oxTrust 'rptConnectionPoolUseConnectionPooling' property is set to true");

        CloseableHttpClient httpClient = HttpClients.custom()
	.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
        		.setConnectionManager(cm).build();
        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);

        client = new ResteasyClientBuilder().httpEngine(engine).build();
    }
    ResteasyWebTarget target = client.target(domain);

    scimService = target.proxy(serviceClass);
    target.register(ListResponseProvider.class);
    target.register(AuthorizationInjectionFilter.class);
    target.register(ScimResourceProvider.class);

    ClientMap.update(client, null);
}
 
Example #17
Source File: TokenManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public TokenManager(Config config, Client client) {
    this.config = config;
    ResteasyWebTarget target = (ResteasyWebTarget) client.target(config.getServerUrl());
    if (!config.isPublicClient()) {
        target.register(new BasicAuthFilter(config.getClientId(), config.getClientSecret()));
    }
    this.tokenService = target.proxy(TokenService.class);
    this.accessTokenGrantType = config.getGrantType();

    if (CLIENT_CREDENTIALS.equals(accessTokenGrantType) && config.isPublicClient()) {
        throw new IllegalArgumentException("Can't use " + GRANT_TYPE + "=" + CLIENT_CREDENTIALS + " with public client");
    }
}
 
Example #18
Source File: HttpResourceDownloader.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public <T> T getResource(String sessionId, String url, Class<T> clazz) throws IOException {
    Response response = null;
    try {
        ResteasyWebTarget target = client.target(url);
        response = target.request().header("sessionid", sessionId).get();
        if (responseIsNotHttpOk(response)) {
            throw new IOException(String.format("Cannot access resource %s: code %d", url, response.getStatus()));
        }
        return (T) response.readEntity(clazz);
    } finally {
        if (response != null) {
            response.close();
        }
    }
}
 
Example #19
Source File: StocksRepositoryImpl.java    From phisix with Apache License 2.0 5 votes vote down vote up
public StocksRepositoryImpl() {
	Client pseClient = new ResteasyClientBuilder()
			.httpEngine(new URLConnectionEngine())
			.register(StocksProvider.class)
			.build();
	this.pseClient = ((ResteasyWebTarget) pseClient.target("http://www.pse.com.ph/stockMarket")).proxy(PseClient.class);
	
	// TODO make this async
	Client gaClient = new ResteasyClientBuilder()
			.httpEngine(new URLConnectionEngine())
			.build();
	this.gaClient = ((ResteasyWebTarget) gaClient.target("http://www.google-analytics.com")).proxy(GaClient.class);
}
 
Example #20
Source File: GaClientTest.java    From phisix with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	Client client = new ResteasyClientBuilder()
			.httpEngine(new URLConnectionEngine())
			.register(StocksProvider.class)
			.build();
	ResteasyWebTarget target = (ResteasyWebTarget) client.target("http://www.google-analytics.com");
	gaClient = target.proxy(GaClient.class);
}
 
Example #21
Source File: PseClientTest.java    From phisix with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	Client client = new ResteasyClientBuilder()
			.httpEngine(new URLConnectionEngine())
			.register(StocksProvider.class)
			.build();
	ResteasyWebTarget target = (ResteasyWebTarget) client.target("https://www.pse.com.ph/stockMarket");
	pseClient = target.proxy(PseClient.class);
}
 
Example #22
Source File: ClientFactory.java    From oxAuth with MIT License 5 votes vote down vote up
public IntrospectionService createIntrospectionService(String p_url, ClientHttpEngine engine) {
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    ResteasyWebTarget target = client.target(UriBuilder.fromPath(p_url));
    IntrospectionService proxy = target.proxy(IntrospectionService.class);

    return proxy;
}
 
Example #23
Source File: FidoU2fClientFactory.java    From oxAuth with MIT License 5 votes vote down vote up
public U2fConfigurationService createMetaDataConfigurationService(String u2fMetaDataUri) {
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    ResteasyWebTarget target = client.target(UriBuilder.fromPath(u2fMetaDataUri));
    U2fConfigurationService proxy = target.proxy(U2fConfigurationService.class);

    return proxy;
}
 
Example #24
Source File: FidoU2fClientFactory.java    From oxAuth with MIT License 5 votes vote down vote up
public AuthenticationRequestService createAuthenticationRequestService(U2fConfiguration metadataConfiguration) {
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    ResteasyWebTarget target = client.target(UriBuilder.fromPath(metadataConfiguration.getAuthenticationEndpoint()));
    AuthenticationRequestService proxy = target.proxy(AuthenticationRequestService.class);

    return proxy;
}
 
Example #25
Source File: FidoU2fClientFactory.java    From oxAuth with MIT License 5 votes vote down vote up
public RegistrationRequestService createRegistrationRequestService(U2fConfiguration metadataConfiguration) {
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    ResteasyWebTarget target = client.target(UriBuilder.fromPath(metadataConfiguration.getRegistrationEndpoint()));
    RegistrationRequestService proxy = target.proxy(RegistrationRequestService.class);

    return proxy;
}
 
Example #26
Source File: OauthClientTest.java    From maven-framework-project with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

		String truststorePath = "C:/Users/Andres/jboss/2do_jboss/jboss-as-7.1.1.Final/standalone/configuration/client-truststore.ts";
		String truststorePassword = "changeit";
		truststorePath = EnvUtil.replace(truststorePath);

		KeyStore truststore = loadKeyStore(truststorePath, truststorePassword);

		ResteasyClient client = new ResteasyClientBuilder()
				.disableTrustManager().trustStore(truststore).build();

		Form form = new Form().param("grant_type", "client_credentials");
		ResteasyWebTarget target = client
				.target("https://localhost:8443/oauth-server/j_oauth_token_grant");
		target.register(new BasicAuthentication("andres", "andres"));

		AccessTokenResponse tokenResponse = target.request().post(
				Entity.form(form), AccessTokenResponse.class);
		Response response = client
				.target("https://localhost:8443/discstore/discs")
				.request()
				.header(HttpHeaders.AUTHORIZATION,
						"Bearer " + tokenResponse.getToken()).get();
		try {
			String xml = response.readEntity(String.class);
			System.out.println(xml);
		} finally {
			client.close();
		}

	}
 
Example #27
Source File: PersonsIT.java    From hibernate-demos with Apache License 2.0 5 votes vote down vote up
private Invocation.Builder invocationBuilder(ResteasyWebTarget webTarget, String path) {
	Invocation.Builder builder = path != null ? webTarget.path( path ).request() : webTarget.request();

	builder.acceptEncoding( "UTF-8" );
	builder.accept( MediaType.APPLICATION_JSON );

	return builder;
}
 
Example #28
Source File: RestEasyClientLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void testListAllMovies() {

    final ResteasyClient client = new ResteasyClientBuilder().build();
    final ResteasyWebTarget target = client.target(FULL_PATH);
    final ServicesInterface proxy = target.proxy(ServicesInterface.class);

    Response moviesResponse = proxy.addMovie(transformerMovie);
    moviesResponse.close();
    moviesResponse = proxy.addMovie(batmanMovie);
    moviesResponse.close();

    final List<Movie> movies = proxy.listMovies();
    System.out.println(movies);
}
 
Example #29
Source File: RestEasyClientLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void testMovieByImdbId() {

    final String transformerImdbId = "tt0418279";

    final ResteasyClient client = new ResteasyClientBuilder().build();
    final ResteasyWebTarget target = client.target(FULL_PATH);
    final ServicesInterface proxy = target.proxy(ServicesInterface.class);

    final Response moviesResponse = proxy.addMovie(transformerMovie);
    moviesResponse.close();

    final Movie movies = proxy.movieByImdbId(transformerImdbId);
    System.out.println(movies);
}
 
Example #30
Source File: Keycloak.java    From keycloak with Apache License 2.0 5 votes vote down vote up
Keycloak(String serverUrl, String realm, String username, String password, String clientId, String clientSecret, String grantType, Client resteasyClient, String authtoken) {
    config = new Config(serverUrl, realm, username, password, clientId, clientSecret, grantType);
    client = resteasyClient != null ? resteasyClient : newRestEasyClient(null, null, false);
    authToken = authtoken;
    tokenManager = authtoken == null ? new TokenManager(config, client) : null;

    target = (ResteasyWebTarget) client.target(config.getServerUrl());
    target.register(newAuthFilter());
}