Verify whether a method parameter is used in the method body - java

I have an interface which looks like the following
interface Evaluator {
boolean requiresP2();
EvalResult evaluate(Param1 p1, Param2 p2, Param3 p3);
// some more methods
}
This interface is implemented by several classes. The parameter p2 of the evaluate method is used by some and not used by others. The method requiresP2 basically returns a boolean telling whether the evaluate method uses p2 or not.
Now, this questions may appear a little weird out of context but believe me, it makes sense in our use case. Plus, it would require a lot of time to refactor all the code to eliminate the need for the requiresP2 method so I would appreciate if we discuss solutions other than a top-to-bottom refactoring of the codebase.
The problem is that the return value of method requiresP2 is based on how the evaluate method is implemented. Therefore everyone must ensure that they update the requiresP2 method when they change the evaluate method.
I am looking for ways so that this can be enforced by the compiler/unit-tests/linters rather than leaving it to the developer's memory.
EDIT: I am still exploring the applicability of mocking frameworks to this problem.
I thought that I could reflection in unit tests to inspect evaluate's body in the unit test to check if it refers to p2 or not and then making sure it matches with the value returned by requiresP2 method but it seems that it is not possible to inspect method body using reflection.
I am looking for suggestions on how to do this. Any input is appreciated.

There is another option you did not mention: a Static Code Analysis tool.
You can use the SonarQube + SonarLint combination in order to get your desired enforcement:
Use the SonarQube server in order to create a new static code analysis rule, which will be based on the interface you are using and your unique use case.
Then install SonarLint on your IDE/IDEs (Eclipse and IntelliJ are both supported), and connect it to the SonarQube server.
This way the static code analysis scan will detect improper usage of your interface and indicate this with a visual marking in the IDE, on the relevant code lines (which is actually linting your code).

You can use ASM to check whether the parameter is used.
To add it to your project using e.g. Apache Ivy, you would add this to ivy.xml:
<dependency org="org.ow2.asm" name="asm" rev="6.1.1" />
Or do the equivalent for Maven, Gradle, etc. Then you can check on the parameter by:
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
// . . .
public static boolean usesP2(Evaluator evaluator) {
AtomicBoolean usesP2 = new AtomicBoolean(false);
String internalName = evaluator.getClass().getName().replace('.', '/');
String classFileResource = "/" + internalName + ".class";
ClassVisitor visitor = new ClassVisitor(Opcodes.ASM6) {
#Override
public MethodVisitor visitMethod(int access, String name,
String desc, String signature, String[] exceptions) {
if ("evaluate".equals(name)) {
return new MethodVisitor(Opcodes.ASM6) {
#Override
public void visitVarInsn(final int insn, final int slot) {
if (slot == 2) usesP2.set(true);
}
};
}
return super.visitMethod(access, name, desc, signature, exceptions);
}
};
try (InputStream is = Evaluator.class.getResourceAsStream(classFileResource)) {
ClassReader reader = new ClassReader(is);
reader.accept(visitor, 0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return usesP2.get();
}
public static void assertCorrectlyDocumentsP2(Evaluator evaluator) {
boolean usesP2 = usesP2(evaluator);
if (usesP2 && !evaluator.requiresP2()) {
throw new AssertionError(evaluator.getClass().getName() +
" uses P2 without documenting it");
}
if (!usesP2 && evaluator.requiresP2()) {
throw new AssertionError(evaluator.getClass().getName() +
" says it uses P2 but does not");
}
}
Unit tests:
#Test
public void testFalsePositive() {
assertCorrectlyDocumentsP2(new FalsePositive());
}
#Test
public static void testFalseNegative() {
assertCorrectlyDocumentsP2(new FalseNegative());
}
(This supposes there are two bad Evaluators, FalsePositive and FalseNegative, one of which documents that it uses P2 but doesn't, and the other which doesn't document that it uses P2 even though it does, respectively.)
Note: In usesP2 we check for a variable instruction (an instruction which accesses a local variable) in slot 2 of the stack frame. The slots are numbered from 0, and the first one is this. P2 is in slots 2 only because Evaluator::evaluate is an instance method. If it were a static method, we would have to check if slot 1 were used in order to detect if parameter P2 were used. Caveat lector.

Related

Function with same name and parameter class name (but different parameter classes)

I ran into a very strange problem that I don't know if I'm even allowed to do.
Basically I have two functions witch should have the same name but get different parameter objects which have the same name.
This is because I want to write a plugin for the game Minecraft and this should be compatible with BungeeCord and Bukkit servers.
public static void sendMessage(org.bukkit.command.CommandSender p, String k, Object...i){
//fancy stuff
}
public static void sendMessage(net.md_5.bungee.api.CommandSender p, String k, Object...i){
//fancy stuff
}
If the plugin is loaded by a Bukkit server the plugin it doesn't know anything about net.md_5.bungee.api.CommandSender since this is a class of the BungeeCord server core and the same is for org.bukkit.command.CommandSender where it is used by Bukkit but not by BungeeCore.
I have no problem compiling the code with IntellIJ even dough I'm a bit sceptic because if decompiled it looks like this:
import org.bukkit.command.CommandSender;
public static void sendMessage(CommandSender p, String k, Object...i){
//fancy stuff
}
public static void sendMessage(net.md_5.bungee.api.CommandSender p, String k, Object...i){
//fancy stuff
}
My first question is: Can I even do this, or will this give exceptions since not all Classes are loaded, even dough it will never get accessed?
Now if the first question can be answered by Sure you can then why is there a compilation problem by compiling eigther a Bukkit or a BungeeCord plugin using this sendMessage( function?
Bukkit:
BungeeCord:
Because if this doesn't work I know for sure that you can at least work with Classes that aren't loaded if you put them into your codeblock since this code works just fine and isn't even throwing an exception when not loaded by a server that is using org.bukkit.craftbukkit.v1_13_R2.entity.CraftPlayer aldough it is in the imports:
import org.bukkit.entity.Player;
import org.bukkit.craftbukkit.v1_13_R2.entity.CraftPlayer;
public static int getPing(Player p) {
String version = getVersion(instance.getServer());
if (version.startsWith("v1_8")) {
return ((org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer)p).getHandle().playerConnection.player.ping;
} else if (version.startsWith("v1_9")) {
return ((org.bukkit.craftbukkit.v1_9_R2.entity.CraftPlayer)p).getHandle().playerConnection.player.ping;
} else if (version.startsWith("v1_10")) {
return ((org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer)p).getHandle().playerConnection.player.ping;
} else if (version.startsWith("v1_11")) {
return ((org.bukkit.craftbukkit.v1_11_R1.entity.CraftPlayer)p).getHandle().playerConnection.player.ping;
} else if (version.startsWith("v1_12")) {
return ((org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer)p).getHandle().playerConnection.player.ping;
} else {
return ((CraftPlayer)p).getHandle().playerConnection.player.ping;
}
}
So is this really a thing I simply cannot do or is this a problem of the compiler of IntellIJ and if so how can I fix it?
Well my attempt to your idea would be to call methods in sub classes. It might be an issue that the non found class is a parameter. When the class is accessed (just my speculations) the parameters are tried to load to determine which method to use.
So something like the following would be the output.
In the class you access have:
public static void sendMessage(Object player, String k, Object...i){
if(isBukkit())
MyBukkitUtils.sendMessage(player, k, i);
else
MyBungeeUtils.sendMessage(player, k, i);
}
MyBukkitUtils:
public static void sendMessage(Object player, String k, Object...i){
if(!(player instanceOf CommandSender))
return;
CommandSender p = (CommandSender) player;
//fancy stuff
}
Same for MyBungeeUtils just with the BunggeeCommandSender.
I don't know your code, but if you have to have everything seperated you can just code two plugins (one for spigot, one for bungee) and use a include a library in both were the common code is placed.

Avoiding sharing Java meta classes across different Groovy scripts

My situation
I call multiple Groovy scripts from Java, they both contain long-lived Groovy objects.
I would like my Groovy scripts to make some changes to a Java meta-class for a Java class (that have about 100 instances). However, the scripts should be able to make different changes, and changes in one of the scripts should not be reflected in the other scripts.
The problem: The meta-class for the Java class is shared across all the scripts.
This question is similar to How do I undo meta class changes after executing GroovyShell? but in this case I want two scripts to execute simultaneously, so it is not possible to reset after script execution.
Example Code
SameTest.java
public interface SameTest {
void print();
void addMyMeta(String name);
void addJavaMeta(String name);
void callMyMeta(String name);
void callJavaMeta(String name);
}
SameSame.java
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
public class SameSame {
public SameTest launchNew() {
try {
GroovyScriptEngine scriptEngine = new GroovyScriptEngine(new String[]{""});
Binding binding = new Binding();
binding.setVariable("objJava", this);
SameTest script = (SameTest) scriptEngine.run("test.groovy", binding);
return script;
} catch (Exception | AssertionError e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
SameSame obj = new SameSame();
SameTest a = obj.launchNew();
SameTest b = obj.launchNew();
a.addMyMeta("a");
a.callMyMeta("a");
try {
b.callMyMeta("a");
throw new AssertionError("Should never happen");
} catch (Exception ex) {
System.out.println("Exception caught: " + ex);
}
a.addJavaMeta("q");
b.callJavaMeta("q");
a.print();
b.print();
}
}
test.groovy
ExpandoMetaClass.enableGlobally()
class Test implements SameTest {
SameSame objJava
void print() {
println 'My meta class is ' + Test.metaClass
println 'Java meta is ' + SameSame.metaClass
}
void addMyMeta(String name) {
println "Adding to Groovy: $this $name"
this.metaClass."$name" << {
"$name works!"
}
}
void addJavaMeta(String name) {
println "Adding to Java: $this $name"
objJava.metaClass."$name" << {
"$name works!"
}
}
void callMyMeta(String name) {
println "Calling Groovy: $this $name..."
"$name"()
println "Calling Groovy: $this $name...DONE!"
}
void callJavaMeta(String name) {
println "Calling Java: $this $name..."
objJava."$name"()
println "Calling Java: $this $name...DONE!"
}
}
new Test(objJava: objJava)
Output
Adding to Groovy: Test#7ee955a8 a
Calling Groovy: Test#7ee955a8 a...
Calling Groovy: Test#7ee955a8 a...DONE!
Calling Groovy: Test#4a22f9e2 a...
Exception caught: groovy.lang.MissingMethodException: No signature of method: Test.a() is applicable for argument types: () values: []
Possible solutions: any(), any(groovy.lang.Closure), is(java.lang.Object), wait(), wait(long), each(groovy.lang.Closure)
Adding to Java: Test#7ee955a8 q
Calling Java: Test#4a22f9e2 q...
Calling Java: Test#4a22f9e2 q...DONE!
My meta class is groovy.lang.ExpandoMetaClass#2145b572[class Test]
Java meta is groovy.lang.ExpandoMetaClass#39529185[class SameSame]
My meta class is groovy.lang.ExpandoMetaClass#72f926e6[class Test]
Java meta is groovy.lang.ExpandoMetaClass#39529185[class SameSame]
Desired result
The two lines showing information about the Java meta should be different.
This should crash:
a.addJavaMeta("q");
b.callJavaMeta("q");
The question
Is it possible somehow to use different MetaClassRegistry's in the different GroovyScriptEngine instances?
Or is there any other way to make the desired result as shown above happen?
The feature you are looking for is one I had planed for Groovy 3. But since I will no longer be able to work full time on Groovy and since nobody else dares a big change to the MOP this is no option at the moment.
So is it possible to use different MetaClassRegistry's in the different GroovyScriptEngine instances?
No, since you cannot use different MetaClassRegistry's. The implementation is somewhat abstracted, but the usage of MetaClassRegistryImpl is hardcoded and allows for only one global version.
Or is there any other way to make the desired result as shown above happen?
That depends on your requirements.
If you could let the scripts not share the Java classes (load them using differing class loaders), then you don't have a problem with shared meta classes to begin with (for those). If you want more the idea bayou.io had might be best.
You could provide your own meta class creation handle (see setMetaClassCreationHandle in MetaClassRegistry). Then you would have to of course capture a call like ExpandoMetaClass.enableGlobally(). You could use ExpandoMetaClass with a custom invoker (set someClass.metaClass.invokeMethod = ...) or of course directly extend the class. You would then somehow need a way to recognize that you are coming from one script or the other (there is something called origin or caller in the bigger invokemethod signature, but the information is not always reliable. Same thing for get/setProperty). As for how to reliably and efficiently transport that information... well.. that's something I have no answer for. You have to experiment if what ExpandoMetaClass provides is good enough for you. Maybe you could use a ThreadLocal to store the information... though then you would have to write a transform, which will rewrite all method and property calls and most probably cause a performance disaster.

How to print the whole String pool?

I wanted to print the whole string pool which contains literals and String objects added using intern() just before garbage collection.
Is there a method implicit to JDK for such operation? How can we inspect the string pool?
EDIT: The comment suggests that there may be a misunderstanding regarding what this "hack" does. It prints the strings that have been interned by (directly or indirectly) calling intern(), as described in the question. It will not print the "whole string pool", as the string pool only resides in the JVM, is filled with symbols and strings that appear during classloading and initialization, and not accessible from Java side.
NeplatnyUdaj mentioned in a comment that it might be possible to define a new java.lang.String class and sneak this into the JVM at startup. I was curious, and tried it out. And what should I say: It works!
1. Create a new project that contains the package java.lang
2. Insert a class like this into this package
package java.lang;
import java.util.LinkedHashSet;
import java.util.Set;
public class StringPool {
private static Set<String> pool = null;
public static synchronized void store(String string)
{
try
{
if (pool == null)
{
pool = new LinkedHashSet<String>();
}
pool.add(string);
}
catch (Exception e)
{
// Ignore
}
}
public static synchronized Set<String> getPool()
{
return new LinkedHashSet<String>(pool);
}
}
3. Copy & Paste the original java.lang.String class into this package. Surprisingly, this works without many problems. It will complain about a single function, namely a call to
h = sun.misc.Hashing.murmur3_32(HASHING_SEED, value, 0, value.length);
that can safely be replaced with
h = 0;
4. Change the String#intern() method of the new String class. Originally, this is a native method. It can be replaced with something like
public String intern()
{
StringPool.store(this);
return this;
}
5. Create a .JAR file from this project, and store it, for example, as newString.jar
6. Create another project with a test class that generates/contains/uses some strings. (that should be easy) and compile this class, which may be named NewStringTest
7. Launch the test program with the modified string class:
java -Xbootclasspath:newString.jar;C:\jre\lib\rt.jar NewStringTest
The StringPool#getPool() method can then be used to obtain the pool containing the interned strings.
I just tested this with the following class, which manually creates some strings, and some Swing components (which can be expected to contain some strings):
import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
public class NewStringTest
{
public static void main(String[] args)
{
generateSomeStrings();
System.out.println(StringPool.getPool());
}
private static void generateSomeStrings()
{
String s = "This is some test string";
for (int i=0; i<10; i++)
{
String t = s + i;
t.intern();
}
try
{
SwingUtilities.invokeAndWait(new Runnable()
{
#Override
public void run() {
JFrame frame = new JFrame();
JTable table = new JTable();
}
});
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
And the output is
[hashSeed, value, buf, J, D, Z, seed, segmentShift, segmentMask,
segments, state, head, tail, waitStatus, next, Ljava/lang/String;,
I, [C, [J, Ljava/util/Hashtable;, Ljava/security/PermissionCollection;,
Ljava/util/Vector;, Ljava/lang/Class;, main, This is some test string0,
This is some test string1, This is some test string2,
This is some test string3, This is some test string4,
This is some test string5, This is some test string6,
This is some test string7, This is some test string8,
This is some test string9, INSTANCE, es, , ES, sv, SE,
values, Ljava/lang/Object;, [Ljava/awt/Component;,
Ljava/awt/LayoutManager;, Ljava/awt/LightweightDispatcher;,
Ljava/awt/Dimension;, createUI, invoke, VK_F10,
VK_CONTEXT_MENU, VK_SPACE, VK_LEFT, VK_KP_LEFT,
VK_RIGHT, VK_KP_RIGHT, VK_ESCAPE, VK_C, VK_V, VK_X,
VK_COPY, VK_PASTE, VK_CUT, VK_INSERT, VK_DELETE,
VK_DOWN, VK_KP_DOWN, VK_UP, VK_KP_UP, VK_HOME, VK_END,
VK_PAGE_UP, VK_PAGE_DOWN, VK_TAB, VK_ENTER, VK_A,
VK_SLASH, VK_BACK_SLASH, VK_F2, VK_F8]
http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#finalize%28%29 , So the GC calls finalize method before clean-up any of the objects.
So the finalize method in String is also getting called. But sadly String is a final class and you cannot override it. (Why is String class declared final in Java?)
But If you really want to get this thing to be worked, then you need to create your own string object named something else, but inner behaviour will keep all the strings functions.
And for a guaranteed GC try this : http://code.google.com/p/jlibs/wiki/GarbageCollection

How to get the Groovy generated java source code

We have some legacy code with Groovy, and we want to remove Groovy from the application, so, we need to get the java source code generated after using the gmaven plug-in.
Basically, in other words I am dynamically generating new classes (using gmaven Groovy maven plug in) and I would like to be able to obtain the java source code of such generated classes.
I researched a little bit and can see that the only goals for this plug in are
<goal>generateStubs</goal>
<goal>compile</goal>
<goal>generateTestStubs</goal>
<goal>testCompile</goal>
I can't see any goal that allows you to obtain the fully implemented java source code, the stub code is not enough for us as we need the final implementation source code in order to get rid of Groovy.
I'm not very familiar with the gmaven plugin, but I assume it compiles the groovy code into byte code. In this case, you can use a byte code decompiler, there is a nice list here. In the past I've used JAD and it was quite nice. The best ones will also try to create meaningful variable names based on class names.
One warning though - Groovy objects are derived from GObject, not java.lang.Object, so you would probably need to keep the groovy jar until the groovy->java porting is done. Also, be prepared that it won't be a very easy to read java...
It may be out of your scope (1 year old) but I fought against the same problem and found a method to retrieve the algorithm (not the java source code) from the decompiled groovy classes.
You may want to take a look : http://michael.laffargue.fr/blog/2013/11/02/decompiling-groovy-made-classes/
The generated stubs will be useless for you. They are just what their names suggests: stubs.
The stubs are only useful when doing joint java/groovy compilation. That's because there are two compilers involved in a java/groovy mixed project.
Parse groovy
Create stubs
Compile java and stubs (using javac)
Continue groovy compilation (using groovyc)
The groovy code will be compiled using groovyc compiler and the result is byte code.
This is an example of a generated stub:
package maba.groovy;
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.*;
import groovy.lang.*;
import groovy.util.*;
#groovy.util.logging.Log4j() public class Order
extends java.lang.Object implements
groovy.lang.GroovyObject {
public groovy.lang.MetaClass getMetaClass() { return (groovy.lang.MetaClass)null;}
public void setMetaClass(groovy.lang.MetaClass mc) { }
public java.lang.Object invokeMethod(java.lang.String method, java.lang.Object arguments) { return null;}
public java.lang.Object getProperty(java.lang.String property) { return null;}
public void setProperty(java.lang.String property, java.lang.Object value) { }
public int getPrice() { return (int)0;}
public void setPrice(int value) { }
public int getQuantity() { return (int)0;}
public void setQuantity(int value) { }
#java.lang.Override() public java.lang.String toString() { return (java.lang.String)null;}
}
As you can see there is nothing useful. And you will still depend on some groovy libraries.
This question has been on the mailing-list some time ago [0]. To summarize: Groovy to Java is hard to achieve since there are language constructs and APIs (if you do want to totally remove the Groovy dependency) that are not available in Java.
Especially with the introduction of call-site caching and other performance optimizing techniques the generated Java code would look a lot like this (for the matter of simplicity I just threw some script into JD-GUI [1]):
public class script1351632333660 extends Script
{
public script1351632333660()
{
script1351632333660 this;
CallSite[] arrayOfCallSite = $getCallSiteArray();
}
public script1351632333660(Binding arg1)
{
Binding context;
CallSite[] arrayOfCallSite = $getCallSiteArray();
ScriptBytecodeAdapter.invokeMethodOnSuperN($get$$class$groovy$lang$Script(), this, "setBinding", new Object[] { context });
}
public Object run()
{
CallSite[] arrayOfCallSite = $getCallSiteArray(); Object items = ScriptBytecodeAdapter.createList(new Object[0]);
Object[] item = (Object[])ScriptBytecodeAdapter.castToType(ScriptBytecodeAdapter.createList(new Object[] { "Fluff", arrayOfCallSite[1].callConstructor($get$$class$java$util$Date()), (Integer)DefaultTypeTransformation.box(11235813) }), $get$array$$class$java$lang$Object());
arrayOfCallSite[2].call(items, item);
arrayOfCallSite[3].callCurrent(this, items);
ValueRecorder localValueRecorder = new ValueRecorder();
try
{
Object tmp102_101 = items; localValueRecorder.record(tmp102_101, 8);
Object tmp126_121 = arrayOfCallSite[4].call(tmp102_101, new script1351632333660._run_closure1(this)); localValueRecorder.record(tmp126_121, 14); if (DefaultTypeTransformation.booleanUnbox(tmp126_121)) localValueRecorder.clear(); else ScriptBytecodeAdapter.assertFailed(AssertionRenderer.render("assert items.findAll { it }", localValueRecorder), null); } finally {
localValueRecorder.clear(); throw finally; } return null; return null; }
static { __$swapInit();
Long localLong1 = (Long)DefaultTypeTransformation.box(0L);
__timeStamp__239_neverHappen1351632333665 = localLong1.longValue();
Long localLong2 = (Long)DefaultTypeTransformation.box(1351632333665L);
__timeStamp = localLong2.longValue(); }
class _run_closure1 extends Closure implements GeneratedClosure { public _run_closure1(Object _thisObject) { super(_thisObject); }
public Object doCall(Object it) { CallSite[] arrayOfCallSite = $getCallSiteArray(); return it; return null;
}
// ...
[0] http://groovy.329449.n5.nabble.com/Java-lt-gt-Groovy-converters-td337442.html
[1] http://java.decompiler.free.fr

Seeking useful Eclipse Java code templates [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
You can create various Java code templates in Eclipse via
Window > Preferences > Java > Editor > Templates
e.g.
sysout is expanded to:
System.out.println(${word_selection}${});${cursor}
You can activate this by typing sysout followed by CTRL+SPACE
What useful Java code templates do you currently use? Include the name and description of it and why it's awesome.
I am looking for an original/novel use of a template rather than a built-in existing feature.
Create Log4J logger
Get swt color from display
Syncexec - Eclipse Framework
Singleton Pattern/Enum Singleton Generation
Readfile
Const
Traceout
Format String
Comment Code Review
String format
Try Finally Lock
Message Format i18n and log
Equalsbuilder
Hashcodebuilder
Spring Object Injection
Create FileOutputStream
The following code templates will both create a logger and create the right imports, if needed.
SLF4J
${:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
private static final Logger LOG = LoggerFactory.getLogger(${enclosing_type}.class);
Log4J 2
${:import(org.apache.logging.log4j.LogManager,org.apache.logging.log4j.Logger)}
private static final Logger LOG = LogManager.getLogger(${enclosing_type}.class);
Log4J
${:import(org.apache.log4j.Logger)}
private static final Logger LOG = Logger.getLogger(${enclosing_type}.class);
Source.
JUL
${:import(java.util.logging.Logger)}
private static final Logger LOG = Logger.getLogger(${enclosing_type}.class.getName());
Some additional templates here: Link I -
Link II
I like this one:
readfile
${:import(java.io.BufferedReader,
java.io.FileNotFoundException,
java.io.FileReader,
java.io.IOException)}
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(${fileName}));
String line;
while ((line = in.readLine()) != null) {
${process}
}
}
catch (FileNotFoundException e) {
logger.error(e) ;
}
catch (IOException e) {
logger.error(e) ;
} finally {
if(in != null) in.close();
}
${cursor}
UPDATE: The Java 7 version of this template is:
${:import(java.nio.file.Files,
java.nio.file.Paths,
java.nio.charset.Charset,
java.io.IOException,
java.io.BufferedReader)}
try (BufferedReader in = Files.newBufferedReader(Paths.get(${fileName:var(String)}),
Charset.forName("UTF-8"))) {
String line = null;
while ((line = in.readLine()) != null) {
${cursor}
}
} catch (IOException e) {
// ${todo}: handle exception
}
Format a string
MessageFormat - surround the selection with a MessageFormat.
${:import(java.text.MessageFormat)}
MessageFormat.format(${word_selection}, ${cursor})
This lets me move a cursor to a string, expand the selection to the entire string (Shift-Alt-Up), then Ctrl-Space twice.
Lock the selection
lock - surround the selected lines with a try finally lock. Assume the presence of a lock variable.
${lock}.acquire();
try {
${line_selection}
${cursor}
} finally {
${lock}.release();
}
NB ${line_selection} templates show up in the Surround With menu (Alt-Shift-Z).
I know I am kicking a dead post, but wanted to share this for completion sake:
A correct version of singleton generation template, that overcomes the flawed double-checked locking design (discussed above and mentioned else where)
Singleton Creation Template:
Name this createsingleton
static enum Singleton {
INSTANCE;
private static final ${enclosing_type} singleton = new ${enclosing_type}();
public ${enclosing_type} getSingleton() {
return singleton;
}
}
${cursor}
To access singletons generated using above:
Singleton reference Template:
Name this getsingleton:
${type} ${newName} = ${type}.Singleton.INSTANCE.getSingleton();
Append code snippet to iterate over Map.entrySet():
Template:
${:import(java.util.Map.Entry)}
for (Entry<${keyType:argType(map, 0)}, ${valueType:argType(map, 1)}> ${entry} : ${map:var(java.util.Map)}.entrySet())
{
${keyType} ${key} = ${entry}.getKey();
${valueType} ${value} = ${entry}.getValue();
${cursor}
}
Generated Code:
for (Entry<String, String> entry : properties.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
|
}
For log, a helpful little ditty to add in the member variable.
private static Log log = LogFactory.getLog(${enclosing_type}.class);
Create a mock with Mockito (in "Java statements" context):
${:importStatic('org.mockito.Mockito.mock')}${Type} ${mockName} = mock(${Type}.class);
And in "Java type members":
${:import(org.mockito.Mock)}#Mock
${Type} ${mockName};
Mock a void method to throw an exception:
${:import(org.mockito.invocation.InvocationOnMock,org.mockito.stubbing.Answer)}
doThrow(${RuntimeException}.class).when(${mock:localVar}).${mockedMethod}(${args});
Mock a void method to do something:
${:import(org.mockito.invocation.InvocationOnMock,org.mockito.stubbing.Answer)}doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
Object arg1 = invocation.getArguments()[0];
return null;
}
}).when(${mock:localVar}).${mockedMethod}(${args});
Verify mocked method called exactly once:
${:importStatic(org.mockito.Mockito.verify,org.mockito.Mockito.times)}
verify(${mock:localVar}, times(1)).${mockMethod}(${args});
Verify mocked method is never invoked:
${:importStatic(org.mockito.Mockito.verify,org.mockito.Mockito.never)}verify(${mock:localVar}, never()).${mockMethod}(${args});
New linked list using Google Guava (and similar for hashset and hashmap):
${import:import(java.util.List,com.google.common.collect.Lists)}List<${T}> ${newName} = Lists.newLinkedList();
Also I use a huge template that generates a Test class. Here is a shortened fragment of it that everyone interested should customize:
package ${enclosing_package};
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.junit.runner.RunWith;
// TODO autogenerated test stub
#RunWith(MockitoJUnitRunner.class)
public class ${primary_type_name} {
#InjectMocks
protected ${testedType} ${testedInstance};
${cursor}
#Mock
protected Logger logger;
#Before
public void setup() throws Exception {
}
#Test
public void shouldXXX() throws Exception {
// given
// when
// TODO autogenerated method stub
// then
fail("Not implemented.");
}
}
// Here goes mockito+junit cheetsheet
Null Checks!
if( ${word_selection} != null ){
${cursor}
}
if( ${word_selection} == null ){
${cursor}
}
One of my beloved is foreach:
for (${iterable_type} ${iterable_element} : ${iterable}) {
${cursor}
}
And traceout, since I'm using it a lot for tracking:
System.out.println("${enclosing_type}.${enclosing_method}()");
I just thought about another one and have found it over the Internet some day, const:
private static final ${type} ${name} = new ${type} ${cursor};
A little tip on sysout -- I like to renamed it to "sop". Nothing else in the java libs starts with "sop" so you can quickly type "sop" and boom, it inserts.
Throw an IllegalArgumentException with variable in current scope (illarg):
throw new IllegalArgumentException(${var});
Better
throw new IllegalArgumentException("Invalid ${var} " + ${var});
Nothing fancy for code production - but quite useful for code reviews
I have my template coderev low/med/high do the following
/**
* Code Review: Low Importance
*
*
* TODO: Insert problem with code here
*
*/
And then in the Tasks view - will show me all of the code review comments I want to bring up during a meeting.
Some more templates here.
Includes:
Create a date object from a particular date
Create a new generic ArrayList
Logger setup
Log with specified level
Create a new generic HashMap
Iterate through a map, print the keys and values
Parse a time using SimpleDateFormat
Read a file line by line
Log and rethrow a caught exeption
Print execution time of a block of code
Create periodic Timer
Write a String to a file
slf4j Logging
${imp:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
private static final Logger LOGGER = LoggerFactory
.getLogger(${enclosing_type}.class);
Bean Property
private ${Type} ${property};
public ${Type} get${Property}() {
return ${property};
}
public void set${Property}(${Type} ${property}) {
${propertyChangeSupport}.firePropertyChange("${property}", this.${property}, this.${property} = ${property});
}
PropertyChangeSupport
private PropertyChangeSupport ${propertyChangeSupport} = new PropertyChangeSupport(this);${:import(java.beans.PropertyChangeSupport,java.beans.PropertyChangeListener)}
public void addPropertyChangeListener(PropertyChangeListener listener) {
${propertyChangeSupport}.addPropertyChangeListener(listener);
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
${propertyChangeSupport}.addPropertyChangeListener(propertyName, listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
${propertyChangeSupport}.removePropertyChangeListener(listener);
}
public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
${propertyChangeSupport}.removePropertyChangeListener(propertyName, listener);
}
Post Java 7, a great way to set up loggers which need (or prefer) static references to the enclosing class is to use the newly introduced MethodHandles API to get the runtime class in a static context.
An example snippet for SLF4J is:
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
Aside from being a simple snippet in any IDE, it is also less brittle if you refactor certain functionality into another class because you won't accidentally carry the class name with it.
Invoke code on the GUI thread
I bind the following template to the shortcut slater to quickly dispatch code on the GUI thread.
${:import(javax.swing.SwingUtilities)}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
${cursor}
}
});
When testing around with code I sometimes missed out on deleting some syso s. So I made myself a template called syt.
System.out.println(${word_selection}${});//${todo}:remove${cursor}
Before I compile I always check my TODOs and will never forget to delete a System.out again.
strf -> String.format("msg", args) pretty simple but saves a bit of typing.
String.format("${cursor}",)
Get an SWT color from current display:
Display.getCurrent().getSystemColor(SWT.COLOR_${cursor})
Suround with syncexec
PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable(){
public void run(){
${line_selection}${cursor}
}
});
Use the singleton design pattern:
/**
* The shared instance.
*/
private static ${enclosing_type} instance = new ${enclosing_type}();
/**
* Private constructor.
*/
private ${enclosing_type}() {
super();
}
/**
* Returns this shared instance.
*
* #returns The shared instance
*/
public static ${enclosing_type} getInstance() {
return instance;
}
And an equalsbuilder, hashcodebuilder adaptation:
${:import(org.apache.commons.lang.builder.EqualsBuilder,org.apache.commons.lang.builder.HashCodeBuilder)}
#Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
#Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
The template for the logger declaration is great.
I also create linfo, ldebug, lwarn, lerror for the log levels that I use more often.
lerror:
logger.error(${word_selection}${});${cursor}
Create everything for an event
Since events are kinda a pain to create in Java--all those interfaces, methods, and stuff to write just for 1 event--I made a simple template to create everything needed for 1 event.
${:import(java.util.List, java.util.LinkedList, java.util.EventListener, java.util.EventObject)}
private final List<${eventname}Listener> ${eventname}Listeners = new LinkedList<${eventname}Listener>();
public final void add${eventname}Listener(${eventname}Listener listener)
{
synchronized(${eventname}Listeners) {
${eventname}Listeners.add(listener);
}
}
public final void remove${eventname}Listener(${eventname}Listener listener)
{
synchronized(${eventname}Listeners) {
${eventname}Listeners.remove(listener);
}
}
private void raise${eventname}Event(${eventname}Args args)
{
synchronized(${eventname}Listeners) {
for(${eventname}Listener listener : ${eventname}Listeners)
listener.on${eventname}(args);
}
}
public interface ${eventname}Listener extends EventListener
{
public void on${eventname}(${eventname}Args args);
}
public class ${eventname}Args extends EventObject
{
public ${eventname}Args(Object source${cursor})
{
super(source);
}
}
If you have events that share a single EventObject, just delete the customized one inserted by the template and change the appropriate parts of raise___() and on____().
I had written a nice, little, elegant eventing mechanism using a generic interface and generic class, but it wouldn't work due to the way Java handles generics. =(
Edit:
1) I ran into the issue where threads were adding/removing listeners while an event was taking place. The List can't be modified while in use, so I added synchronized blocks where the list of listeners is being accessed or used, locking on the list itself.
Insert test methods should-given-when-then
I saw a similar version to this one recently while pair programming with a very good developer and friend, and I think it could be a nice addition to this list.
This template will create a new test method on a class, following the Given - When - Then approach from the behavior-driven development (BDD) paradigm on the comments, as a guide for structuring the code. It will start the method name with "should" and let you replace the rest of the dummy method name "CheckThisAndThat" with the best possible description of the test method responsibility. After filling the name, TAB will take you straight to the // Given section, so you can start typing your preconditions.
I have it mapped to the three letters "tst", with description "Test methods should-given-when-then" ;)
I hope you find it as useful as I did when I saw it:
#Test
public void should${CheckThisAndThat}() {
Assert.fail("Not yet implemented");
// Given
${cursor}
// When
// Then
}${:import(org.junit.Test, org.junit.Assert)}
Spring Injection
I know this is sort of late to the game, but here is one I use for Spring Injection in a class:
${:import(org.springframework.beans.factory.annotation.Autowired)}
private ${class_to_inject} ${var_name};
#Autowired
public void set${class_to_inject}(${class_to_inject} ${var_name}) {
this.${var_name} = ${var_name};
}
public ${class_to_inject} get${class_to_inject}() {
return this.${var_name};
}
Here is a constructor for non-instantiable classes:
// Suppress default constructor for noninstantiability
#SuppressWarnings("unused")
private ${enclosing_type}() {
throw new AssertionError();
}
This one is for custom exceptions:
/**
* ${cursor}TODO Auto-generated Exception
*/
public class ${Name}Exception extends Exception {
/**
* TODO Auto-generated Default Serial Version UID
*/
private static final long serialVersionUID = 1L;
/**
* #see Exception#Exception()
*/
public ${Name}Exception() {
super();
}
/**
* #see Exception#Exception(String)
*/
public ${Name}Exception(String message) {
super(message);
}
/**
* #see Exception#Exception(Throwable)
*/
public ${Name}Exception(Throwable cause) {
super(cause);
}
/**
* #see Exception#Exception(String, Throwable)
*/
public ${Name}Exception(String message, Throwable cause) {
super(message, cause);
}
}
I like a generated class comment like this:
/**
* I...
*
* $Id$
*/
The "I..." immediately encourages the developer to describe what the class does. I does seem to improve the problem of undocumented classes.
And of course the $Id$ is a useful CVS keyword.
I've had a lot of use of these snippets, looking for null values and empty strings.
I use the "argument test"-templates as the first code in my methods to check received arguments.
testNullArgument
if (${varName} == null) {
throw new NullPointerException(
"Illegal argument. The argument cannot be null: ${varName}");
}
You may want to change the exception message to fit your company's or project's standard. However, I do recommend having some message that includes the name of the offending argument. Otherwise the caller of your method will have to look in the code to understand what went wrong. (A NullPointerException with no message produces an exception with the fairly nonsensical message "null").
testNullOrEmptyStringArgument
if (${varName} == null) {
throw new NullPointerException(
"Illegal argument. The argument cannot be null: ${varName}");
}
${varName} = ${varName}.trim();
if (${varName}.isEmpty()) {
throw new IllegalArgumentException(
"Illegal argument. The argument cannot be an empty string: ${varName}");
}
You can also reuse the null checking template from above and implement this snippet to only check for empty strings. You would then use those two templates to produce the above code.
The above template, however, has the problem that if the in argument is final you will have to amend the produced code some (the ${varName} = ${varName}.trim() will fail).
If you use a lot of final arguments and want to check for empty strings but doesn't have to trim them as part of your code, you could go with this instead:
if (${varName} == null) {
throw new NullPointerException(
"Illegal argument. The argument cannot be null: ${varName}");
}
if (${varName}.trim().isEmpty()) {
throw new IllegalArgumentException(
"Illegal argument. The argument cannot be an empty string: ${varName}");
}
testNullFieldState
I also created some snippets for checking variables that is not sent as arguments (the big difference is the exception type, now being an IllegalStateException instead).
if (${varName} == null) {
throw new IllegalStateException(
"Illegal state. The variable or class field cannot be null: ${varName}");
}
testNullOrEmptyStringFieldState
if (${varName} == null) {
throw new IllegalStateException(
"Illegal state. The variable or class field cannot be null: ${varName}");
}
${varName} = ${varName}.trim();
if (${varName}.isEmpty()) {
throw new IllegalStateException(
"Illegal state. The variable or class field " +
"cannot be an empty string: ${varName}");
}
testArgument
This is a general template for testing a variable. It took me a few years to really learn to appreciate this one, now I use it a lot (in combination with the above templates of course!)
if (!(${varName} ${testExpression})) {
throw new IllegalArgumentException(
"Illegal argument. The argument ${varName} (" + ${varName} + ") " +
"did not pass the test: ${varName} ${testExpression}");
}
You enter a variable name or a condition that returns a value, followed by an operand ("==", "<", ">" etc) and another value or variable and if the test fails the resulting code will throw an IllegalArgumentException.
The reason for the slightly complicated if clause, with the whole expression wrapped in a "!()" is to make it possible to reuse the test condition in the exception message.
Perhaps it will confuse a colleague, but only if they have to look at the code, which they might not have to if you throw these kind of exceptions...
Here's an example with arrays:
public void copy(String[] from, String[] to) {
if (!(from.length == to.length)) {
throw new IllegalArgumentException(
"Illegal argument. The argument from.length (" +
from.length + ") " +
"did not pass the test: from.length == to.length");
}
}
You get this result by calling up the template, typing "from.length" [TAB] "== to.length".
The result is way funnier than an "ArrayIndexOutOfBoundsException" or similar and may actually give your users a chance to figure out the problem.
Enjoy!
I use this for MessageFormat (using Java 1.4). That way I am sure that I have no concatenations that are hard to extract when doing internationalization
i18n
String msg = "${message}";
Object[] params = {${params}};
MessageFormat.format(msg, params);
Also for logging:
log
if(logger.isDebugEnabled()){
String msg = "${message}"; //NLS-1
Object[] params = {${params}};
logger.debug(MessageFormat.format(msg, params));
}
My favorite few are...
1: Javadoc, to insert doc about the method being a Spring object injection method.
Method to set the <code>I${enclosing_type}</code> implementation that this class will use.
*
* #param ${enclosing_method_arguments}<code>I${enclosing_type}</code> instance
2: Debug window, to create a FileOutputStream and write the buffer's content's to a file.
Used for when you want to compare a buffer with a past run (using BeyondCompare), or if you can't view the contents of a buffer (via inspect) because its too large...
java.io.FileOutputStream fos = new java.io.FileOutputStream( new java.io.File("c:\\x.x"));
fos.write(buffer.toString().getBytes());
fos.flush();
fos.close();

Categories