Modify Java sourcecode programmatically with Java or Groovy - java

To automate certain manual tasks in an legacy project, I need to modify existing java files from within java or groovy code.
I donĀ“t want to use RegEx, because it would be neither quick nor clean in my opinion.
I found javassist and srcgen4javassist. The first one lets me modify my sources as I wish, but only writes bytecode, loosing all comments and annotations. And with the second one I didnt manage to read an existing Class not created with srcgen4javassist itself.
Is there an elegant solution, or do i need to bite the bullet and use Regex?

you could really parse the code using something like eclipse's ASTParser at which point you coudl locate your replacement targets xpath-style, but its a lot of work.
you could also consider marking replacement areas with annotation and writing an annotation processor to generate/alter sources at runtime, but (at least in my opinion) the API is cumbersome.
you can combine regexp with some marker in the source code, something like
//START REPLACEMENT-TARGET
...code to be edited/replaced
//END REPLACEMENT TARGET
which would make your regexp targeting a lot safer.

Related

Finding usages of Java Reflection in a codebase

I'd like to avoid using Reflection where possible. I have a legacy codebase to refactor that has at least one getMethod(), and now I'm afraid to delete functions that seem to be dead.
How can I easily find places in the code where I can work backwards from? Is there a static analyser that can collect Reflection API usage?
Searching for every variant of getClass() and getMethod() seems tedious.
I don't know of any tools on top of my head but it wouldn't be to hard to write script which traverses project structure, going through all directories(packages) and checks in each file if it contains import of java.lang.reflect or calls to getMethod()/ getClass().
There is FileVisitor interface in java which can help you do this.
This answer might also help you as an alternative to FileVisitor
. There is implementation of breadth first search traversal of directories, so you would have to add on top of it:
Read all files from directory
For each file check if it contains reflection keywords as mentioned above
Generate report for each file found
Keep in mind that reflection might be there for problems which are otherwise not possible to solve. Think of frameworks which must work with any supplied classes, processing of runtime annotations and so on.
Hence i would suggest you to be sure that the problem solved by reflection can be and is worth refactoring.

Manipulating Java classes with Java

I would like to manipulate Java classes (with java extension not .class) so that I could :
Delete all methods of a class (keeping the constructor)
Add unimplemented methods
Remove unused imports
...
Is there an API that could accomplish this ?
What I've done so far is trying to manipulate the .java files like text files (with regex,FileUtils, etc.).
Regards.
I
You could look at using the AST (Abstract Syntax Tree) tools from the Eclipse JDT project.
There is a tutorial to get you started at Vogella: Eclipse JDT - Abstract Syntax Tree (AST) and the Java Model - Tutorial
If you only want to temporarily modify the classes (i.e. within the scope of the jvm) then you could do this with reflection:
What is reflection and why is it useful?
If you're taking about permanently altering/creating source code then this is maybe best done using an IDE. Most IDE will tell you about unimplemented methods and provide auto completion to create them. They will also format the source code, remove unused imports etc.
You can use a regular expression, the question then is then what regular expression (And what other options are there!)
Regular expressions maybe aren't ideally suited to this, and for example, when it comes to another task they're not ideally suited to, such as parsing XML, people say don't do it, use an XML parser, but in this case, if you find that there is an absence of a tool built for parsing java source code, then regular expressions may be the best option.
Yes, you can use java reflection api. Please check here
Later edit: To update the class structure you can use javassist. Here you have an example.

Remove all annotations in Java source code and get new source code

I am looking for ways to remove all the annotations from existing Java Source Code. I am looking for an ant task or any other approach. I have seen some solutions that do this at the class level, but I am looking to do this at the source code to source code level.
I have done this through Java Parser code available in Lombok.
Look at these methods which has the logic
lombok.javac.handlers.JavacHandlerUtil#deleteAnnotationIfNecessary
lombok.javac.handlers.JavacHandlerUtil#deleteImportFromCompilationUnit
I ended up using JEdit which has brilliant regular expression support.
I wanted to replace specific annotations (I wanted to keep stuff like #Override). You can easily do that for all buffers or a directory tree.
Just write some simple expressions for the annotations you want to remove. For example
^\s*#NamedQueries\(\n\{[^\}]+\}\)\n

Is there a way to link JDK annotations to requirements?

Hi guys: Is there an open source way to associate java #annotations to functional requirements, or for example, TRAC tickets, etc? I want to do something like this:
I'm thinking along the lines of an eclipse plugin which somehow links up with another FOSS project tracking tool, wiki, or maybe even a CSV file.
A somewhat silly but exemplary illustration of what I desire is below:
#Requirement WalkDogTwiceADay
public void walkTheDog()
{
}
#Requirement WalkDogTwiceADay
public void dogWalkerThread()
{
walkTheDog(); //in the morning.
Thread.sleep(36000000);
walkTheDog(); //at night
}
Annotations are metadata, they simply add information to your code for other tools to use or to be inspected at runtime via reflection.
One thing you can do is write an annotation processor that will generate the necessary artefacts. Those could be configuration files, scripts, code...
Another thing you can do is write some tool that knows how to interpret your annotations and uses reflection to find them and take the appropriate actions. For this you'd need to make sure that the annotation type is set to have runtime retention, as opposed to only source or class.
Perhaps some of the stuff found in the answers to this question might prove of use. If that's the case, go ahead and use it. But writing custom annotation processors or code for handling them is not all that terribly hard. The difficult part is getting to know the Java model API that's used by annotation processors, which is like reflection but at compile time (before you have fully-formed classes).
in a previous life, we did something similar with #requirement ##### annotations, and then had a custom javadoc task that turned the requirement annotations into hyperlinks in the javadocs.
I was going to write an addin for eclipse that turned them into links in the code as well, but never got that far.

(2009) - Tool to deobfuscate Java codes

Is there a tool to deobfuscate java obfuscated codes?
The codes is extracted from a compiled class but they are obfuscated and non-readable.
First step would be to learn with which tool it was obfuscated. Maybe there's already a "deobfuscator" around for the particular obfuscator.
On the other hand, you can also just run an IDE and use its refactoring powers. Rename the class, method and variable names to something sensitive. Use your human logical thinking powers to figure what the code actually represents and name them sensitively. And the picture would slowly but surely grow.
Good luck.
Did you try to make the code less obscure with Java Deobfuscator (aka JDO), a kind of smart decompiler?
Currently JDO does the following:
renames obfuscated methods, variables, constants and class names
to be unique and more indicative of
their type
propogates changes throughout the entire source tree (beta)
has an easy to use GUI
allow you to specify the name for a field, method and class (new feature!)
Currently JDO does not do the
following (but it might one day)
modify method bytecode in any way
Not to gravedig but I wrote a tool that works on most commercial obfuscators
https://github.com/Contra/JMD
I used Java Deobfuscator (aka JDO) but it has a few bugs. It can't work with case sensitive file names.
So I've changed the source and uploaded a patch for that in sourceforge.
The patch, Download
Most likely only human mindpower to make sense of it. Get the best decompiler available and ponder on its output.
Maybe it will work on Unix/Linux/MacOS?
If so, you could move one step of your process to a VM, in where you unpack the code, before you rename the too long names. How long is the file name limit on Windows?

Categories

Resources