Persistence of service for multiple requests - web-services

I had originally thought that a particular "service interface" and in my example one that inherits from ServiceStack.ServiceInterface.Service is recreated with every request. I recently found out that perhaps it's not the case, as dependencies( and members in general) are retaining internal state. I was just hoping if someone could point me in the right direction as to expected behavior and why it behaves this way. I'm primarily interested in two scenarios, one for IIS hosting, and one for VS hosting / debugging.

A Service in ServiceStack is registered and autowired like any other IOC dependency. Every request a new instance of the Service is created and autowired with its dependencies.
Whether the service is autowired with existing instances or not depends on how the dependency is registered, e.g if you use the built-in Funq IOC:
By default dependencies are registered with Singleton scope, i.e. it will inject the same instance everytime:
container.Register<IFoo>(c => new Foo());
container.Register<IFoo>(c => new Foo()).ReusedWithin(ReuseScope.Container);
You can also specify RequestScope so a new instance is created and injected per request:
container.Register<IFoo>(c => new Foo()).ReusedWithin(ReuseScope.Request);
Finally there's transient scope where a new instance is created and injected each time:
container.Register<IFoo>(c => new Foo()).ReusedWithin(ReuseScope.None);
To re-cap a new instance of your service is indeed created per request, but whether you get a new instance or not depends on the Registration scope of your dependencies:
public class MyService : Service {
public IFoo Foo { get; set; } // auto-wired using above registration rules
}

Related

How to receive public and private IPs while creating an instance in GCP using java sdks?

Whenever I create a virtual machine in AZURE and AWS with java SDK, the return object always give me public and private IPs.
Now I am exploring GCP java SDK and have successfully created an instance using it but how will I get ip addresses in return?
Instance instance = new Instance()
.setName(createInstance.getInstanceName())
.setMachineType(createInstance.getMachineTypeUrl()) //can provide 'prepare url' option
.setDisks(attachedDiskList)
.setNetworkInterfaces(networkInterfaceList)
.setCpuPlatform(createInstance.getCpuPlatform());
Operation instanceCreated = gcpCredentialService.getGcpClient()
.instances()
.insert(GcpContext.getContext().getServiceAccountProjectId(), completeRegion, instance)
.execute();
This object instanceCreated does not return public and private IPS in return.
I am new to GCP and struggling in this part.
Google's API (!) documentation is excellent and I encourage you to become familiar with navigating it as it will prove very helpful. While each SDK (library) is documented too, the underlying REST API methods and types are definitive and it should be straightforward to work upwards into your preferred language(s).
Compute Engine's [instances.insert] returns an Operation because the method is asynchronous. You'll need to query the Operation's state for successful completion of the operation (i.e. instance created) and then you can query the instance (instances.get, the response to which contains the properties that you need.
The documentation contains:
a (trivial but realistic) example code for the method.
guidance for using Operations.
required permissions for this task

Java Jersey REST Webservice: Not possible to create a singleton bean over all cluster nodes

i'd like to have an singleton object in my Jersey 1.19.1 webservice, which is the same instance over all my Glassfish nodes. This is my current implementation:
#Singleton
#ApplicationScoped
#Stateless
public class ValueObject {
public long downloads = 0;
}
and
#Path("downloads")
public class Downloads {
#InjectParam
private ValueObject singleton;
}
The counter is increased when a file is downloaded.
After downloading a file and asking for the downloadCounter 1 and 0 is returned depending on which of the two Glassfish nodes processed the request.
My goal is to get always 1. How can i achieve that?
Without #ApplicationScoped or using #Stateful instead of #Stateless leads to the same result.
Regards
John
This is not possible with GlassFish. As discussed in this StackOverflow answer, the EJB #Singleton annotation will have one instance per JVM, as per the EJB 3.1 spec:
A Singleton session bean is a session bean component that is instantiated once per application. In cases where the container is distributed over many virtual machines, each application will have one bean instance of the Singleton for each JVM
The answer also mentions that WildFly 10 has a mechanism to support this, but this is a proprietary solution, and not one found in GlassFish.
A solution is currently being investigated for Payara Server, though this is not yet implemented.

Service Fabric Unit Tesitng a Reliable Actor Method which reads config info from Settings.xml and App.Config

I am currently working on a Service Fabric project, where in one of our reliable actors we make calls to a SOAP service. For these calls we read a couple of parameters from the Actor's Settings.xml and also - the SOAP endpoint address and binding information from the App.config file (actually the latter is done implicitly by the generated service proxy class for the SOAP service).
Now I am trying to get the unit testing work with xUnit + ServiceFabric.Mocks. To test an Actor specific method I go through:
1) Creating a "MockCodePackageActivationContext"
2) Creating a "StatefulServiceContext" using the instance of the activation context in step 1.
3) Instantiate the Actor with the code below
MyActor target = new MyActor(
new ActorService(
context: serviceContext,
actorTypeInfo: ActorTypeInformation.Get(typeof(MyActor)),
stateManagerFactory: (actorBase, stateProvider) => new MockActorStateManager()
),
new ActorId(Guid.NewGuid())
);
4) I call target.MyMethod() which breaks due to inability to read config info either from the Settings.xml or the App.config file
I made a test where target.MyMethod_Test() does not read anything from config and it was successful.
Anyone who stumbled upon similar thing? How did you solve it?
You could create a separate class that provides configuration data. Create an interface for it and then inject it in the Actor constructor, in Program Main. (Passing the service context into the new class for example.)
Also create a mock implementation of the interface and pass that one to the Actor for testing purposes.

Truncated Java object when passing through JAX-WS WebService

I am currently working on a project that uses JAX-WS webservices in Java.
The global topic is this : the user creates locally an object, let's say an Agent. He calls a first webservice and passes its Agent to the webservice. The webservice treats the Agent (modifies its properties : e.g. lifepoints), and passes it to another webservice. This call is made from the first webservice, so the user has nothing to do in the process.
After a chain of several webservices, the user retrieves the Agent that has been modified.
The aim of my project is to design 2 parts:
a framework that specifies the behaviour previously described : webservices, Agents and the process of migration
a demo application using my framework. The main difference is the addition of a GUI and a new class Avatar, that extends Agent. So the migration process is still being done "by the framework", with Agent objects.
The following code shows a simple example of how I call my webservice, host my Avatar, then retrieves the agent from the service :
// connection to the server
URL endpoint= new URL("http://SERVER/tomcat/KiwiBidonDynamique/ServiceWebBidonDeDadou?wsdl");
QName serviceName=new QName("http://avatar/","ServeurKiwiBidonService");
Service service = Service.create(endpoint, serviceName);
WebService port = service.getPort(WebService.class);
Avatar myAvatar = new Avatar(1, "Jack the Ripper");
port.hostAgent(myAvatar);
// some process on the service...
Avatar myAvatarTransformed = (Avatar) port.getAgent("AgentNumberOne");
When I do that, I get an exception on the final line :
Exception in thread "main" java.lang.ClassCastException: agent.Agent cannot be cast to avatar.Avatar
After a lot of log reading, I guess the reason is the way the webservice works. When being called, my Avatar given in parameter is marshalled in my JVM then unmarshalled on the service, but the service only constructs an Agent when it unmarshalles. Doing so, it truncates the data specific to the Avatar. Then when I try to retrieve my Agent from the service, it cannot be cast to an Avatar.
Is there a way to keep the Avatar information while processing as an Agent on the service ?
Can I write my own marshalling/unmarshalling somehow ?
Thanks a lot.
If your webservice has Agent element defined as incoming data, then no it is not possible to unmarshall it into an inherited class. I guess it would be possible to write your own marshaller but it is not as easy as it sounds (I would advise against it). Either write a separate WS for each class (messy) or make the incoming data have an element that can store additional structures, like type:any (also messy). The truth is WS are not exactly OO.

Should the Entity Manager be closed by ourself in EJB?

I am new to EJB. I want to know that the EnityManger should be closed by ourself (em.close() )of a stateless or statefull sessionbeans in EJB 3.0 ( may be inside a method where #preDestroy annotation is used )? Is it closed by the ejb container, release its resources and we don't need to dwell EnitityManger after retrieving required DB data? What are the services we should stop or close ourselves ?
In EJB there is normally no need to do any of that.
An entity manager is by default container managed and its associated persistence context is transaction scoped. This means there is no need to either create or close the entity manager, nor is there any need to begin, commit or rollback anything.
After the method that starts a transaction (which happens transparently as well) completes, the transaction scoped persistence context is guaranteed to be flushed (all outstanding updates are written to the DB) and cleaned (the L1 cache is destroyed) as well as any other resources involved with that entity manager.
A standard example:
#Stateless
public class CustomerService {
#PersistenceContext
private EntityManager entityManager;
public void addCustomer(Customer customer) {
entityManager.persist(customer);
}
}
Note that if you really wanted, you could use an application managed entity manager by injecting a factory instead and obtaining the entity manager from it. In that situation you would indeed need to do any closing yourself. If you would also combine this with bean managed transactions and the extended persistence context, you'd be in a situation where even in EJB you'd need to do everything yourself. But this is very rare, and only provided to you as an option. It's not the default.