Two SSLContext in same JVM - ssl

We are receiving a SSL handshaking exception when another part of the code is calling SSLContext.getInstance(). Can someone please confirm or deny the ability to have multiple concurrent SSLContexts running in the same JVM using the same provider? The method name getInstance implies a singleton.

Yes, you can have multiple SSLContext instances, configured differently if you wish.
getInstance(...) is generally part of the factory pattern, not the singleton pattern, although a number of implementations of the singleton pattern also use the factory pattern to access this singleton.
In addition, SSLContext.getInstance() doesn't exist, only getInstance(String), getInstance(String,String) or getInstance(String,Provider) (and having an argument on the getInstance method hardly makes sense for a singleton).
(Don't confuse this with SSLContext.getDefault(), which will always return the current default instance, although this can also be changed globally with setDefault(SSLContext).)
Just in case you were talking about SSLContext.getDefault() instead, it's worth noting that the default SSLContext will only read and use the javax.net.ssl.* system properties once, the first time it is loaded. This could have consequences if you set these properties somewhere within the code, but not somewhere else (or differently) and call SSLContext.getDefault() in a different order: the first call to SSLContext.getDefault() wins (assuming you're not complicating this with further calls to SSLContext.setDefault(...)).

Related

Instantiation of System.ServiceModel.Description.WsdlContractConversionContext class

For the case of a project requirement, I need to instantiate WsdlContractConversionContext which is not having a constructor for doing so.
Is there any work around to achieve this?
WsdlContractConversionContext is a member of the System.ServiceModel.Description namespace.
Note:
The requirement exactly is that, I am doing an implementation of IWsdlExportExtension.ExportContract and IWsdlImportExtension.ImportContract, and to unit test this implemetation I need the instance of WsdlContractConversionContext.
There are basically two ways to do that: you can either use reflection to call the non-public constructor of the class (making sure you're passing appropriate parameters to it); or you can let WCF create it for you, and use it wherever you need. The WsdlContractConversionContext is passed as one of the parameters to either IWsdlExportExtension.ExportContract or an IWsdlImportExtension.ImportContract, so you'd need to implement one of the two interfaces (exporting is usually easier, since you won't need to fiddle with WSDL-consuming tools), and force the interface to be called (you may need to hit the service metadata endpoint for that).
The post at http://blogs.msdn.com/b/carlosfigueira/archive/2011/10/06/wcf-extensibility-wsdl-export-extension.aspx has an example of an implementation of a WSDL export extension.
Update following edit in the question: many parts of WCF are notoriously hard to be unit tested. If you can't use WCF itself to create the instance, the only alternative you have is to use reflection. To create an instance of the conversion context class you need an instance of a ContractDescription (which you can create for your contract, but isn't easy), and a PortType, which is even harder. I'm afraid that unit testing your implementation of the WSDL export / import extension may not be worth the effort.

Aspects scanning too many classes and method cache fills memory

In our application we have several (actuall many, about 30) web services. Each web service resides in its own WAR file and has its own Spring context that is initialised when application starts.
We also have a number of annotation-driven aspect classes that we apply to web service classes. In the begining the poincut expression looked like this:
#Pointcut("execution(public * my.package.service.business.*BusinessServiceImpl.*(..))")
public void methodsToBeLogged() {
}
And AOP was enabled on services through entry in configuration.
But when the number of web serivces grew, we began to experience OutOfMemoryExceptions on our servers. After doing some profiling and analysis it appeared that memory is taken by the cache that is kept by instances of AspectJExpressionPointcut class.
Each instance's cache was about 5 MBs. And as we had 3 aspects and 30 services it resulted in 90 instances holding 450MBs of data in total.
After examining the contents of the cache we realised that it contains Java reflection Method instances for all classes existing in the WAR even those which are not part of my.package.service.business package. After modifing the point cut expression to have additionally within clause:
#Pointcut("execution(public * my.package.service.business.*BusinessServiceImpl.*(..)) &&
within(my.package.service.business..*)")
public void methodsToBeLogged() {
}
Memory usage was down to normal again. And all AspectJExpressionPointcut instances took less than 1MB all together.
Can someone explain why is that? And why first point cut expression is not enough? Why the cache of AspectJExpressionPointcut is not shared?
The AspectJExpressionPointcut uses a cache (shadowMatchCache) which speeds up the decision of whether AOP should be applied to a certain method call or not, based on the pointcut expression. This cache possibly consumes a lot of memory.
Additionaly, before offering all methods of a specific bean to see if there is a pointcut expression match or not, Spring first checks if a bean class, could possibly match or not, by calling AspectJExpressionPointcut.matches(Class targetClass).
This method delegates to AspectJ's PointcutExpressionImpl.couldPossiblyMatch() method. This will perform a fast check whether a class could 'possibly' match a pointcut expression or will never 'definetely' match.
According to the AspectJ developers using a within pointcut, results in more definite no's. They also recommend to never use a standalone kind of pointcuts (execution, call, get, set), but combine these with within.
The shadowMatchCache can not be shared however, because it contains the result of match or no match per pointcut expression.
But at least you can limit what gets cached. I also think Spring could possibly improve on this by not keeping this whole cache around, once the applicationContext is started. F.e. they could possibly throw away all the no matches, at the expense of redoing some of the matching, when a new bean is dynamically added to the applicationContext after it is already started.
Another possible memory hog inside the AspectJExpressionPointcut class is the pointCutParser. This parser could possibly be shared across all AspectJExpressionPointcuts in the applicationContext. Take a loot at JIRA ticket SPR-7678.

"Fluent interfaces" that maintain order in the invokation chain

Is there an elegant/convinient way (without creating many "empty" classes or at least they should be not annoying) to have fluent interfcaes that maintain order on compilation level.
Fluent interfaces:
http://en.wikipedia.org/wiki/Fluent_interface
with an idea to permit this compilation
var fluentConfig = new ConfigurationFluent().SetColor("blue")
.SetHeight(1)
.SetLength(2)
.SetDepth(3);
and decline this
var fluentConfig = new ConfigurationFluent().SetLength(2)
.SetColor("blue")
.SetHeight(1)
.SetDepth(3);
Each step in the chain needs to return an interface or class that only includes the methods that are valid to use after the current step. In other words, if SetColor must come first, ConfigurationFluent should only have a SetColor method. SetColor would then return an object that only has a SetHeight method, and so forth.
In reality, the return values could all be the same instance of ConfigurationFluent but cast to different interfaces explicitly implemented by that class.
I've got a set of three ways of doing this in C++ using essentially a compile time FSM to validate the actions. You can find the code on github.
The short answer is no, there is no elegant or convenient way to enforce an order of constructing a class that properly impelemnts the "Fluent Interface" as you've linked.
The longer answer starts with playing devil's advocate. If I had dependent properties (i.e. properties that required other properties to be set first), then I could implement them something like this:
method SetLength(int millimeters)
if color is null throw new ValidationException
length = millimeters
return this
end
(NOTE: the above does not map to any real language, it is just psuedocode)
So now I have exceptions to worry about. If I don't obey the rules, the fluent object will throw an exception. Now let's say I have a declaration like yours:
var config = new Fluent().SetLength(2).SetHeight(1).SetDepth(3).SetColor("blue");
When I catch the ValidationException because length depends on the color being set first, how am I as the user supposed to know what the correct order is? Even if I had each SetX method on a different line, the stacktrace will just give me the line where the config variable was declared in most languages. Furthermore, how am I supposed to keep the rules of this object straight in my head compared to other objects? It is a cocophony of conflicting ideals.
Such precedence checks violate the spirit of the "Fluent Interface" approach. That approach was designed for conveniently configure complex objects. You take the convenience out when you attempt to enforce order.
To properly and elegantly implement the fluent interface there are a couple of guidelines that are best observed to make consumers of your class thank you:
Provide meaningful default values: minimizes need to change values, and minimizes chances of creating an invalid object.
Do not perform configuration validation until explicitly asked to do so. That event can be when we use the configuration to create a new fully configured object, or when the consumer explicitly calls a Validate() method.
In any exceptions thrown, make sure the error message is clear and points out any inconsistencies.
maybe the compiler could check that methods are called in the same order as they are defined.
this could be a new feature for compilers.
Or maybe by means of annotations, something like:
class ConfigurationFluent {
#Called-before SetHeight
SetColor(..) {}
#Called-After SetColor
SetHeight(..) {}
#Called-After SetHeight
SetLength(..){ }
#Called-After SetLength
SetDepth(..) {}
}
You can implement a state machine of valid sequence of operations and on each method call the state machine and verify if the sequence of operation is allowed or throw an exception if not.
I will not suggest this approach for Configurations though, it can get very messy and not readable

Create each COM-instance in it's own exe-container

Is there possible to create a COM-instance in it's own, dedicated, host-process?
I guess some background is needed.
We have an end-user client which has it's central logical components inside an singleton-COM object. (Not propper singleton, but it uses global variables internally, so it would fail.) So that there should be only one instance per exe-file. Convenient while making the client.
However, I should now make a "client-simulator" to test the server-side. I therefore which to make 20 instances of the client-component.
If I could make each instance instanciate in its own exe-host, then the singleton-issue would be handled.
Regards
Leif
I have been struggling with this problem for a few days. I finally found a solution that works. My COM object is written using ATL, so my code snippet will be geared toward that, but the technical solution should be clear. It all hinges on how the class objects are registered. The REGCLS_SINGLEUSE flag is the key. I now have separate processes for each object instance.
In the ATL module, override the RegisterClassObjects() function as follows:
HRESULT RegisterClassObjects(DWORD dwClsContext, DWORD dwFlags) throw()
{
return base::RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_SUSPENDED | REGCLS_SINGLEUSE);
}
From MSDN regarding REGCLS_SINGLEUSE:
REGCLS_SINGLEUSE
After an application is connected to a class object with
CoGetClassObject, the class object is removed from public view so that
no other applications can connect to it. This value is commonly used
for single document interface (SDI) applications. Specifying this
value does not affect the responsibility of the object application to
call CoRevokeClassObject; it must always call CoRevokeClassObject when
it is finished with an object class.
My theory is that because the registration was removed from public view, it causes a new process to be created for the subsequent instantiations.
This other question mentioned a description of how to use DLLHost as a surrogate process:
http://support.microsoft.com/kb/198891
I've never tried this myself, and I don't know off-hand if you can specify flags for the factories (which control if surrogates can be reused for multiple objects), but maybe you can tweak that via DCOMCNFG or OLEVIEW.
My COM days are long gone, but as far as I remember, there's no built-in way to do that.
It might be easier to rewrite your code so it supports multiple instances than to go the one-process-per-instance route with COM, but here's what you could do:
Use thread-local storage for your global variables and write another CoClass, where each instance owns its own thread through which accesses to the class with the global variables are marshaled. This would at least allow you to avoid the performance impact of DCOM.
Write your own out-of-process exe server (similar to windows' DllHost.exe) to host your COM instances. This requires IPC (Inter-Process Communication), so you either have to code something yourself that marshals calls to the external process or use DCOM (presuming your COM object implements IDispatch)

Rhinomocks, how to verify that a stub/mock was never called at all?

Using Rhinomocks, how can I verify that a Mock/stub was never called at all? Meaning no methods was called on the mock/stub?
I am aware of the AssertWasNotCalled method, but this method requires that I mention a method name. (Perhaps I have a class with 10 different methods that could be called).
Log.AssertWasNotCalled(x => x.LogAndReportException(null, null), x => x.IgnoreArguments());
You can use a Strict mock, althought this is a feature that may go away in the future:
var mocks = new MockRepository();
var cm = mocks.StrictMock<ICallMonitor>();
cm.Replay();
cm.HangUp(); // this will cause VerifyAllExpectations to throw
cm.VerifyAllExpectations();
In this syntax, a Strick Mock only allows explicitly defined calls.
You can use the StrictMock method to create a strict mock - this will fail if any unexcepted method call is used. According to Ayende's site, this is discouraged, but it sounds like exactly the scenario where it would be useful.
When you are using mocks, you should not assert every single call was made or not. That couples your tests to a particular implementation and makes them fragile and a refactoring nightmare.
If I ever ran into this situation I would rethink why I wanted to assert that a dependency was never used.
Obviously, if the dependency is not used anywhere, just remove it. If it is needed for some operations, but all the operations in the dependency are destructive operations and you want to make sure some operation does not do harm with them, you should assert explicitly that the destructive operations were not called and allow the implementation to do whatever it wants with the non-destructive operations (if there are any). This makes your tests more explicit and less fragile.