Is it possible to detect which deprecated classes are actively used? - java

I have a relatively complex java project, with many classes that are probably not used.
Static analysis of the code base is relevant for some of the classes, but some are loaded dynamically (network services, persisted data, etc.)
Is there a method to get a list of deprecated classes that were actively used in the jvm, so I can know if those classes are used?
[I know there may be "sleeper classes" that are used only rarely, but that's a risk I can take]

The JVM may have an option to print information about all used classes. For example:
java -verbose:class ...
You still would have to filter out the deprecated ones by some other means.

You can try to compile with -deprecation (or -Xlint:deprecation) to see the uses of deprecated APIs if you have to sourcecode (I guess you have it)

I could think of the following :
Add static initializer to each of your classes in the form
static {
// here you can get creative :
// either do some writing to a file with each class printing its name
// or do System.err outputing the class name, then later fetching the entire output.
}
If you are too lazy to manually add the piece of code you could write simple program to append this initializer to all files ending with .java.
This is simple way of getting a list of all the classes that are being used ( I think).
Best of luck!

There are tools like UCDetector which I've used in the past. But that requires manual assessments which can be painful for large projects. You can do text analysis like below:
Listing active usage deprecated methods
For static code analysis, list down deprecated methods of which source is already available using an IDE.
In Eclipse, goto Window -> Preferences -> Java -> Compiler -> Errors/Warnings -> Deprecated and restricted API : Set level to WARNING and check the items besides.
In Problems view, click the down button near the tab -> Group By -> Java Problem Type
You will be able to see Deprecation usage list grouped together, copy the contents as text, which you can use to further prepare scripts/excel for analysis
Use a simple text editor to find and replace "from the type " and " is deprecated" with tab characters
Copy the contents to a spreadsheet. You will have a list of classes which contain deprecated methods but have active usage.
Listing inactive usage deprecated methods
List down the class and method names by using similar approach above (For method name replace the text "The method " and " from the type " with tab characters).
This list minus the previous list is the inactive methods list.
Listing dynamic deprecated methods
For dynamic code using reflections etc, there is no single bullet approach. You can do filtering of basic stuff using the method names.
List down the method names by using similar approach above (Replace the text "The method " and " from the type " with tab characters).
For the unique set of method names, loop to use a grep script. This type of search can be slow even for small projects. But just in case you 'ld want to invest the time.

Remove them all and try to run your application. Every time you get a ClassNotFoundException for one of them, write it down and add the class back. Rinse and repeat.

Related

Eclipse: Replace multiple, different regexes simultaneously

I'm currently trying to replace an old (java) testing framework with a different, although similar, one. Therefore, as most occurences of old framework code are the same 90% of the time (in the sense of identic variable names, parameter types etc.), replacing them is pretty straightforward and rather repetitive.
Therefore, I wrote myself a few regex matches (which work just fine, they are not the focus of this question).
However, I have a rather large number of different test files, and I already at this point - just having started - have 6 different match/replacement-pairs that I would like to apply.
Now obviously, being a computer scientist, I would love to automate this, instead of going through every file, pressing Ctrl+F, pasting the matching regex, pasting the replacement regex, pressing the replace button, repeating this cycle 5 more time, and then moving to the next file.
So, let's say for the sake of simplicity, that these are my regexes:
//matches the existing framework
OldClass (.*?) = new OldClass("string");
//replacement regex:
NewClass $1 = new NewClass("string");
//example replacement:
OldClass foo = new OldClass("string");
//becomes:
NewClass foo = new NewClass("string");
So, If I want to replace several of these match/replace-pairs in lots of different files - can I use any built-in eclipse function, or is there an extension that provides this functionality?
Note that I'm aware that I could write a simply java program that just skims through all my source code and applies the regexes as desired.
I'd much rather avoid spending that time, though, and especially would also like to get a chance to apply them individually to each file, so I can re-run the tests afterwards and make sure nothing is broken - which will happen, as not all of the old framework code can be replaced automatically, due to too complex & specific cases. Since I'm also removing the old imports, though, this will break any still existing non-replaced code relying on now-no-longer-existing imports.
Eclipse should have a simple file search option with a "Replace.." button at the bottom. You can search as you would normally specifying the file endings that you'd like to search (probably in this case you'd want *.java). The replace button lets you replace each search result with a replacement using regular expressions.
Granted, this will change your source one replace at a time and that is awkward I know, but my recommendation is to perform small steps, minimizing time in which your code is broken. For instance if you move your class to a new location with a new name, just focus on renaming the class first (verifying that the code then works afterwards), and only then focus on changing its package.
Word to the wise, click Preview first!
Alternatively, consider using ctrl+shift+R to rename methods/variables/classes. Assuming the code is under a source folder, it will automatically rename everywhere it is used. Generally it is preferable to using regular expressions. But again, you can't perform multiple changes at the same time. Though this is probably for the best. Just make a backup of the project and organize the changes that need to be made before starting.
Good luck!

A table that contains View objects tags

First of all I must say I'm new to both Android dev and Java.
I'm trying to find a list of the tags that are used for logging in Android studio.
The examples I've been researching include using:
Log.i(tag:"Info","message");
Log.i(tag:"Values","another message");
Log.i(tag:"Seekbar changed", "and another message");
I tried for the past couple of hours to find a document online, that has a table to describe the reserved tags for View objects, any help will be appreciated.
There is no fixed list of "reserved tags" one can use for logging in Android. You decide for yourself which tags you want to use and what additional information about the state of your objects or primitive types you want to display.
The Log class has six different log levels (debug, error, info, verbose, warn and wtf [What a Terrible Failure]) and corresponding (static) methods (Log.d, Log.e, Log.i, Log.v, Log.w and Log.wtf) each of which you call with two string parameters, one string parameter and one Throwable or two string parameters and one Throwable.
The most commonly used is probably the variant with two string parameters, one parameter for a tag (chosen by you) and one parameter for a message (also chosen by you). See this post for information about which level to choose.
During debugging I often use commands like this one:
Log.e(String.valueOf(myIntVariable), String.valueOf(myOtherVariable));
Let me explain the reason for using the Log class like this. I use the error level because it will give you red entries in the LogCat output (inside an IDE, e.g. Android Studio), and the same IDE will also let you filter out all logs below the error level. However, this is for debugging only; make sure to get rid of those log commands before your app enters production.
Instead of using logs in the way I do, you can also use breakpoints in the debug mode. I guess it is mainly a question of taste if you prefer one or the other. Toasts would be third option (with more boilerplate though).
If you use logs a lot in your code, it makes sense to use real tags. Either you define a string called TAG (or something else) in your class, or you put the name of the containing method as the first parameter. This will give you a sense of the order by which your methods are being called. You can also use other tags as well, and it doesn't have to follow a specific convention either (though you should have a system for it to make sense of it).

JavaScript that must be placed outside a function

We have a tool that generates the source code (for C#, Java, IOS, etc.) from a given model. The code is manually edited for any feature that is missing by the code generator. Whenever any changes made to the model and needs to generate the source code out of it, the manual changes that performed on the previous version are lost.
In order to minimize the loss, the user edited code blocks (methods, classes, properties, etc.) are marked with a custom attribute (say CUSTCODE). While generating the source for the new version, if a path for previous version is mentioned (by user), system will compare the two source codes and merge the contents as follows (previous version is considered as the base in this case):
Remove any code blocks that are available in previous version and not available in new version, which are not marked as CUSTCODE.
Replace any code blocks that are available in both the versions, and not marked as CUSTCODE with latest version code.
Add the missing code blocks from the latest code.
For this, we are using Microsoft Roslyn and is working as expected for C# (of course additional checks like usings are performed)
[Note: I can use Java / C# for the merger app. The system is going to invoke any app by passing params. The same is achieved using ASTRewriter for Java]
Now the challenge is for the JS and HTML. Currently We are focusing at JS.
We have checked several AST JavaScript parsers like Rhino, IronJS, astify etc. But I am blocked at some point in using them.
So I want to build a custom merger. Since JavaScript is so dynamic, we are (going to) setting up the guidelines for JS code.
Enclose all the code within a named function, which acts as unique identifier to match and merge.
Add a comment with "CUSTCODE" on top of the method when system need to keep the function intact while merge.
Our intention is to follow the following approach:
Move the anonymous functions found in jQuery into named functions and call them in jQuery
Name any anonymous function like var v = function()...
Wrap all jQueries and standalone pieces of code into named self executable functions while keeping the order intact.
Move all global variables to top of the JS file. (Do not enclose in any function)
The merging process works as follows:
Capture all strings (single quote, double quote), comments (inline, block) and replace with some unique identifiers. (Except the ones tagged with "CUSTCODE"
Capture the function body (based on the count of '{' and '}') and replace with unique identifier. Read the previous line, mark the method if it is "CUSTCODE"
Compare and replace the captured function bodies with latest version content appropriately.
Restore all captures to generate the final output.
I am wondering if anything else I need to consider.

How to find all Java method calls and given parameters in a project programmatically?

I have a multilingual web application that gets all of the translations from a single object, for example lang.getTranslation("Login") and the object is responsible for finding the translation in an xml file in the user's language.
What I'd like to do is a script / custom static analysis that outputs all the missing translations and translations that are no more used in the application. I believe I should start by programmatically finding every call to the getTranslation method and the string parameter, storing the data in a special structure and comparing it to all the translation files.
Is there a library that will allow me to do this easily? I already found Javassist but I can't use it to read the parameter values. I also tried grepping, but I'm not sure if that's a robust solution (in case there will be a call to another class that has a getTranslation method). I know Qt has a similar mechanism for finding translatable strings in the code, but that's a totally different technology..
I'm asking this because I'm quite sure there's a good existing solution for this and I don't want to reinvent the wheel.
Ok, here's how I did it. Not the optimal solution, but works for me. I created a utility program in Java to find all the method calls and compare the parameters to existing translations.
Find all classes in my project's root package using the Reflections library
Find all getTranslation method calls of the correct class in the classes using the Javassist library and create a list of them (contains: package, class, row number)
Read the appropriate .java files in the project directory from the given row until the ';' character
Extract the parameter value and add it to a list
Find the missing translations and output them
Find the redundant translations and output them
It took me a while to do this, but at least I now have a reusable utility to keep the translation files up to date.

Simple way to reorder methods of a Java class in IntelliJ?

Is there a simpler way of reordering methods within a class source file in IntelliJ than cutting and pasting the code manually? Nowadays I often need this while refactoring legacy code, e.g. to move related methods close to each other in the source code.
In Eclipse AFAIK there is a view similar to the Structure view of IntelliJ, where I can drag and drop methods around. However, this does not work in IntelliJ and I couldn't find any hints from its help either.
I am using IntelliJ 9.0.2 to be specific.
You can select a method name and hit: Ctrl+Shift+Up or Ctrl+Shift+Down to move it up and down.
On OS X: Cmd+Shift+Up or Cmd+Shift+Down
Beyond this the Rearranger Plugin lets you move methods around quickly, and even define a standard ordering based on your coding convention.
IntelliJ has a built in system that allows you to specify how to order your methods. You need to go to Settings (Ctrl + Alt +S) -> Editor -> Code Style -> Java -> Arrangement (tab) and scroll down until you find the icons with methods. There you can manipulate the options to sort them by visibility, or alphabetically, or to keep related ones grouped together.
Here is a screenshot of my settings which will order methods automatically by visibility (public, protected, private) and alphabetically (a-z).
The blue highlights show the currently selected rules.
Not a perfect answer yet, due to a bug in IntelliJ.
Though IntelliJ offers this feature implicitly, but it needs to be enabled as well as fixed. The OP's suggested way is technically arranging methods in depth-first order. However, if you use Breadth-first ordering(which works properly), it should reduce the manual work of moving functions by a lot, by arranging all caller and callee methods together.
Issue Link: https://youtrack.jetbrains.com/issue/IDEA-149524. Please do vote for its resolution.
The appropriate action for this is Rearrange Code. This has no key assigned to it, but you can define your own using Preferences->Keymap.
With your cursor on the method definition line (you do not have to and press ctrl+shift+up or ctrl+shift+down, to move up or down respectively.
You can also to ctrl+shift+numberpad - to quickly collapse everything so you can focus on moving around (plain - works on my laptop as well, not sure why) and ctrl+shift+numberpad + to get back to see everything (ctrl-shift-equals works on my laptop as well).
Select a block of text (hit Ctrl-W a few times) and then use Ctrl-Shift-Up and Ctrl-Shift-Down to move it around.
There is an automated way, which you can later tweak
Code -> show reformat file dialog
and tick "rearrange code" box

Categories