AspectJ problem - class

Hi I am new to AspectJ and I would like to find out if creating variants of a class using Aspects - I will create another instance of the class as well?

I am guessing that the question is, if I am adding aspects would a new class be created.
The answer is no, as the weaving, either when compiling or at run-time, using AspectJ, will add the changes to the classes that are affected by the aspects, so there is no new class created, it is just that the byte code for the original class and the final class are different.

What do you mean by variants?
If you are asking if AspectJ instantiates copies of your class, the answer is no.
AspectJ uses a design pattern called proxy to intercept calls to your class.

Related

Dont understand the concept of extends in URL.openConnection() in JAVA

Hi I am trying to learn JAVA deeply and so I am digging into the JDK source code in the following lines:
URL url = new URL("http://www.google.com");
URLConnection tmpConn = url.openConnection();
I attached the source code and set the breakpoint at the second line and stepped into the code. I can see the code flow is: URL.openConnection() -> sun.net.www.protocol.http.Handler.openConnection()
I have two questions about this
First In URL.openConnection() the code is:
public URLConnection openConnection() throws java.io.IOException {
return handler.openConnection(this);
}
handler is an object of URLStreamHandler, define as blow
transient URLStreamHandler handler;
But URLStreamHandler is a abstract class and method openConnection() is not implement in it so when handler calls this method, it should go to find a subclass who implement this method, right? But there are a lot classes who implement this methods in sun.net.www.protocol (like http.Hanlder, ftp.Handler ) How should the code know which "openConnection" method it should call? In this example, this handler.openConnection() will go into http.Handler and it is correct. (if I set the url as ftp://www.google.com, it will go into ftp.Handler) I cannot understand the mechanism.
second. I have attached the source code so I can step into the JDK and see the variables but for many classes like sun.net.www.protocol.http.Handler, there are not source code in src.zip. I googled this class and there is source code online I can get but why they did not put it (and many other classes) in the src.zip? Where can I find a comprehensive version of source code?
Thanks!
First the easy part:
... I googled this class and there is source code online I can get but why they did not put it (and many other classes) in the src.zip?
Two reasons:
In the old days when the Java code base was proprietary, this was treated as secret-ish ... and not included in the src.zip. When they relicensed Java 6 under the GPL, they didn't bother to change this. (Don't know why. Ask Oracle.)
Because any code in the sun.* tree is officially "an implementation detail subject to change without notice". If they provided the code directly, it helps customers to ignore that advice. That could lead to more friction / bad press when customer code breaks as a result on an unannounced change to sun.* code.
Where can I find a comprehensive version of source code?
You can find it in the OpenJDK 6 / 7 / 8 repositories and associated download bundles:
http://hg.openjdk.java.net/jdk6/jdk6 - http://download.java.net/openjdk/jdk6/
http://hg.openjdk.java.net/jdk7/jdk7 - http://download.java.net/openjdk/jdk7/
http://hg.openjdk.java.net/jdk8/jdk8
Now for the part about "learning Java deeply".
First, I think you are probably going about this learning in a "suboptimal" fashion. Rather than reading the Java class library, I think you should be reading books on java and design patterns and writing code for yourself.
To the specifics:
But URLStreamHandler is a abstract class and method openConnection() is not implement in it so when handler calls this method, it should go to find a subclass who implement this method, right?
At the point that the handler calls than method, it is calling it on an instance of the subclass. So finding the right method is handled by the JVM ... just like any other polymorphic dispatch.
The tricky part is how you got the instance of the sun.net.www.protocol.* handler class. And that happens something like this:
When a URL object is created, it calls getURLStreamHandler(protocol) to obtain a handler instance.
The code for this method looks to see if the handler instance for the protocol already exists and returns that if it does.
Otherwise, it sees if a protocol handler factory exists, and if it does it uses that to create the handler instance. (The protocol handler factory object can be set by an application.)
Otherwise, searches a configurable list of Java packages to find a class whose FQN is package + "." + protocol + "." + "Handler", loads it, and uses reflection to create an instance. (Configuration is via a System property.)
The reference to handler is stored in the URL's handler field, and the URL construction continues.
So, later on, when you call openConnection() on the URL object, the method uses the Handler instance that is specific to the protocol of the URL to create the connection object.
The purpose of this complicated process is to support URL connections for an open-ended set of protocols, to allow applications to provide handlers for new protocols, and to substitute their own handlers for existing protocols, both statically and dynamically. (And the code is more complicated than I've described above because it has to cope with multiple threads.)
This is making use of a number of design patterns (Caches, Adapters, Factory Objects, and so on) together with Java specific stuff such as the system properties and reflection. But if you haven't read about and understood those design patterns, etcetera, you are unlikely to recognize them, and as a result you are likely to find the code totally bamboozling. Hence my advice above: learn the basics first!!
Take a look at URL.java. openConnection uses the URLStreamHandler that was previously set in the URL object itself.
The constructor calls getURLStreamHandler, which generates a class name dynamically and loads, and the instantiates, the appropriate class with the class loader.
But URLStreamHandler is a abstract class and method openConnection()
is not implement in it so when handler calls this method, it should go
to find a subclass who implement this method, right?
It has to be declared or abstract or implemented in URLStreamHandler. If you then give an instance of a class that extends URLStreamHandler with type URLStreamHandler and call the openConnection() method, it will call the one you have overriden in the instance of the class that extends URLStreamHandler if any, if none it will try to call the one in URLStreamHandler if implemented and else it will probably throw an exception or something.

MVVM Dependency Injection

I'm in the process of teaching myself the MVVM pattern by dividing the pattern into its core facets and learning those facets one by one.
My question is related to dependency injection. What is it, and why/when should I use it? I've looked at Jason Dolinger's excellent MVVM intro video and I see he uses Unity. This might be strange to ask but how would I implement dependency injection WITHOUT using Unity? I basically want to understand the concept of dependency injection and how to use it without having to implement other frameworks/tools (for now).
Thanks.
I think it's good that you want to understand DI without using a framework, the concept is not terribly difficult to wrap your head around.
Let's say you want to use some form of transportation.
interface ITransportation
{
Transport();
}
An initial implementation of a method that uses a form of transportation might look like this:
public void Move()
{
ITransportation car = new Car();
car.Transport();
}
The problem with that method is that it is now dependent on a Car class. We should pass our transportation object in for added flexibility. This is inversion of control and is closely related to DI.
public void Move(ITransportation tr)
{
tr.Transport();
}
As you can see, we don't need to know anything about a specific DI framework. You might also want to check out the ninject DI by hand tutorial.
Just to extend #Andy's answer
Dependency Injection is one of the forms of the Dependency Inversion Principle
To achieve the decoupling of dependencies (as typically found in layered architecture),
DI is commonly used for instantiation scenarios such as basic new() and patterns like Factory method. In addition to being able to inject a new dependency instance every time (e.g. like factory), containers can also be set up to inject named instances, singleton instances, etc - i.e. IoC containers usually also take on the responsibility of managing the lifespans of objects as well.
One potential 'mindset shift' is that dependencies now potentially become publicly visible on concrete classes, since DI typically injects via constructors or public Get / Set properties. This may seem strange if you are used to using OO encapsulation, where dependencies of a class are seen as implementation and should be hidden from the 'outside' i.e. class method signatures.
However, by implementing Interface / Concrete class separation (as you should, not only for decoupling but also for testing / mocking purposes), the injection constructors / property injection methods will not be on the interface, so encapsulation is again in place.
Re : "Doing DI by hand" without Unity etc
What you would need to do is to code your own IoC container, which then is responsible for 'building up' instances of classes - during each 'build up', you would scan the class for dependencies (which are configured in the container, e.g. by config, by attributes, or simply just by convention, e.g. all public settable properties, or any class parameters on a constructor will be assumed to be dependencies). You would then create (if necessary) and inject this 'dependency' instance onto the object (e.g. by using reflection). And then recursively, all dependencies of these dependencies need to be built up etc. You would then also need to provide lifespan management for each of the objects, e.g. Singletons etc.

Is there any way to create a fake from a System.Type object in FakeItEasy?

Is there any way to create a fake from a System.Type object in FakeItEasy? Similar to:
var instance = A.Fake(type);
I try to write a fake container for AutoFac that automatically return fakes for all resolved types. I have looked in the code for FakeItEasy and all methods that support this is behind internal classes but I have found the interface IFakeObjectContainer that looks pretty interesting, but the implementations still need registration of objects that is the thing that I want to come around.
As of FakeItEasy 2.1.0 (but do consider upgrading to the latest release for more features and better bugfixes), you can create a fake from a Type like so:
using FakeItEasy.Sdk;
…
object fake = Create.Fake(type);
If you must use an earlier release, you could use some reflection based approach to create a method info for the A.Fake() method. (since it's about auto mocking this shouldn't be a problem really).
This is best done using a registration handler. You should look into how AutofacContrib.Moq implements its MoqRegistrationHandler. You'll see that it is actually using the generic method MockRepository.Create to make fake instances. Creating a similar handler for FakeItEasy should be quite simple.

GWT: Replace AbstractPlaceHistoryMapper with a custom mapper using deferred binding

Looks like the class that is generated for PlaceHistoryMapper is hard-coded to use AbstractPlaceHistoryMapper as the super class.
So, I am trying to work around this by trying to replace this AbstractPlaceHistoryMapper with a custom mapper of mine using deferred binding . I am using the following rule in my *.gwt.xml:
<replace-with class="com.google.gwt.place.impl.AbstractPlaceHistoryMapper">
<when-type-is class="com.test.sampleapp.CustomPlaceHistoryMapper" />
</replace-with>
But for some reason the replace does not seem to be happening. CustomPlaceHistoryMapper is not getting kicked in and the generated class still uses AbstractPlaceHistoryMapper.
Any thoughts/pointers as to what might be resulting this behavior are much appreciated.
Note: I have also posted this on the GWT group but haven't received an answer so far.
To make the deferred binding work a class must be created with GWT.create(). However, AbstractPlaceHistoryMapper is only used as an extended class. So it will never be created via GWT.create, but always by instantiation the subclass. And therefor deferred binding won't work in this case. If you want a complete different implementation you have to implement a custom PlaceHistoryMapper, and manage the known tokens yourself. This also means you can't use the History annotations either.
As a side note the classnames in your rule should be swapped. But for the end result this doesn't matter, since it won't work in the first place.
It is absolutely possible to have custom history tokens (eg. #mail or #mail/bla instead of only #mail:inbox) using the out-of-the-box Place-related classes that GWT (2.0) provides.
Instead of replacing AbstractPlaceHistoryMapper you could instantiate the default PlaceHistoryMapper passing in it's constructor your implementation of PlaceHistoryMapper<T> or PlaceHistoryMapperWithFactory<T>.
eg.:
final PlaceHistoryHandler placeHistoryHandler = new PlaceHistoryHandler(new CustomHistoryMapper());
You will be able then to map tokens as you wish.
I personally recommend you to use an unique PlaceTokenizer in you mapper custom implementation so that I dont have to have an inner PlaceTokenizer class in each of your Places.
Hope that helps. Feel free to ask any doubts.

Windsor Container: How to specify a public property should not be filled by the container?

When Instantiating a class, Windsor by default treats all public properties of the class as optional dependencies and tries to satisfy them. In my case, this creates a rather complicated circular dependency which causes my application to hang.
How can I explicitly tell Castle Windsor that it should not be trying to satisfy a public property? I assume there must be an attribute to that extent. I can't find it however so please let me know the appropriate namespace/assembly.
If there is any way to do this without attributes (such as Xml Configuration or configuration via code) that would be preferable since the specific library where this is happening has to date not needed a dependency on castle.
You can use the Castle.Core.DoNotWireAttribute attribute to stop a property from being wired up by the IoC container (this is in the Castle.Core assembly, which means your library only needs to take a dependency on the lightweight Castle.Core assembly - if for example you want to use the code without an inversion of control container altogether, or in a different IoC container).
I don't believe there's any way to prevent wiring from occurring in the Xml configuration, but it would be reasonably easy to add support for this - if I had to do this I would probably:
Introduce some kind of attribute on the property declaration in the xml: <myprop wire="false" />
Inherit from PropertiesDependenciesModelInspector, overriding the InspectProperties method to apply some additional logic to identifying which properties should be added as dependencies to the components model (inspecting the model.Configuration for the wire="false" attribute/value pair).
Inherit from DefaultComponentModelBuilder and override the InitializeContributors to include your replacement PropertiesDependenciesModelInspector - or just remove the existing properties contributor and add your own at run time via the AddContributor/RemoveContributor methods.
Replace the ComponentModelBuilder service instance assigned to the kernel of your container.
Another approach which could work for you is to just manually remove the dependencies from the model before any instances of the service are requested ie.
kernel.GetHandler(typeof(MyComponent)).ComponentModel.Dependencies.RemoveAll(d => d.DependencyKey == "PropertyThatShouldNotBeWired");
YMMV with that approach though - especially if you have startable services or other facilities which may be eagerly instantiating your component after it's registered.
I created a facility to help with this:
Castle.Facilities.OptionalPropertyInjection
I do not know which version of Castle you guys were using at that time, but none of the solution mentioned were working. Plus, there is a lot of dead links.
With castle 3.1, here the solution I came up with (thanks to some castle source code digging):
container.Register(Component.For(type)
.LifestyleTransient()
.Properties( propertyInfo => propertyInfo.PropertyType != typeof(MyOtherType)));
The 'Properties' function adds a property filter used by castle when constructing the ComponentModel. In my case, all properties dependency will be satisfied except the property type 'MyOtherType'.
Maybe it will be helpful for someone. In Windsor 4.1 there is PropertiesIgnore method during registration.
Component.For<Role>().LifestyleTransient().PropertiesIgnore((model, propertyInfo) => true)
DoNotWireAttribute
Class: http://svn.castleproject.org:8080/svn/castle/trunk/Core/Castle.Core/Attributes/DoNotWireAttribute.cs
Test: http://svn.castleproject.org:8080/svn/castle/trunk/InversionOfControl/Castle.Windsor.Tests/IgnoreWireTestCase.cs
This can be achieved by the following code:
var container = new WindsorContainer();
// We don't want to inject properties, only ctors
var propInjector = container.Kernel.ComponentModelBuilder
.Contributors
.OfType<PropertiesDependenciesModelInspector>()
.Single();
container.Kernel.ComponentModelBuilder.RemoveContributor(propInjector);
Source Castle Windsor Documentation
Posted this on the google groups forum too here: http://groups.google.com/group/castle-project-devel/browse_thread/thread/43aa513817bd057a