Java API modification - java

I have a very quick question - Is it possible to modify the source code of Java API e.g. Junit, JABX ?
I know it seems a very stupid question, but it has been bugging me for a while.

If you can get your hands on the source, then sure you can modify it. It might not be the best option. It might be better to just create subclasses (if possible) and overwrite implementations, and use your subclasses. Or use composition to proxy the library classes. Depends on what you need to do/fix.
Keep in mind if you modify the source of an external library, and upgrade, you have to modify the source again. You might have to change your extensions/proxies as well if you go that route, but experience has taught me that's typically less complicated.

for open source API such as JUnit: yes

Related

JVM: most simple way to alter code of a dependency library?

Most of the time, I don't like Javascript and would prefer strict and compiled languages like Scala, Java, Haskell...
However, one thing that can be nice with Javascript is to be able to easily change code of external dependencies. For exemple, if you have a bug and you think it's one of your dependency library you can easily hack around and swap a library method by your own override and check if it's better. You can even add methods to Array ou String prototypes and things like that... One could even go to node_modules and alter the library code here temporarily if he wants to.
In the JVM world this seems to me like an heavy process to just get started:
Clone the dependency sources
Hack it
Compile it
Publish it to some local maven/ivy repository
Integrate the fixed version in your project
This is a pain, I just don't want to do that more than once in a year
Today I was trying to fix a bug in my app, and the lib did not provide me enough information. I would have loved to just be able to put a Logger on one line of that lib to have better insight of what was happening but instead I tried to hack with the debugger with no success (the bug was not reproductible on my computer anyway...)
Isn't there any simple alternative for rapidly altering the code of a dependency?
I would be interested in any solution for Scala, Java, Clojure or any other JVM language.
I'm not looking for a production-deployable solution, just a quick solution to use locally and eventually deployable on a test env.
Edit: I'm talking about library internals that are not intended to be modified by the library author. Please assume that the class to change is final, not replaceable by library configuration, and not injectable by any way into the library.
In Clojure you can re-bind vars, also from other namespaces, by using intern. So as long as the code you want to alter is Clojure code, that's a possible way to monkeypatch.
(intern 'user 'inc dec)
(inc 1)
=> 0
This is not something to do lightly though, since it can and will lead to problems with other code not expecting this behavior. It can be handy to use during development to temporarily fix edge cases or bugs in other libraries, but don't use it in published libraries or production code.
Best to simply fork and fix these libraries, and send a pull request to have it fixed in the original library.
When you're writing a library yourself that you expect people need to extend or overload, implement it in Clojure protocols, where these changes can be restricted to the extending/overloading namespaces only.
I disagree that AspectJ is difficult to use, it, or another bytecode manipulation library is your only realistic alternative.
Load-time weaving is a definite way around this issue. Depending on how you're using the class in question you might even be able to use a mocking library to achieve the same results, but something like AspectJ, which is specifically designed for augmentation and manipulation, would likely be the easiest.

Is there a tool to make all classes package protected and final if possible?

Background: I notice that in many projects almost all classes in the internal code are public and not final, even if they don't need to be. However, it seems sensible to me to make this decision not by default, but only make classes public if they are actually meant to be used from other parts of the system. Having package protected classes is an easy mechanism to enforce boundaries between modules, and serves as a documentation on the intended use of a class.
If there was a (preferrably free :-) tool to protect all classes that can be protected without breaking the program, and maybe make everything final that has no subclasses, that would be a good starting point to start a conscious use of protection mechanisms. (Of course you need to tweak things afterwards.) Do you know such tool?
Caveat: I am aware that there are better modularization mechanisms like OSGI and the planned superpackages and so forth. But in many current projects this is not an option, and using the plain old Java mechanisms is something you can easily do. Also, this works only if you have shared code ownership (such that everybody can change things back to public as needed) and if you are developing an endproduct, not a library for use by others. I am also not too sure about the benefits of making things final - this prevents AOP and mocking.
CLARIFICATION: As I said, I am not talking about libraries that are thrown over the fence to someone who can't change it, but about internal code of medium sized projects where everybody is encouraged to change and refactor everything as needed. When I am talking about package protected or final think of it as "protected until someone feels a compelling need to lift those restrictions". If someone feels the need to lift the restrictions set by the tool, he is welcome to do so.
Even if there was such a tool, (there isn't), a good programmer wouldn't use it... access specification is a design issue best understood and settled by the programmer himself. Think about it... you make a program and run the tool and get everything sorted (Assuming the tool is super-intelligent in the first place to actually understand your program).. then you decide to modify it... extend some classes, etc.. and you end up extending final classes and making objects of private classes.. (and these are few of the many problems you'll face)...
Thing is.. when the tool does its job, you would no longer even understand your own program.
Bottomline.. stop looking for tools to solve your design issues.. (its like asking for tools that will automatically debug your program)
You can have a look at ATL from Eclipse. Although ATL is used to create model to model transformations between different kinds of models, there is no restriction that source and target model are not of the same type. You could create a transformation from Java to Java that makes your current classes protected or final. MoDisco is a toolset of Eclipse makes use of that, just if you want to see examples.

How to edit Java Platform Package (Built-in API) source code?

As good as the Java API is, I need to change the code of some classes in the default API packages (for example java.util.Scanner) for a project I am working on.
Ideally, I would extend the classes I am interested and create my own sub-classes, but the classes I want to extend are declared 'final'. How do you suggest I do this? Will I get into trouble with the compiler if I customize the source code of these packages?
If you can, you should rather wrap and delegate, as suggested in another answer. See the Adapter Pattern.
But there are of course ways to do this if you really need it.
A straightforward approach is to simply modify the code in downloaded sources and substitute your own version of a jar in the classpath.
Another option is to use aspect-oriented programming techniques, likely with AspectJ to intercept and modify calls as needed.
It might also be possible to hack together a solution using reflection and home-grown classloaders, but it will be painful to code.
All of these are however quite risky if you don't know what you're doing. Frequently classes are made final for good reason.
If you tell us more specifically what it is you're hoping to change, we might be able to provide assistance in avoiding what you currently think you need.
you really cant extend a final class..
if u really want to add a functionality by extending a class you can do it by modifying class src. from JDK and save it as your own class and use it.
Don't do that. Write your own code which wraps around the original scanner and use that. To update internal packages, there is an endorsed directory property which you can provide at runtime.
Never do it! Never change core classes. If class is final - use composition not inheritance.

Intercepting method of an tomcat application with aop

I have a problem which is hard to explain so lets get started:
Context: I have a application running on a tomcat server Lets call it "admin". The admin have an import/export function. Our own application is an extension to that and we need to gather some information when the "admin apps" use the import/export function.
Problem: The third party jar that contain the class ImportController is located there: ~/someFolder/admin/WEB-INF/lib/admin.jar. The goal is to gather the Old project ID and the new Project ID so that our extension can link our class to the right project. Since i know the method signature i though i could use AOP to do so.
Idea: The idea i came with is to put something like idHiJacker.jar that would contain a single pointcut and advice into the ~/someFolder/admin/WEB-INF/lib/ and enable load-time weaving. That advice would simply put the information into an xml file so our extension would be able to read it when we want to put the link back after a project import.
Also i must say I'm a pure newbie with AOP and web stuff. But i do not wish to import a monster for just doing this small operation with AOP. At the moment im reading on aspectJ and AspectWerkz
Question:
1) Am I in the right direction? Do you see anything that would make this idea not work at all?
2) If this is possible what would be the good practice to do it in a very clean manner?
3) Should i do it with AspectJ? AspectWerkz? Or Something else?
4) Am i doing this for nothing? Is there an easier way to do that operation?
Edit: Also if you have good tutorial to link with answer, it would be awesome
Thanks for your time and answer
Question:
1) Am I in the right direction? Do you see anything that would make this idea not work at all?
I can't see any reason why this will not work. Aspect Oriented Programming and cross-cutting concerns apart, the notion of advice is to execute some before or after some other pointcut and often to influence the behavior of that advised function. You are doing exactly that here.
2) If this is possible what would be the good practice to do it in a very clean manner?
There is some inherent chaos with aspects/advices -- since the control flow is hijacked more then a simple sequential reading of code is needed to understand whats going on.
3) Should i do it with AspectJ? AspectWerkz? Or Something else?
I have never used AspectWerkz but I have very good experience with AspectJ; especially in terms of the support here on stackoverflow and perhaps even more on its mailing list.
4) Am i doing this for nothing? Is there an easier way to do that operation?
Unless you can change the code of import controller or change the clients to make extra calls to do the linking thing this interception based approach seems best IMHO.
I have suggestion for a simpler solution - use a decorator pattern to wrap around the third party ImportController, put your functionality before the third party library is called. You should be able to do this since you seem to have access to the admin application.
This is essentially doing what AOP is doing, but using code. Your approach using load time weaver should also work, but is in my opinion complicated - if you absolutely plan to go this way, do use AspectJ.

Functional depedency analysis

Developers who have used eclipse cannot miss out the Cntrl+Shift+G combo - the easiest way to find all references to a particular member/method/class in your workspace.
Consider a scenario where you are a new guy maintaining a web application written in java. Now, you are about to change a method signature, and you do a Cntl+Shift+G to find all references to the said method (yes, hoping that you are not doing depedency injection / reflection etc). However, a new guy, would want not to screw up any functionality in the application. How would ensure that the functional dependencies are not affected?
I guess..the question is a bit unclear.. lemme rephrase... Say you are changing something functional (an if loop in a business rule or whateva) - this will definetly CHANGE something else in the context of the application.. and at this point you wish there was something (a plugin?) in eclipse, that would tell you - "hey noob..don't change this - it would affect this..." - Now, if you were to create something that does this for eclipse (plugin?) - where would you start? (tagging parts of scr code and introducing a depdency tree? etc?)
Perhaps I failed to understand your question, but I think I might have an answer. Take a look at nWire for Java (or PHP). It is a plugin for code exploration. Focusing on a piece of code, the developer can quickly determine where the method is invoked, where the class is used, etc. This makes it easier to understand what you are about to change.
I am the developer of this plugin. If it is not exactly what you are looking for, let me know, I'll be happy to better understand what you are looking for.
Besides: ALT+SHIFT+C is the way to change a method signature. ALT+SHIFT+G "only" finds references, which is helpful of course.
vickirk mentionend the most important aspect here: Without having tests and a good code coverage you aren't able to apply any changes without risking a failing system afterwards.
The book "Working Effectively with Legacy Code" from Robert C Martin explains it nicely: All code, which is not covered by tests, is legacy code. You could draw the conclusion, that before you apply any functional change you need to ensure a sufficient test coverage.
Tagging parts in the source code seems like a bad idea, since these tags need to be additionally maintained, which usually never really happens in projects. :)
What about JDepend?

Categories