JX-RS 2.0 client API with Apache CFX 3.1.8 client implementation Thread Safety concern - java-ee-7

I am writing REST client using JX-RS 2.0 client API and have Apache CXF 3.1.8 client as implementation in classpath.
My gradle dependency
compile group: 'org.apache.cxf', name: 'cxf-rt-rs-client', version: '3.1.8'
I plan to client the Client instance with root url only once and use it to multiple create WebTarget at runtime as needed by the application. I want to reuse Client object because https://docs.oracle.com/javaee/7/api/javax/ws/rs/client/Client.html this says it expensive operation to create and destroy client object.
String baseUrl = "http://localhost:9081/rest-service/rest/";
Client client = ClientBuilder.newClient();
client.register(JacksonJsonProvider.class);
client.register(CustomObjectMapperProvider.class);
Use the client object to create WebTarget
WebTarget webTarget = client.target(baseUrl + path);
I understand that under the cover org.apache.cxf.jaxrs.client.WebClient (the CXF's client implementation) is used. http://cxf.apache.org/docs/jax-rs-client-api.html#JAX-RSClientAPI-ThreadSafety link says that both CXF WebClient and ProxyClient are not thread safe by default. As per this link there a threadSafe boolean flag that we can set to true while creating CXFs WebClient or ProxyClient.
In my code I want to use standard JX-RS 2.0 client APIs/interfaces and not CXF specific classes like WebClient or ProxyClient.
Questions -
If I instantiate the standard Client object using code above, is
it thread safe? Is it ok to create it once and use it multiple time
to WebTarget of different resources?
List item If it is not thread safe how to achieve thread safety where I want to reuse client object?

Related

correct pattern of Ktor's HttpClient usage

What's the correct pattern of usage for HttpClient in KTOR. Should I use it like singleton per app lifecycle, or should I create it per each request?
I would say that you may have more than one client per app if you need to connect to more than one logical services.
But if you are dealing with one single HTTP server it's better to have one client because it establishes and holds a connection with server. It also allocates the following resources: prepared threads, coroutines and connections. If you have multiple clients you can potentially run out of these resources.
Should I use it like singleton per app lifecycle, or should I create it per each request
Creation of a http client instance is usually a bit resource intensive, hence you should not create an instance of client for every request. You should create just one http client instance per app's lifecycle, injected wherever required in your app, ensuring that
you have used the right http client configurations like the thread pool size, timeouts etc
you are releasing the resources upon the app's shutdown.
The client can be configured with HttpClientEngineConfig(doc) or any of its inheritors. More details in the documentation here.
It is better to reuse the HttpClient instance for performance reasons if the requests can be performed using the same configuration/settings.
But in some cases you have to create separate instances because the features of a HttpClient are determined by the engine and the plugins specified when creating the instance.
For example when using bearer authentication the HttpClient instances can be reused only when sending requests to the same resource server (with the same authorization configuration).
Similarly, if two requests should use different timeouts then they can be performed only by different HttpClients.
To summarize, a HttpClient instance should be created per "feature set", determined by the required engine and plugins.

Self Hosted WCF via MSMQ Simple Injector Lifestyle

I'm using WCF (self-hosted) using MSMQ bindings and wanted to use the Per WCF request lifestyle with SimpleInjector. I setup my code as:
Dim httpLifecycle = New SimpleInjector.Integration.Wcf.WcfOperationLifestyle(True)
container.Register(of ISomeType, SomeType)(httpLifecycle)
Over MSMQ, this doesn't work, as I get the error:
The dependency resolver for the web services host failed to
initialize: SimpleInjector.ActivationException: The registered
delegate for type ILoader threw an exception. The ISomeType is
registered as 'WCF Operation' lifestyle, but the instance is requested
outside the context of a WCF Operation.
Is there a way the WCF request lifestyle an work with MSMQ?
I ended up using a per execution scope and defining that scope within the WCF service operation itself. By scoping it that way, it ensured the dependencies opened and closed when I wanted them to.
I needed to include execution context scoping.

SOAP Connection WCF

I am connecting to a 3rd party API. They have provided me with a WSDL file which i have added by using a web reference. Is it possible to connect via SOAP and send multiple messages across the same connection?
I have created the client from the proxy classes but there doesn't appear to be a Open() or a Close() method. Does the client connect and disconnect when a method is called?
SampleService client = new SampleService
client.SampleMethod();
Edit:
I have added a "Service Reference" from the WSDL file. The client is constructed from the "PortType" in the WSDL file. There inst a Close() or a Abort() method. The only method on SampleService.client is SampleMethod()
They have provided me with a WSDL file which i have added by using a web reference.
In such case you are not using WCF but ASP.NET WebServices client. In your case it is probably not a big difference but ASP.NET WebServices are mostly for backward compatibility when moving legacy code to new version of .NET framework. Today you should rather use Add Service Reference to use WCF as other also recommended.
SOAP Connection WCF
There is nothing like SOAP connection. SOAP is application protocol tunneled through some transport protocol. In your case the transport protocol is HTTP.
I have created the client from the proxy classes but there doesn't
appear to be a Open() or a Close() method. Does the client connect and
disconnect when a method is called?
You don't need to call Open or Close. This is all handled in low level layer of communication stack. By default all HTTP client applications use something called persistent connection. It means that when you access some host for the first time TCP connection is established between your client computer and server hosting target resource. Subsequent calls reuse the same connection. If the connection is not in use for some predefined time (both client and server can have different timeouts) the connection is closed and next time the client wants to call the server it will create a new connection (again you don't need to bother with this).
So calling the method on SOAP proxy in your application can automatically open connection if no one exists. You don't need to explicitly close the connection but you should dispose the proxy to release its resources. Connection itself can live after the proxy was disposed and can be reused by another proxy.
You should add a service reference (WCF) instead of using the outdated Web Reference.
Then follow the bellow pattern:
try
{
SampleServiceClient client = new SampleServiceClient();
client.SampleMethod();
//... Make as many calls to as many methods as you like.
client.SampleMethod();
client.Close();
}
catch (Exception e)
{
//client is unusable once an exception occurs.
...
client.Abort();
throw;
}
You need to use the Add Service Reference rather than Add Web Reference. And once added you can invoke the service as shown:
using(SampleServiceClient client = new SampleServiceClient())
{
var response = client.SampleMethod();
}
Hope that helps.

Does client consuming WCF service require Interface definition?

I have been going through the book "Learning WCF" trying to get my head around creating and using WCF web services. The first part of the book walks the reader through creating and then consuming a simple "Hello World" web service.
The problem I am having is that the client application seems to have no know the structure of the WCF Interface when calling it. How can this be necessary if a web service could be called from any number of programming languages?
I have listed the relevant example code below ...
Here is the code for the Interface
[ServiceContract(Namespace="http: //www.thatindigogirl.com/samples/2006/06")]
public interface IHelloIndigoService
{
[OperationContract]
string HelloIndigo();
}
Here is the code for the Service that hosts the web service
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(HelloIndigo.HelloIndigoService) ,
new Uri("http: //localhost: 8000/HelloIndigo")))
{
host. AddServiceEndpoint(typeof(HelloIndigo. IHelloIndigoService) ,
new BasicHttpBinding(), "HelloIndigoService");
host. Open( );
Console. WriteLine("Press <ENTER> to terminate the service host") ;
Console. ReadLine();
}
}
Here is the code for the client app that consumes the WCF service
This is where I get confused. Since this client application could be any language capable of calling a web service why is there a necessity of knowing the definition of the interface?
using System. ServiceModel;
[ServiceContract(Namespace = "http: //www.thatindigogirl.com/samples/2006/06")]
public interface IHelloIndigoService
{
[OperationContract]
string HelloIndigo( );
}
static void Main(string[ ] args)
{
EndpointAddress ep = new
EndpointAddress("http: //localhost: 8000/HelloIndigo/HelloIndigoService") ;
IHelloIndigoService proxy = ChannelFactory<IHelloIndigoService>.
CreateChannel(new BasicHttpBinding(), ep);
string s = proxy. HelloIndigo();
Console. WriteLine(s) ;
Console. WriteLine("Press <ENTER> to terminate Client.") ;
Console. ReadLine();
}
Am I missing an important point here? Perhaps my understanding of what is needed to consume a web is lacking. My goal is to be able to use WCF to create a .NET service that could be called from any programming language or environment.
Might anyone suggest a good tutorial on creating "cross platform consumable" web services from within .NET? Thanks!
This approach is based on shared interface (the book acutally does not share the interface but instead it uses local copy) and is successfully applied in environment where both client and server are written in .NET. This approach is not usable for interoperability or SOA solutions.
Other approach uses metadata exposed by the service. Metadata are defined as WSDL document plus several XSD documents. These metadata files are way to provide information about your service to both .NET and non .NET developers. The book contains definition of Metadata (mex) endpoint so you will definitely read about that.
Using metadata in .NET means creating service proxy. You can do it automatically using Visual studio's Add service reference or command line utility svcutil.exe. Anyway generated proxy code will probably still contain the interface created from metadata. It is used to create transparent abstraction of the service for the client.
'The interface' doesn't mean a .NET interface file, it means the more general programming interface - a set of objects with properties, and methods with parameters. This is also called the service contract.
The reason that the client and the service need to share (i.e. both know about) the interface is simple when you think about it - if the client doesn't know the interface, how do they know what operations are available and what the expected request/response objects should look like?
Every WCF service is composed of
A - address
B - binding
C - contract
The contract is declared using an interface on the serverside. It declares which methods are available to the client. If you are using a http binding you can invoke a service operation by issuing a http request (using a http client in any library or language - or even a web browser) pointed at the correct address. So the client does not need any interface reference at all. It just needs to follow the ABC of the service.
Here is a nice blog on WCF and Java interopability.
To answer your question on how to develop 'cross platform consumable' web services, consider the REST approach. Making REST-style web services truly makes them independent of the platform that consumes them. Simply put, they use the already well established HTTP protocols everything supports: GET and POST Http methods.
You could then have a Java app simply make POST calls to your WCF services with your own custom XML content in the payload without having to fiddle with more complex stuff like making SOAP wrappers and the like. Check out Rob Bagby's article on REST:
http://www.robbagby.com/rest/rest-in-wcf-part-i-rest-overview/

Adding a web Proxy for a client created with NetCFSvcUtil with credentials

We have an implemented a WCF service for sync framework communication with the guidance of http://wcfguidanceformobile.codeplex.com/ . The client in created by NetCFSvcUtil.
We have run into a problem when web proxy support is needed.
How can you enable credentials with it?
On the HttpTransportBindingElement we can set the proxyadress, but since our proyx requires login this won't do it.
When trying to set UseDefaultWebProxy to true it still won't use any credentials. It connects to the proxy but gets
Error 407: Proxy authentication required
Can't find any information about it on SO or msdn. Anyone got a clue where to look?
In Compact Framework, use the static GlobalProxySelect.Select property to set the global proxy used by all HttpWebRequests, including WCF service calls.
GlobalProxySelect.Select = new WebProxy(...);
For this to work in WCF, the HttpTransportBindingElement properties must be
ProxyAddress = null (default)
UseDefaultWebProxy = true (default)
The GlobalProxySelect class is deprecated in the full framework, so you should use WebRequest.DefaultWebProxy instead.