I am learning Spock so this may be very basic.
public Random genRand() {
try {
return SecureRandom.getInstanceStrong();
}
catch (NoSuchAlgorithmException e) {
logger.debug(e.getMessage());
return new SecureRandom();
}
}
What I have tried so far is:
public void setup() {
mockClassName = spy(ClassName)
mockClassName.logger() >> mockLogger
}
def "exception test case"() {
given: "nothing"
when:"method call happens"
mockClassName.genRand()
then:"handle"
SecureRandom.getInstanceStrong()
}
This covers the try block only.
While trying:
public void setup() {
mockClassName = spy(ClassName)
mockClassName.logger() >> mockLogger
}
def "exception test case"() {
given: "nothing"
SecureRandom.getInstanceStrong() >> Exception
when:"method call happens"
mockClassName.genRand()
then:"catch"
NoSuchAlgorithmException e = thrown()
new SecureRandom()
}
This gives the error, expected exception of type java.security.NoSuchAlgorithmException, but no exception was thrown.
Is it possible to do both try and catch in one test case? Feel free to make two.
You should not try to test several branches of your code in one test, so doing it in two tests is actually the right approach. If you try to find a simple description of your test and have to describe several kinds of results, then that's a hint that your approach is not good.
A reminder, you should name your test methods with "It...", for example:
"It returns a default SecureRandom, if no strong instance of SecureRandom can be found"
Another point: You code never leaks a NoSuchAlgorithmException into Spec. This exception is caught in your production code, and then you retunr a valid SecureRandom. You can only use thrown() if your code actually throws an exception, meaning this is a hard expectation. Your test will fail if the exception is not thrown.
Quoting my own comment:
Why don't you want to change the application code in order to make it more testable? You could factor out the SecureRandom.getInstanceStrong() call into an extra method, calling it from genRand(), handling the exception there like before. Then you could stub that method in a spy for the error case, throwing an exception instead of returning a result. That would give you full coverage of all execution paths without the need to mock static methods of JDK classes.
I mean something like this:
package de.scrum_master.stackoverflow.q74797317;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
public class RandomProvider {
public Random genRand() {
try {
return getRandStrong();
}
catch (NoSuchAlgorithmException e) {
System.err.println(e.getMessage());
return new SecureRandom();
}
}
protected SecureRandom getRandStrong() throws NoSuchAlgorithmException {
return SecureRandom.getInstanceStrong();
}
}
package de.scrum_master.stackoverflow.q74797317
import spock.lang.Specification
import java.security.NoSuchAlgorithmException
class RandomProviderTest extends Specification {
def "happy path"() {
given:
RandomProvider randomProvider = new RandomProvider()
expect:
randomProvider.genRand()
}
def "exception test case"() {
given:
RandomProvider randomProvider = Spy() {
getRandStrong() >> { throw new NoSuchAlgorithmException("oops") }
}
expect:
randomProvider.genRand()
}
}
Try it in the Groovy Web Console.
In my IDE, the coverage view looks like this:
I was wondering if there is a Java API that could tell you whether a particular language feature (e.g. "diamond" operator) is available on the current platform.
(In other words, what I'm trying to do is analogous to "browser sniffing" in JavaScript.)
This would be really handy in meta-programming (writing a Java program that generates Java source code.
The best solution I've found so far is to parse System.getProperty("java.specification.version") and check whether it's ≥ the version that introduced this feature, but I'm not 100% sure that this property is available in all JVMs (or even whether it conforms to the same syntax in all JVMs). Another minor annoyance with this approach is that you have to take the extra step of looking up which version of Java introduced the language feature you're interested in. Not a big deal, since that info is pretty easy to google, but ideally it would be nice if there was an API that could readily provide the info, for example:
code.append("Map<Integer, String> map = ");
if (javax.meta.JavaVersion.getCurrentVersion().supportsDiamond()) {
code.append("new Map<>();");
} else {
code.append("new Map<Integer, String>();");
}
Obviously there's no package named javax.meta, but I was wondering if there might already be an existing solution for this problem that's cleaner than parsing the "java.specification.version" property.
Update: I just realized that Package#getSpecificationVersion() also provides the same value as System.getProperty("java.specification.version") but is probably more reliable, because System properties are mutable. In other words, the best way to get the Java spec version is probably to call Package#getSpecificationVersion() on any "built-in" package. For example: String.class.getPackage().getSpecificationVersion()
This will give you the version of java that the system is running.
System.getProperty("java.version")
If you're running Java 9 and greater you can use:
Runtime.Version version = Runtime.version();
Java Docs
Just a note the Java versioning naming standard changed at Java 9 as well.
Java Version: 1.7, 1.8, 9, 10, 11
I don't have a solution for you to check for specific features.
A feature could be: JDK 10
Method : Optional.orElseThrow()
API : API for Creating Unmodifiable Collections
System Property : Fore example, to Disable JRE Last Usage Tracking
GC enhancement (Full parallel)
Javadoc Support : (For Multiple Stylesheets)
It Could also be a REMOVAL of feature : also in Java 10
Removal of Support for Using Old LookAndFeel
Removal of Runtime.getLocalizedInputStream and getLocalizedOutputStream Methods
And so on..
So it is hard to check or discover programmatcally if a new feature exist or of it has been removed UNLESS you know what you are looking for, it needs to to be provided by Oracle itself as a documentation, feature name and description.
If we are going to create and API for that, we must get the list first from Oracle docs, and then do required checks for each feature to discover the current version or if it is supported.
Following is an example to programmaticaly check the compiler for a specific functionality.
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.Arrays;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject.Kind;
public class CompileSourceInMemory {
public static void main(String args[]) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
out.println("public class HelloWorld {");
out.println(" public static void main(String args[]) {");
out.println(" System.out.println(\"This is in another java file\");");
out.println(" }");
out.println("}");
out.close();
JavaFileObject file = new JavaSourceFromString("HelloWorld", writer.toString());
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
boolean success = task.call();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
System.out.println(diagnostic.getCode());
System.out.println(diagnostic.getKind());
System.out.println(diagnostic.getPosition());
System.out.println(diagnostic.getStartPosition());
System.out.println(diagnostic.getEndPosition());
System.out.println(diagnostic.getSource());
System.out.println(diagnostic.getMessage(null));
}
System.out.println("Success: " + success);
if (success) {
try {
Class.forName("HelloWorld").getDeclaredMethod("main", new Class[] { String[].class })
.invoke(null, new Object[] { null });
} catch (ClassNotFoundException e) {
System.err.println("Class not found: " + e);
} catch (NoSuchMethodException e) {
System.err.println("No such method: " + e);
} catch (IllegalAccessException e) {
System.err.println("Illegal access: " + e);
} catch (InvocationTargetException e) {
System.err.println("Invocation target: " + e);
}
}
}
}
class JavaSourceFromString extends SimpleJavaFileObject {
final String code;
JavaSourceFromString(String name, String code) {
super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),Kind.SOURCE);
this.code = code;
}
#Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}
See JDK 10 features
I just discovered another partial solution: javax.lang.model.SourceVersion. It still doesn't solve the problem entirely, but seems like a step in the right direction.
So instead of my old approach,
if (System.getProperty("java.specification.version").compareTo("1.7") >= 0)
// do something that requires Java 7
you could write:
if (SourceVersion.latestSupported().ordinal() >= SourceVersion.RELEASE_7.ordinal())
// do something that requires Java 7
(because SourceVersion has its enum constants declared in ascending order)
This class also provides the static methods isKeyword, isName, isIdentifier, which might be useful, but it was already reasonably easy to derive some of this info (e.g. Character.isJavaIdentifierPart(cp)).
Under the hood, SourceVersion also relies on reading the "java.specification.version" system property:
private static SourceVersion getLatestSupported() {
try {
String specVersion = System.getProperty("java.specification.version");
if ("1.8".equals(specVersion))
return RELEASE_8;
else if("1.7".equals(specVersion))
return RELEASE_7;
else if("1.6".equals(specVersion))
return RELEASE_6;
} catch (SecurityException se) {}
return RELEASE_5;
}
That's some smelly code right there! e.g. if someone calls System.setProperty("java.specification.version", "6.9"); then SourceVersion.latestSupported() will return RELEASE_5 ;)
I'm surprised that even Sun didn't provide a "magic" way to get the Java version directly from the VM (like the various internal "magic" operations exposed by the sun.misc package)
This question already has answers here:
Better understaning - Class.forName("com.mysql.jdbc.Driver").newInstance ();
(4 answers)
Closed 10 years ago.
I am a java beginner and trying to insert a row in db. This is first time in java i am performing insertion operation. For around 2 Hrs i was googling and frustated and cannot solve my error. I called my friend and he gave live support for me in team viewer and added just one line of code to my program.
Class.forName("com.mysql.jdbc.Driver")
Can anyone please explain why we need to include this in my code before connection string. Is it necessary to place my code there each and every time. Please Explain me in Detail.
Here is some very simplified code that illustrates how driver initialization works. There are 3 classes, please put each one in an appropriately-named file.
import java.util.HashMap;
import java.util.Map;
public class DriverMgr {
private static final Map<String, Class<?>> DRIVER_MAP = new HashMap<String, Class<?>>();
public static void registerDriver(final String name, final Class<?> cls) {
DRIVER_MAP.put(name, cls);
}
public static Object getDriver(final String name) {
final Class<?> cls = DRIVER_MAP.get(name);
if (cls == null) {
throw new RuntimeException("Driver for " + name + " not found");
}
try {
return cls.newInstance();
} catch (Exception e) {
throw new RuntimeException("Driver instantiation failed", e);
}
}
}
public class MysqlDriver {
static {
// hello, I am a static initializer
DriverMgr.registerDriver("mysql", MysqlDriver.class);
}
#Override
public String toString() {
return "I am the mysql driver";
}
}
public class TestProg {
public static void main(final String... args) {
try {
Class.forName("MysqlDriver"); // try with or without this
} catch (Exception e) {
throw new RuntimeException("Oops, failed to initialize the driver");
}
System.out.println(DriverMgr.getDriver("mysql"));
}
}
When you call Class.forName, the driver class gets loaded and the static initializer gets executed. That in turn registers the driver class with the driver manager, so that the manager is now aware of it. Obviously, this only needs to be done once.
Class.forName("com.mysql.jdbc.Driver")
It must be required to load the driver of database which you are using.
the forNmae() method in this line load the driver of mysql database.
Yes , it's necessary to include every time .
but you can use a method for not repeating the codes .
for example
public void connectToMYSQL(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdatabase","username",""password);
}catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
and before writing any sql statement , just call the method for example
public void insert(String sql)
{
connectToMYSQL();
//.. then do your stuffs
}
The basic idea is that this action forces the driver class to be registered in JDBC's driver manager.
The method Class.forName("fully qualified class name) is used to initialize the static fields of the class and load the JDBC driver class, MySQL driver in your case, to your application. When it is instantiated, it gets registered with the DriverManager. By the latter you create connections, using Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","login","password");, which you later use to query the database.
just started using the Serializable-thingy, I want to save a couple of lists and some other objects, but I can't seem to get some things right.
I have some JLists with their own "DefaultListModel" that I use to sort things in the list, I call the class SortModel, when I run the program I do this:
SortModel sortModel = new SortModel();
JList jList = new JList(sortModel);
Then later when the program runs, objects are added and sorted according to the specified needs, now, when I save the lists and load them again, they're empty.
I also save a object of a class that holds the background for the program (user chooses one themself), after saving it I need to add it again to the program (the object, background is stored in it), I need to add it to the program again not only load it "as it where", plus I have some objects that I added on that object with their own listeners. After I somehow succeeded in loading it, the objects are there but I can't use them, so I figure listeners don't get saved?
* explaining edit
The class that is the program extends JFrame, nothing funny about that I think.
The "background obect" (call it map) extends JComponent, I add this to (let's call it program for now...) the program and it pops up with the image which it holds. Onto this map I then add objects that also extends JComponent (call them dots), the dots are assigned their own listeners before they're added, the listeners might not be "real" listeners, but they act the same way, they're "MouseAdapter" does that makes any difference?.
/explaining edit *
* code edit *
code for saving:
FileOutputStream fOut = new FileOutputStream("testFile.mpd");
ObjectOutputStream outSt = new ObjectOutputStream(fOut);
outSt.writeObject(savedMap);
"testFile.mpd" is what it sounds like, I'm quite sure the .mpd shouldn't matter, you can make up your own formats, right? :) (main-class is called Mappedoodle, .mpd sounds reasonable, no?)
"savedMap" is an object of said Mappedoodle and holds all lists and other information needed to be saved.
code for loading:
FileInputStream fIn = new FileInputStream("testFile.mpd");
ObjectInputStream inSt = new ObjectInputStream(fIn);
Mappedoodle openedMap = (Mappedoodle)inSt.readObject();
The information in openedMap is used (well... it should be...) to overwrite certain things in the program.
* /code edit *
Adding everything back onto this object, even adding everything back into the lists wouldn't be so hard since that's just some more lists and a few loops, but I feel like I just don't really get Serializable ^^ so, someone care to try to explain why not everything gets saved? And if it is, why I can't access it? But if I can, how? :)
I don't know what more code should be relevant, please tell me what more information you would need to help me solve this, pasting the whole program would be really messy since it's 11 classes and quite a few lines.
Thanks <3
The code you must show us must be sufficient to demonstrate your error, and I unfortunately must state that yours doesn't. For instance if I use your code in a very simple example (something I recommend that you do), you'll see that it works. My test code:
Mappedoodle.java
import java.io.Serializable;
public class Mappedoodle implements Serializable {
private static final long serialVersionUID = -1760231235147491826L;
private String text;
private int value;
public Mappedoodle(String text, int value) {
this.text = text;
this.value = value;
}
public String getText() {
return text;
}
public int getValue() {
return value;
}
#Override
public String toString() {
return text + ", " + value;
}
}
MappedoodleSerialize.java
import java.io.*;
public class MappedoodleSerialize {
public static void main(String[] args) {
Mappedoodle savedMap = new Mappedoodle("Fubar", 200);
FileOutputStream fOut;
try {
// your code below
fOut = new FileOutputStream("testFile.mpd");
ObjectOutputStream outSt = new ObjectOutputStream(fOut);
outSt.writeObject(savedMap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
MappedoodleDeSerialize.java
import java.io.*;
public class MappedoodleDeSerialize {
public static void main(String[] args) {
try {
// your code below
FileInputStream fIn = new FileInputStream("testFile.mpd");
ObjectInputStream inSt = new ObjectInputStream(fIn);
Mappedoodle openedMap = (Mappedoodle) inSt.readObject();
System.out.println(openedMap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
}
}
}
This bit of code compiles, runs and outputs as expected. Your error must lie in code that you've not shown us.
This problem was solved 5 years ago, the solution is lost due to bad memory though.
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();