下面列出了javax.ws.rs.client.Client#register ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testGetBookSpecTemplate() {
String address = "http://localhost:" + PORT + "/bookstore/{a}";
Client client = ClientBuilder.newClient();
client.register((Object)ClientFilterClientAndConfigCheck.class);
client.register(new BTypeParamConverterProvider());
client.property("clientproperty", "somevalue");
WebTarget webTarget = client.target(address).path("{b}")
.resolveTemplate("a", "bookheaders").resolveTemplate("b", "simple");
Invocation.Builder builder = webTarget.request("application/xml").header("a", new BType());
Response r = builder.get();
Book book = r.readEntity(Book.class);
assertEquals(124L, book.getId());
assertEquals("b", r.getHeaderString("a"));
}
private static Client getJAXRSClient(boolean skipSSLValidation) throws KeyManagementException, NoSuchAlgorithmException {
ClientBuilder cb = ClientBuilder.newBuilder();
cb.connectTimeout(10, TimeUnit.SECONDS);
Client newClient;
if (skipSSLValidation) {
SSLContext nullSSLContext = SSLContext.getInstance("TLSv1.2");
nullSSLContext.init(null, nullTrustManager, null);
cb.hostnameVerifier(NullHostnameVerifier.INSTANCE)
.sslContext(nullSSLContext);
newClient = cb.build();
} else {
newClient = cb.build();
}
newClient.register(JacksonJsonProvider.class);
return newClient;
}
@Test
public void testGetProperties() {
// String port = System.getProperty("liberty.test.port");
String port = System.getProperty("boost_http_port");
// String port = "9000";
String url = "http://localhost:" + port + "/";
Client client = ClientBuilder.newClient();
client.register(JsrJsonpProvider.class);
WebTarget target = client.target(url + "system/properties");
Response response = target.request().get();
assertEquals("Incorrect response code from " + url, 200, response.getStatus());
JsonObject obj = response.readEntity(JsonObject.class);
assertEquals("The system property for the local and remote JVM should match", System.getProperty("os.name"),
obj.getString("os.name"));
response.close();
}
@Test
public void testGetProperties() {
// String port = System.getProperty("liberty.test.port");
String port = System.getProperty("boost_http_port");
// String port = "9000";
String url = "http://localhost:" + port + "/";
Client client = ClientBuilder.newClient();
client.register(JsrJsonpProvider.class);
WebTarget target = client.target(url + "system/properties");
Response response = target.request().get();
assertEquals("Incorrect response code from " + url, 200, response.getStatus());
JsonObject obj = response.readEntity(JsonObject.class);
assertEquals("The system property for the local and remote JVM should match", System.getProperty("os.name"),
obj.getString("os.name"));
response.close();
}
private void authenticate(Client client, RestSBDevice device) {
AuthenticationScheme authScheme = device.authentication();
if (authScheme == AuthenticationScheme.NO_AUTHENTICATION) {
log.debug("{} scheme is specified, ignoring authentication", authScheme);
return;
} else if (authScheme == AuthenticationScheme.OAUTH2) {
String token = checkNotNull(device.token());
client.register(OAuth2ClientSupport.feature(token));
} else if (authScheme == AuthenticationScheme.BASIC) {
String username = device.username();
String password = device.password() == null ? "" : device.password();
client.register(HttpAuthenticationFeature.basic(username, password));
} else {
// TODO: Add support for other authentication schemes here.
throw new IllegalArgumentException(String.format("Unsupported authentication scheme: %s",
authScheme.name()));
}
}
@Test
public void shouldNotTransformAuthenticationExceptionIntoMappedException() throws AuthenticationException {
when(AuthenticatorApp.getMockAuthenticator().authenticate(any(BasicCredentials.class))).thenThrow(new AuthenticationException("test"));
final Client client = new JerseyClientBuilder(new MetricRegistry())
.using(executorService, Jackson.newObjectMapper())
.build("dropwizard-app-rule");
client.register(HttpAuthenticationFeature.basicBuilder()
.nonPreemptive()
.credentials("user", "stuff")
.build());
final Response response = client
.target(URI.create("http://localhost:" + RULE.getLocalPort() + "/auth"))
.request()
.get(Response.class);
assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
verify(AuthenticatorApp.getMockAuthenticator(), times(1)).authenticate(any(BasicCredentials.class));
verifyZeroInteractions(AuthenticatorApp.getTenacityContainerExceptionMapper());
verify(AuthenticatorApp.getTenacityExceptionMapper(), times(1)).toResponse(any(HystrixRuntimeException.class));
}
@Test
public void testGetSetEntityStreamLambda() {
String address = "http://localhost:" + PORT + "/bookstore/entityecho";
String entity = "BOOKSTORE";
Client client = ClientBuilder.newClient();
client.register((ClientRequestFilter) context -> {
context.setEntityStream(new ReplacingOutputStream(context.getEntityStream(), 'X', 'O'));
});
WebTarget target = client.target(address);
Response response = target.request().post(
Entity.entity(entity.replace('O', 'X'), "text/plain"));
assertEquals(entity, response.readEntity(String.class));
}
@Before
public void setup() throws Exception {
// create ResourceConfig from Resource class
ResourceConfig rc = new ResourceConfig();
MultiCube cube = new MultiCubeTest(null);
rc.registerInstances(new CubeResource(cube));
rc.register(JsonIteratorConverter.class);
// create the Grizzly server instance
httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, rc);
// start the server
httpServer.start();
// configure client with the base URI path
Client client = ClientBuilder.newClient();
client.register(JsonIteratorConverter.class);
webTarget = client.target(baseUri);
}
@Before
public void setup() throws Exception {
//create ResourceConfig from Resource class
ResourceConfig rc = new ResourceConfig();
cube = new MultiCubeImpl(null);
rc.registerInstances(new CubeResource(cube));
rc.register(JsonIteratorConverter.class);
//create the Grizzly server instance
httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, rc);
//start the server
httpServer.start();
//configure client with the base URI path
Client client = ClientBuilder.newClient();
client.register(JsonIteratorConverter.class);
webTarget = client.target(baseUri);
}
@Test
public void testGetBookSpec() {
String address = "http://localhost:" + PORT + "/bookstore/bookheaders/simple";
Client client = ClientBuilder.newClient();
client.register((Object)ClientFilterClientAndConfigCheck.class);
client.register(new BTypeParamConverterProvider());
client.property("clientproperty", "somevalue");
WebTarget webTarget = client.target(address);
Invocation.Builder builder = webTarget.request("application/xml").header("a", new BType());
Response r = builder.get();
Book book = r.readEntity(Book.class);
assertEquals(124L, book.getId());
assertEquals("b", r.getHeaderString("a"));
}
public void init(
Stage.Context context,
List<Stage.ConfigIssue> issues,
Client webClient
) throws AuthenticationFailureException, IOException, StageException {
if (credentialsGrantType == OAuth2GrantTypes.JWT) {
prepareEL(context, issues);
if (isRSA()) {
privateKey = parseRSAKey(key.get(), context, issues);
}
}
if (issues.isEmpty()) {
String accessToken = obtainAccessToken(webClient);
if (!accessToken.isEmpty()) {
String token = parseAccessToken(accessToken);
if (token.isEmpty()) {
issues.add(context.createConfigIssue("#0",
"",
HTTP_33,
ACCESS_TOKEN_RFC,
ACCESS_TOKEN_SF,
ACCESS_TOKEN_GOOGLE
));
} else {
filter = new OAuth2HeaderFilter(token);
webClient.register(filter);
}
}
}
}
@Test
public void testGetBookSpecProviderWithFeature() {
String address = "http://localhost:" + PORT + "/bookstore/bookheaders/simple";
Client client = ClientBuilder.newClient();
client.register(new ClientTestFeature());
WebTarget target = client.target(address);
BookInfo book = target.request("application/xml").get(BookInfo.class);
assertEquals(124L, book.getId());
book = target.request("application/xml").get(BookInfo.class);
assertEquals(124L, book.getId());
}
protected Client initClient(int rt, int ct) {
ClientConfig clientConfig = new ClientConfig();
clientConfig.property(ClientProperties.CONNECT_TIMEOUT, ct);
clientConfig.property(ClientProperties.READ_TIMEOUT, rt);
ClientBuilder.newBuilder().register(JacksonFeature.class);
Client client = ClientBuilder.newClient(clientConfig);
client.register(JacksonFeature.class);
JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
provider.setMapper(JacksonUtil.getMapper());
client.register(provider);
return client;
}
public final static void main(String[] args) throws Exception {
Client client = ClientBuilder.newClient();
client.register(RxObservableInvokerProvider.class);
WebTarget target = client.target("http://localhost:8080/jaxrs-async/rest/ejb");
target.request()
.rx(RxObservableInvoker.class)
.get(String.class)
.subscribe(new Observer<String>() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
System.out.println("onError:" + e.getMessage());
}
@Override
public void onNext(String t) {
System.out.println("onNext:" + t);
}
});
}
public final static void main(String[] args) throws Exception {
Client client = ClientBuilder.newClient();
client.register(RxListenableFutureInvokerProvider.class);
WebTarget target = client.target("http://localhost:8080/jaxrs-async/rest/ejb");
ListenableFuture<String> future = target.request()
.rx(RxListenableFutureInvoker.class)
.get(String.class);
FutureCallback<String> callback = new FutureCallback<String>() {
@Override
public void onSuccess(String result) {
System.out.println("result :" + result);
}
@Override
public void onFailure(Throwable t) {
System.out.println("error :" + t.getMessage());
}
};
Futures.addCallback(future, callback, Executors.newFixedThreadPool(10));
System.out.println("ListenableFuture:" + future.get());
}
@Inject
public JerseyConfig(Tracer tracer) {
Client client = ClientBuilder.newClient();
client.register(new Builder(tracer).build());
register(new ServerTracingDynamicFeature.Builder(tracer)
.build());
register(new TestHandler(tracer, client));
}
private WebTarget webTarget(String path)
{
Client client = ClientBuilder.newClient();
client.register(JacksonFeature.class);
client.register(BitemporalBankJacksonObjectMapperProvider.class);
return client.target("http://localhost:9998").path(path);
}
public MLModelRegistryClient(String catalogURL, Client client) {
this.modelRegistryURL = String.join("/", catalogURL, "ml", "models");
this.client = client;
client.register(MultiPartFeature.class);
}
public void configureClient(@Observes @Configuring Client client) {
client.register(this);
}
private void authenticate(Client client, String username, String password) {
client.register(HttpAuthenticationFeature.basic(username, password));
}