Pages

Friday, February 24, 2012

Useful Eclipse Templates for Faster Coding

from:  http://fahdshariff.blogspot.com/2011/08/useful-eclipse-templates-for-faster.html
 
I wrote about my Eclipse code templates a few years ago and since then I've made a quite a few changes to them. I've added a few new templates to help with JUnit tests and xml parsing. I've also updated my existing file IO templates to use Java 7 features.
Templates are simply "magic words" or shortcuts to standard blocks of code or text. They are very handy because once you have them setup you don't have to waste time writing boilerplate code any more! An example of a pre-defined template in Eclipse is sysout which expands to System.out.println();. All you have to do is type sysout followed by Ctrl+Space to insert the statement into your Java source file.

To see what templates are defined in Eclipse:
  • Open your Preferences dialog by going to Windows > Preferences
  • On the navigation tree on the left, go to Java > Editor > Templates
  • You will see a list of pre-defined templates
  • You can add new ones by pressing the "New..." button
My templates are shown below. They can also be downloaded from my GitHub repository and then imported into Eclipse. General Utility Templates:

Nameif
ContextJava statements
Descriptionif null
Pattern
if (${var} == null){
    ${cursor}
}
Nameif
ContextJava statements
Descriptionif not null
Pattern
if (${var} != null){
    ${cursor}
}
Namefor
ContextJava statements
Descriptioniterate over map
Pattern
${:import(java.util.Map.Entry)}
for(Entry<${key:argType(map,0)},${value:argType(map,1)}> entry :
                    ${map:var(java.util.Map)}.entrySet()) {
    ${key} key = entry.getKey();
    ${value} value = entry.getValue();
    ${cursor}
}
Namestrf
ContextJava
Descriptionformat string
Pattern
String.format("${word_selection}${}",${var}${cursor})
Namesysf
ContextJava statements
Descriptionprint formatted string to standard out
Pattern
System.out.printf("${word_selection}${}",${var}${cursor});
Namestatic_final
ContextJava type members
Descriptionstatic final field
Pattern
${visibility:link(
              public,
              protected,
              private)} static final ${type} ${NAME} = ${word_selection}${};
File IO Templates:
The following templates are useful for reading or writing files. They use Java 7 features such as try-with-resources to automatically close files. They also use methods from NIO2.0 to obtain a buffered reader and read the file.

Namereadfile
ContextJava statements
Descriptionread text from file
Pattern
${: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
}
Namereadfile
ContextJava statements
Descriptionread all lines from file as a list
Pattern
${:import(java.nio.file.Files,
          java.nio.file.Paths,
          java.nio.charset.Charset,
          java.util.List,
          java.util.ArrayList)}
Lis<String> lines = new ArrayList<>();
try{
    lines = Files.readAllLines(Paths.get(${fileName:var(String)}),
                                        Charset.forName("UTF-8"));
}catch (IOException e) {
    // ${todo}: handle exception
}
${cursor}
Namewritefile
ContextJava statements
Descriptionwrite text to file
Pattern
${:import(java.nio.file.Files,
          java.nio.file.Paths,
          java.nio.Charset,
          java.io.IOException,
          java.io.BufferedWriter)}
try (BufferedWriter out = Files.newBufferedWriter(Paths.get(${fileName:var(String)}),
                                                  Charset.forName("UTF-8"))) {
    out.write(${string:var(String)});
    out.newLine();
    ${cursor}
} catch (IOException e) {
    // ${todo}: handle exception
}
XML Templates:
The following templates are used to read xml files or strings and return a DOM.

Nameparsexml
ContextJava statements
Descriptionparse xml file as Document
Pattern
${:import(org.w3c.dom.Document,
          javax.xml.parsers.DocumentBuilderFactory,
          java.io.File,
          java.io.IOException,
          javax.xml.parsers.ParserConfigurationException,
          org.xml.sax.SAXException)}
Document doc = null;
try {
    doc = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder()
            .parse(new File(${filename:var(String)}));
} catch (SAXException | IOException | ParserConfigurationException e) {
    // ${todo}: handle exception
}
${cursor}
Nameparsexml
ContextJava statements
Descriptionparse xml string as Document
Pattern
${:import(org.w3c.dom.Document,
          javax.xml.parsers.DocumentBuilderFactory,
          org.xml.sax.InputSource,
          java.io.StringReader,
          java.io.IOException,
          javax.xml.parsers.ParserConfigurationException,
          org.xml.sax.SAXException)}
Document doc = null;
try {
    doc = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder()
            .parse(new InputSource(new StringReader(${str:var(String)})));
} catch (SAXException | IOException | ParserConfigurationException e) {
    // ${todo}: handle exception
}
${cursor}
Logging Templates:
The templates below are useful for creating a logger and logging messages. I use SLF4J, but they could easily be tweaked to use any other logging framework.

Namelogger
ContextJava type members
Descriptioncreate new logger
Pattern
${:import(org.slf4j.Logger,
          org.slf4j.LoggerFactory)}
private static final Logger LOGGER =
       LoggerFactory.getLogger(${enclosing_type}.class);
Namelogd
ContextJava statements
Descriptionlogger debug
Pattern
if(LOGGER.isDebugEnabled())
     LOGGER.debug(${word_selection}${});
${cursor}
Namelogi
ContextJava statements
Descriptionlogger info
Pattern
LOGGER.info(${word_selection}${});
${cursor}
Namelogerr
ContextJava statements
Descriptionlogger error
Pattern
LOGGER.error(${word_selection}${}, ${exception_variable_name});
Namelogthrow
ContextJava statements
Descriptionlog error and throw exception
Pattern
LOGGER.error(${word_selection}${}, ${exception_variable_name});
throw ${exception_variable_name};
${cursor}
JUnit Templates:
The templates below assist in writing JUnit tests.

Namebefore
ContextJava type members
Descriptionjunit before method
Pattern
${:import (org.junit.Before)}
 
@Before
public void setUp() {
    ${cursor}
}
Nameafter
ContextJava type members
Descriptionjunit after method
Pattern
${:import (org.junit.After)}
 
@After
public void tearDown() {
    ${cursor}
}
Namebeforeclass
ContextJava type members
Descriptionjunit beforeclass method
Pattern
${:import (org.junit.BeforeClass)}
 
@BeforeClass
public static void oneTimeSetUp() {
    // one-time initialization code
    ${cursor}
}
Nameafterclass
ContextJava type members
Descriptionjunit afterclass method
Pattern
${:import (org.junit.AfterClass)}
 
@AfterClass
public static void oneTimeTearDown() {
    // one-time cleanup code
    ${cursor}
}
Do YOU have any useful templates? If so, share them in the comments section!

No comments:

Post a Comment