DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Frameworks Topics

article thumbnail
Effective Eclipse: Custom Templates
The same way I try to avoid the redundancy in my code, the same way I try to avoid the redundancy in my writing. I am lazy and templates do the most writing for me. Eclipse comes bundled with predefined templates, but they are too general and not all of them are too useful. The real power is in custom templates. In this article I would like to show you how to create them and list a few useful pieces for inspiration. What are templates Exactly as the name suggests, templates are little pieces of code with defined placeholders. An example of simple template is System.out.println(${text}); Each template has a name, which serves as a shortcut to the template itself. You type the name, press CTRL + SPACE and it will be expanded. Our first template would expand to [img_assist|nid=1424|title=|desc=|link=none|align=middle|width=186|height=19] I will not explain here what it all means, I already did this in my previous post on templates. What is important now, is that the ${text} placeholder (variable) was highlighted and can be edited immediately. The true power of templates can be fully seen in more complex templates. The first power point lies in the fact, that you can have more than one variable with same name. Our second template will have more variables: int ${increment} = ${value}; y = ${increment} + ${increment}; and will expand to [img_assist|nid=1428|title=|desc=|link=none|align=middle|width=204|height=45] When you start typing now, all occurrences of increment variable will be changed. You can then switch to the next variable by pressing TAB key. In the end, you can have [img_assist|nid=1425|title=|desc=|link=none|align=middle|width=110|height=43] in just three key presses - one for i, one for TAB and one for 2. To make it even better, the template system provides predefined variables, which will be expanded depending on their context. I will not list them, you can find them under the Insert variable button. [img_assist|nid=1426|title=|desc=|link=popup|align=middle|width=640|height=274] Notice, that you are not getting only a list, you are also getting a description and an usage example. To make it clear, I will illustrate one builtin variable - ${enclosing_type}. When this one is expanded you will get a name of the class (or interface, enum) in which your template was expanded. "But how can I use it?", I hear you asking. I have prepared few templates just for inspiration, I believe that after reading this you will find thousands others and I believe that you will create them and share them with us. Custom templates Open Window -> Preferences and type Templates into the search box. [img_assist|nid=1427|title=|desc=|link=popup|align=middle|width=640|height=578] You will get a list of all editors, and their respective template settings. This is because templates are closely bound to editors - you will get different builtin variables in different editors. Also note, that your list may vary from my list, it all depends on installed plugins. Now you must decide what type of template you would like to create. If it is a Java template, which will be applicable in context of classes, interfaces and enums, then choose Java -> Editor -> Templates. If you create a Java template you won't be able to use it in XML editor, that's quite expected. So click on the New button, to get a dialog. Here it is, in all its glory: [img_assist|nid=1430|title=|desc=|link=popup|align=middle|width=640|height=316] Name is the name of the template. Choose it well, because it will serve as a shortcut to your template. After you type the name of the template (or at least a few characters from its name) and hit CTRL+SPACE it will be expanded. Description is what you will see next to the template name when the template name is ambiguous. [img_assist|nid=1433|title=|desc=|link=none|align=middle|width=415|height=296] Pattern is the template body. And the Context? This varies in every editor. If you look in the combobox in Java templates, you will see Java and Javadoc. It is simple a context within the respective editor in which the template would be applicable. Check Automatically insert if you want the template to expand automatically on ctrl-space when there is no other matching template available. It is usually good idea to leave the checkbox checked, otherwise you would get a template proposal "popup". See what happens when I uncheck it on sysout template. [img_assist|nid=1432|title=|desc=|link=none|align=middle|width=256|height=46] If I would have checked it, it would automatically expand, as there is no other template matching sysout* pattern. My list So here is the list I promised. I have categorized it. Java (Java->Editor->Templates) logger - create new Logger private static final Logger logger = Logger.getLogger(${enclosing_type}.class.getName()); Notice the usage of ${enclosing_type} variable. This way you can create a logger in few hits. After the template expands, you will probably get red lines, indicating that Logger clas could not be found. Just hit CTRL + SHIFT + O to invoke the organize imports function. You are using shortcuts, aren't you? loglevel - log with specified level if(${logger:var(java.util.logging.Logger)}.isLoggable(Level.${LEVEL})) { ${logger:var(java.util.logging.Logger)}.${level}(${}); } ${cursor} Let me explain the details. ${logger:var(java.util.logging.Logger)} uses a builtin "var" variable. It starts with logger, the default name, in case the var variable finds no match. It is then followed by var(java.util.logging.Logger), what will evaluate to the name of the variable (member or local) of the specified type (in our case of the Logger type). Further, the ${cursor} variable marks the place where the cursor will jump after you press enter. So the result after expanding could be [img_assist|nid=1429|title=|desc=|link=none|align=middle|width=297|height=66] You might wonder what is the purpose of the if. It is there only for performance gain. If specified level is not allowed the logging method will never be called and we can spare JVM some string manipulation to build the message. readfile - read text from file Never can remember how to open that pesky file and read from it? Nor can I, so I have a template for it. BufferedReader in; try { in = new BufferedReader(new FileReader(${file_name})); String str; while ((str = in.readLine()) != null) { ${process} } } catch (IOException e) { ${handle} } finally { in.close(); } ${cursor} Maven (Web and XML -> XML Files -> Templates) dependency - maven dependency ${groupId} ${artifactId} ${version} ${cursor} parent - maven parent project definition ${artifactId} ${groupId} ${version} {$path}/pom.xml ${cursor} web.xml (Web and XML -> XML Files -> Templates) servlet - new servlet definition ${servlet_name} ${servlet_class} ${0} ${servlet_name} *.html ${cursor} JSP pages (Web and XML -> JSP Files -> Templates) spring-text - spring text field with label and error ${cursor} spring-checkbox ${cursor} spring-select ${cursor} spring-generic ${cursor} These are my favorites. They regularly save me a huge amount of time. Creating spring forms has never been easier for me. In some editor types you can set the template to 'new', for example, in XML editor it is new XML. This is really useful, as you can prepare the skeleton of a new file. For example, this is what I use to create new Spring servlet configuration for freemarker application. true messages Now, I can create new XML file from template and it will be ready to use. Before I knew about templates, I used to copy this from an older project, or search for it in Spring documentation. Now I don't have to.. [img_assist|nid=1431|title=|desc=|link=none|align=middle|width=640|height=201] If you can overcome the initial laziness and create your own templates from the pieces of code you really use, than this investment will shortly return in form of less typing. If you have some interesting templates, please, share them with us. You can download the templates mentioned in this post and import them using the Import button in the editor template settings.
February 28, 2008
by Tomas Kramar
· 232,605 Views · 1 Like
article thumbnail
Effective Eclipse: Don't write the code, generate it
I hope that we will never be able to generate applications. I would be without a job then and you probably too. But what we can generate are various repetitive and boring pieces of code. The first thing that can be generated is class file. You are using it, but you have probably never realized how much time does it save you. If there was no class skeleton generation, you would have to: create new file in the proper directory (with respect to package (and create the folders too)) and place the package statement at the beginning of a class. I will make a short stop here. I noticed that all people generate their classes, but not all of them specify implemented interfaces and extended class. Surely, you can generate the class and write the extends and implements part afterwards, but it involves moving the cursor, writing and eventually generating abstract or implemented methods. I found it much easier to press ALT + E (extend) to add extended class and ALT + A (add interface) to add interfaces in the new class wizard. My class will then come out with empty overridden methods and correct imports. If you look at the Source menu you can find more "Generate" commands. But none of them is so valuable and useful as Eclipse templates. They are the true gem in my daily work and it is pity they are hidden out of sight. And they are hidden well. What are they and how to get them? Templates serve as a shorthand for a snippet of code. You type in the magical word and it will be transformed into the snippet. Some examples: Type sysout and press CTRL + SPACE (the autocompletion) and it will be automagically changed to System.out.println(); with the caret waiting right in the middle between the parenthesizes. While we are here, let's explore the next interesting feature. Type "for" and press CTRL + SPACE to change it to a skeleton of a for loop. The for template is a showcase of templates' power. Notice the blue boxes around some of the commands. They represent the caret stop and you can move between them using the TAB key. Now, with the caret on "iterator", type the name of the variable representing the iterator. Its name will be changed in the whole loop as you type (the occurrences are marked with a light blue background). Now just two more TABs to change the collection variable and the type. Noticed the green line waiting in the empty line? It marks the position where the caret will jump when Enter key is pressed. So after changing the variable type you can just press Enter and the caret will jump to the empty line. When you use autocompletion the green marker is always somewhere around, waiting for you to press Enter. Every particular template is closely bound to editor. Each editor has its own defined set of templates, which are applicable only in that editor type. It is quite logical that the sysout template will not work in JSP editor. Furthermore, each template is applicable only within the specified context of the particular editor. There are two contexts in the Java editor for example, Java and Javadoc. To see list of all templates open Window -> Preferences and type templates into the search box. You will get a list of all editors and their respective template settings. Your list may vary from my list, because it depends on installed plugins. I encourage you to walk through the list to see what predefined templates are available. Not all of them are useful, but you need to see it, because what does not work for me might work for you. The true and real power of templates lies in custom templates, but I will leave this topic for the next week article. Apart from the fact, that it can expand templates, CTR + SPACE has few more interesting uses. It is an autocompletion shortcut and it can complete the names of variables or methods and in fact, it is its most obligate and the most famous usage. But it has some more surprises to offer. If you get used to it, you will be hitting it often, even in situations where there is obviously nothing to autocomplete. Or is it? Guess what is on the picture above? It is eclipse trying to autocomplete the name of a variable. It is pity it cannot read my mind. I often find myself hitting the shortcut in the middle of the string ever wondering why it doesn't complete the word. Never can remember the signature of a method you want to override? Never mind, hit CTRL + SPACE and you will get a list. It can assist you in private method creation, and it can guess what to complete even from the upper case letters. Warning: Using autocompletion and templates can lead to uncontrolled ctrl + space hitting, surprises and productivity boost.
February 22, 2008
by Tomas Kramar
· 102,780 Views
article thumbnail
Effective Eclipse: Shortcut Keys
The less you touch the mouse, the more code you can write. Below you will find a set of essential keyboard shortcuts that I love for Eclipse.
February 15, 2008
by Tomas Kramar
· 1,509,942 Views · 29 Likes
article thumbnail
Effective Eclipse: Setup Your Environment
Today, I was taught an important lesson. The lesson of effectiveness. I was attending a presentation, called "Python Django: Advanced web application in 40 minutes". The guy was a geek, he was writing the code in a very basic vim installation. I bet, that if he used something better (no offense, it was really basic installation and he was apparently no vim master) he could crack it in half the time. It was an "oh, I made a typo here" presentation. It was then, when I realized that you really need a good editor if you want to be productive. Choose your tool Just do it. Find what suits you best and use it. I found Eclipse. Basic setup The first thing you should do, is to set up your font. If you are using Windows, you are lucky, as the font looks probably good and is well readable. If you are using Ubuntu like me, you might have less luck. When I first started eclipse, I was stunned. The font was big and crappy. But not for too long. Open: Window->Preferences->General->Appearance->Color and Fonts->Basic->Text Font and change the font size to 8. Much better now. The font used is called Monospace, some people recommend Bitstream Vera Sans Mono. This is how it looked before and how it looks now. Before: After: I recommend lowering the font size for your whole desktop. You will be surprised how much more can you see now. You can improve the font rendering too. Don't be greedy Eclipse is running with very small memory by default, but there is really no reason to be greedy. Just give your toy what it needs. Fire up the text editor, open eclipse.ini and enter: -vmargs -Xms512M -Xmx1024M -XX:PermSize=128M -XX:MaxPermSize=256M The -Xms option specifies the minimum and -Xmx the maximum heap size. The same holds for PermSize and MaxPermSize. Heap is that part of memory, where all your objects live. PermGen means "Permanent Generation" and it is a part of memory where all permanent objects are stored. By permanent, I mean those, which are not going to be garbage collected (for example Strings, classes etc.). Here you can find a better explanation of what PermGen is. If you are running a linux box, you might experience OutOfMemoryError-s if you do not adjust memory size. The values provided above are only for example, you should enter the values appropriate to your RAM size. You can further tune the performance by providing additional arguments. In his article, Jim Bethancourt recommends using Throughput garbage collector (-XX:+UseParallelGC), Robi Sen recommends using CMS Collector (-XX:+UseConcMarkSweepGC) as more effective. Help, I am giving the crap all my memory and it still keeps OutOfMemoryErroring! The reason is that you are simply not giving it enough memory. But don't worry, you don't have to buy another memory module (well, unless you have 128MB RAM). It is possible that you have made a typo in eclipse.ini, or maybe you used wrong eclipse.ini or maybe it simply doesn't work. I cannot tell you how to fix it, but I can tell how much memory are you giving it. Open Window->Preferences->General and check the "Show heap status" checkbox. You should now see the memory status in the bottom right corner. If you see values which correspond to the values you entered, everything should be fine. Set it up You should really take a time to walk through all the options under Window -> Preferences and customize your eclipse installation. I am going to list few ba General Always run in background: when eclipse is doing something time consuming, it will bother you with a modal popup window showing the progress of a task. I used to dismiss the popup with "Run in background" button. I am usually not interested in watching the lazy progressbar. If you enable this option eclipse will no longer bother you, and all tasks will run in background by default. There is nothing worse than breaking your workflow with messages: Hey I am building, can you see? Appearance: You can set various font related options here. If you are interested, you can change the position of tabs from top to bottom. Editors->File associations: if you have some exotic extension you can map it to the appropriate editor here. If you have xml file called myfile.exotic you can map .exotic extension to the xml editor. Editors->Text Editors -> Show line numbers: If you like, you can see line numbers. Very useful. Editors->Text Editors -> Spelling: Eclipse comes bundled with a spell checking turned on by default. This is a good idea and I really liked it, until I opened localized messages for my web application. Every word in my file was marked as misspelled, I was looking at an yellow sea of warnings, editor became quickly unresponsive as it wasn't able to handle hundreds of spelling errors. I had to turn this feature off, at least until some kind of ignore list is implemented or some good folk creates dictionary for my language. Java Java->Code style: Under Cleanup and Formatter are code formatting settings which are applied everytime the file is saved. If you tune it, it can save you much time. Java->Code style->Code templates: Here you can find and edit various templates. The only thing I do here is changing the "new Type" template to show my real name as author instead of my operating system username. Run/Debug Run/Debug->Launching: In previous Eclipse releases if you hit the run button, the last launched application was started. In Eclipse 3.3 this behavior changed a bit, and the selected resource gets launched. I found it annoying as I usually have only one runnable class. You can switch to the old style by choosing the right option under Launch Operation fieldset. I know I am repeating myself, but it is essential that you walk through the options and set it, such that it works with you, not against you.
February 8, 2008
by Tomas Kramar
· 49,610 Views
  • Previous
  • ...
  • 224
  • 225
  • 226
  • 227
  • 228
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×