Can AspectJ replace "new X" with "new SubclassOfX" in third-party library code? - aop

I am looking at AspectJ to see if perhaps we can use it in our test suite.
We have a rather large third party Java communications library hardwired to use its own classes (which do not implement any interfaces) which in turn mean that we need a physical backend present and correctly configured to be able to run tests.
I am looking at our options for removing this restriction. A possibility would be to create a subclass of the troublesome classes and then ask AspectJ to simply replace "new X" with "new OurSubclassOfX" when loading the third party library, but I am new to AspectJ and from my brief skimming of the documentation this is not a typical use case.
Can AspectJ do this? What would the configuration snippet be?

Yes, this is possible. Let us assume you have a hard-wired class, possibly fetching something from a database, and want to mock it via an aspect:
package de.scrum_master.aop.app;
public class HardWired {
private int id;
private String name;
public HardWired(int id, String name) {
this.id = id;
this.name = name;
}
public void doSomething() {
System.out.println("Fetching values from database");
}
public int getSomething() {
return 11;
}
#Override
public String toString() {
return "HardWired [id=" + id + ", name=" + name + "]";
}
}
Then there is a little driver application using that very class (not an interface):
package de.scrum_master.aop.app;
public class Application {
public static void main(String[] args) {
HardWired hw = new HardWired(999, "My object");
System.out.println(hw);
hw.doSomething();
System.out.println(hw.getSomething());
}
}
The output is as follows:
HardWired [id=999, name=My object]
Fetching values from database
11
Now you define your derived mock class which should replace the original for testing purposes:
package de.scrum_master.aop.mock;
import de.scrum_master.aop.app.HardWired;
public class HardWiredMock extends HardWired {
public HardWiredMock(int id, String name) {
super(id, name);
}
#Override
public void doSomething() {
System.out.println("Mocking database values");
}
#Override
public int getSomething() {
return 22;
}
#Override
public String toString() {
return "Mocked: " + super.toString();
}
}
And finally you define an aspect with a simple pointcut and advice to replace the original value during each constructor call:
package de.scrum_master.aop.aspect;
import de.scrum_master.aop.app.HardWired;
import de.scrum_master.aop.mock.HardWiredMock;
public aspect MockInjector {
HardWired around(int p1, String p2) : call(HardWired.new(int, String)) && args(p1, p2) {
return new HardWiredMock(p1, p2);
}
}
The output changes as desired:
Mocked: HardWired [id=999, name=My object]
Mocking database values
22
You do that once per class and constructor and are fine. In order to generalise the approach you would need joinpoint properties and, depending on how far you want to go, maybe reflection, but this here is pretty straightforward. Enjoy!

Related

Cling: Looking for Opensource code for uPnp ContentDirectory

I'm trying to build a uPnP control point for controlling audio and I am using Java the cling library. To browse the music on the server requires the ContentDirectory service, cling provides the api to access this but doesnt provide any classes to represent the various actions and arguments requiring me to write lots of boilerplate code, I wonder does such a library exist ?
For example Ive create a Browse class for the Browse action of a Content Directory
import org.fourthline.cling.model.meta.Action;
import org.fourthline.cling.model.types.UnsignedIntegerFourBytes;
public class Browse extends AbstractActionAndInvocation
{
//INPUT
public static final String OBJECT_ID = "ObjectID";
public static final String BROWSE_FLAG = "BrowseFlag";
public static final String FILTER = "Filter";
public static final String STARTING_INDEX = "StartingIndex";
public static final String REQUESTED_COUNMT = "RequestedCount";
public void setObjectID(String objectID)
{
actionInvocation.setInput(OBJECT_ID, objectID);
}
public void setBrowseFlag(BrowseFlag browseFlag)
{
actionInvocation.setInput(BROWSE_FLAG, browseFlag.getParameterName());
}
public void setFilter(String filter)
{
actionInvocation.setInput(FILTER, filter);
}
public void setStartingIndex(int startingIndex)
{
actionInvocation.setInput(STARTING_INDEX, new UnsignedIntegerFourBytes(startingIndex));
}
public void setRequestedCount(int requestCount)
{
actionInvocation.setInput(REQUESTED_COUNMT, new UnsignedIntegerFourBytes(requestCount));
}
public Browse(Action action)
{
super(action);
}
}
Since ContentDirectory only has a predefined list of Actions it seems weird that these don't already exist somewhere ?
Within the cling-support module there are useful classes such as callback classes for the main services
e.g
org.fourthline.cling.support.contentdirectory.callback.Browse.java;
However I found them to be of limited usefulness and serve more as an example implementation rather than one that can be used as is.

Intellij reports code duplication while actually it's not

Here's the code. The code in method test and test2 are different because the parameter passed to Test constructor are different. Actually, if I change any parameter to null, intellij stops reporting the duplication. Is there any way to fix this?
---- Updated --------
I pass 2 functions doing totally different things but intellij still reports duplication
public class TestMain {
public void test(int a)
{
System.out.println("haha");
System.out.println("hahaa");
TestMain testMain = new TestMain();
new Test(testMain::test3);
System.out.println("hahaaa");
}
public void test2(int a)
{
System.out.println("haha");
System.out.println("hahaa");
TestMain testMain = new TestMain();
new Test(testMain::still_dup);
System.out.println("hahaaa");
}
public void test3(int a) {
System.out.println("abc");
}
public void still_dup(int a) {
String b = "edf";
b.toLowerCase();
}
public class Test {
Test(handler h) {
}
}
public interface handler<M> {
void entitySelector(int a);
}
public static void main(String[] args) {
TestMain test = new TestMain();
test.test(1);
System.out.println("-------");
test.test2(2);
}
}
I think the best way to fix this is to replace test and test2 by a single method. You don't have to distinguish what to pass the constructor because it's the current method. This might be the reason why code duplication is reported. The methods can be replaced by a single one without problems.

Expectations are not recorded for injectable instances

Here is my code and I am doing code coverage testing
public class RegisterTest {
#Tested Register register;
#Test
public void testGetStudentName(#Injectable final Student student) {
new NonStrictExpectations(){
{
student.getRollNo();
result="ab1";
}
};
assertEquals(register.getStudentNo(), "ab1");
}
}
I got assertion error for the above testcase because the injectable instance doesnt work here..I dont know y?
Here is my testclass...
Register.class
public class Register {
Student student=new Student();
public String getStudentNo(){
return student.getRollNo();
}
}
Here is my dependency class
Student.class
public class Student {
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
How can I resolve that assertion error??
The #Injectable mock used in the test does work. However, it is never injected into the tested object, which instead creates its own Student instance. So, in situations like this you use #Mocked, not #Injectable.
I should point out two other things, though:
Please take notice of the API documentation. The JMockit jar files (even the Maven ones) contain source code precisely to facilitate access to API documentation from any Java IDE.
"Value classes" like Student (which merely contain getters/setters) are not good candidates for mocking. In general, they should not be mocked. Instead, real instances should be used.

In OOP reading from text file should be a Independent class method?

I have a class that only have main which read in some txt and do the algorithms.
my class is look like:
class doThejob{
public static void main(String args[]){
//*****start part A******
//do the reading from text file, and tokenize it
// process into the form I need,
//about 10-30 lines of codes
//******End of part A*****
//then run the algorithms
algorithm alg=new aglorithm();
Object output = alg.x(input);
//****Part B**** output to txt, about 10~40 lines
}
}
class algorithm{
private void a(Object x){
//do something
return (Object)result;
}
}
Can anyone tell me should I extract those part A and part B to a new class ,and then setup them as a public method .like below
class Io{
public Object readFromTxt(String path){
}
public void outputToTxt(String path){
}
}
And if I setup them , and then use it like below, is that more OOP?
class doThejob{
public static void main(String args[]){
Io dataProcess= new Io();
Object input = dataProcess.readFromTxt(args[0]);
algorithm alg=new aglorithm();
Object output =alg.x(input);
dataProcess.readFromTxt(args[1],output);
}
}
class algorithm{
private Object a(Object x){
//do something
}
}
Do it the way you fill is more readable.
Separating this in another class is according to the Single Responsability Principle. It will help making the code more readable and easy to change later on.
If you want to expand more on this, you could create an interface (eg.: IIO) for input and output. This way you can implement this interface in the IO class, renaming it to FileIO. Anytime you want to create another form of IO, like database access, you just have to create a DatabaseIO class that implements this interface and change the instance in the main method for this new type:
public interface IIO
{
string Read();
void Write(string text);
}
public class FileIO : IIO
{
string path;
public FileIO(string filePath)
{
path = filePath;
}
public string Read()
{
// read from file and return contents
}
public void Write(string text)
{
// write to file
}
}
public class SqlServerIO : IIO
{
SqlConnection conn;
public SqlServerIO(string connectionStringName)
{
// create the connection
}
public string Read()
{
// read from database
}
public void Write(string text)
{
// write to database
}
}
Extracting interfaces makes the code more maintenable by alowing to switch implementations anytime without messing with working code. It also facilitates unit testing.

Design pattern to save/load an object in various format

I have an object: X, that can be saved or loaded in various formats: TXT, PDF, HTML, etc..
What is the best way to manage this situation? Add a pair of method to X for each format, create a new Class for each format, or exists (as I trust) a better solution?
I'd choose the strategy pattern. For example:
interface XStartegy {
X load();
void save(X x);
}
class TxtStrategy implements XStartegy {
//...implementation...
}
class PdfStrategy implements XStartegy {
//...implementation...
}
class HtmlStrategy implements XStartegy {
//...implementation...
}
class XContext {
private XStartegy strategy;
public XContext(XStartegy strategy) {
this.strategy = strategy;
}
public X load() {
return strategy.load();
}
public void save(X x) {
strategy.save(x);
}
}
I agree with #DarthVader , though in Java you'd better write
public class XDocument implements IDocument { ...
You could also use an abstract class, if much behavior is common to the documents, and in the common methods of base class call an abstract save(), which is only implemented in the subclasses.
I would go with Factory pattern. It looks like you can use inheritance/polymorphism with generics. You can even do dependency injection if you go with the similar design as follows.
public interface IDocument
{
void Save();
}
public class Document : IDocument
{
}
public class PdfDocument: IDocument
{
public void Save(){//...}
}
public class TxtDocument: IDocument
{
public void Save(){//...}
}
public class HtmlDocument : IDocument
{
public void Save(){//...}
}
then in another class you can do this:
public void SaveDocument(T document) where T : IDocument
{
document.save();
}
It depends on your objects, but it is possible, that visitor pattern (http://en.wikipedia.org/wiki/Visitor_pattern) can be used here.
There are different visitors (PDFVisitor, HHTMLVisitor etc) that knows how to serialize parts of your objects that they visit.
I would instead suggest the Strategy pattern. You're always saving and restoring, the only difference is how you do it (your strategy). So you have save() and restore() methods that defer to various FormatStrategy objects you can plug and play with at run time.