Getting started with IntelliJ IDEA Live Templates

posted by Roberto Cortez on
tags: , ,

Do you find yourself writing the same code over and over again? Maybe you’re already familiar with IntelliJ Live Templates feature. If that’s the case don’t go away. I’m going to demonstrate how to use them, but also the most interesting part is how to create your own Live Templates that can help you on your everyday coding.

For those not familiar with Live Templates, this feature allows you to quickly insert code fragments in your source code files and have the ability to replace or auto-complete sections of the template based on the current code context. IntelliJ already has a lot of templates that you can use right away after installing the IDE. You can have a look into the templates by using the shortcut CTRL+J/CMD+J:

Live Templates Popup

You get a list of the Live Templates that can be applied in the current context. The context is related with the file type you are editing (Java, SQL, XML, HTML, etc.), and also with the section itself (inside a method, field declaration, in the comments, etc). Let’s try one of the Live Templates I use the most, iterate an array. Did you notice the abbreviation on the left side of the Live Template popup? You can use it instead of using the popup shortcut. Just type iter followed by TAB key (do it inside the main method):

Iteration Expansion

The Live Template gets expanded to the Java 5 for each loop and IntelliJ suggests you the args array from the main method in the iteration plus the element type being iterated. You can pick other arrays available in the context and the code will automatically adjust to your choice (look at the red square around the args, it can auto complete to other arrays using CTRL+SPACE). Pretty cool!

Other notable Live Templates that I find pretty useful:

AbbreviationGenerated Code
psvmpublic static void main(String[] args) {}
psfspublic static final String
psfpublic static final
soutSystem.out.println();
soutvSystem.out.println("var = " + $var);
StString
ifnif ($var == null) {}
innif ($var != null) {}

Try to explore others that suit your programming style. Remember, Live Templates change with the file type you are editing. If you type udp in a SQL file and press TAB the abbreviation gets expanded to update set = where ;.

The real power is IntelliJ ability to create and customise your own code fragments. Lacking ideas? How about List<String> strings = new ArrayList<String>();? You type that a lot right? Well, maybe not with the String type, but that’s just an example. We’re going to create a Live Template for it where you can pick the type of the elements in the List. Go to IntelliJ Settings CTRL+ALT+S/CMD+, and search for Live Templates. You should get the following screen:

Live Templates Settings

We can now add a new Live Template by pressing the + on the right upper corner of the screen. We now need to add an abbreviation, a description, the template text itself and pick the applicable contexts.

PropertyValue
Abbreviationls
DescriptionList
Template TextList<$TYPE$> $VAR$ = new ArrayList<$TYPE$>();
ApplicableJava: statement, declaration

Add Live Template

The $TYPE$ and $VAR$ are variables that you can replace on the Live Template generation using IntelliJ pre-defined functions. Go to Edit Variables screen and you should get a screen like this:

Edit variables Live Template

So expectedType() replaces the $TYPE$ variable with a class type with the default value of String and suggestVariableName() replace the $VAR$ variable with an auto suggestion for the variable name where the default value is list. Take a look into IntelliJ help and see which other predefined functions are available for you to use. You can even use Groovy code!

Now you can type ls in the editor and expand it with TAB. You will get:

List Live Template

You can auto-complete and replace String by another type. Notice how the rest of the template adjusts to your pick:

List Live Template Edit

Note: If you’re using Java 7 or higher you can get rid of the generic type declaration on the right hand side of the template. I’m still working in a couple of projects that use Java 6, so I need it this way.

Now you just have to think on the code you type all the time and convert it to a Live Template and save precious time typing it! How about a template to create the Log instance to perform logging? You’re also going to need template log methods like sout to output log.info(""), log.error("") and so on. Try them out!

Feel free to share your Live Templates :)

Share with others!
  • Twitter
  • Facebook
  • LinkedIn
  • Google Plus
  • Reddit
  • Add to favorites
  • Email
  • RSS

Custom Principal and LoginModule for Wildfly

posted by Roberto Cortez on

Did you ever had the need to implement your own custom JAAS Principal and LoginModule for you JEE application? There are a couple of reasons for it. I’ve done it in the following cases:

  • Authenticate the user using different strategies.
  • Have additional user information on the Principal object.
  • Share user information between applications using the Principal object.

Maybe you have your own specific reason, it doesn’t matter. Today’s post will guide you on how to do it for Wildfly. There are a few articles on the topic, but each of them deal with a different aspect of the problem. I got motivated to write this post to aggregate all the steps in a single article, including the Arquillian test.

Wildfly uses PicketBox for Java Application Security and already implements some handy classes to take care of the authentication of the user for you. Have a look into UsersRolesLoginModule, DatabaseServerLoginModule, LdapUsersLoginModule, BaseCertLoginModule and so on. Let’s start by creating a Maven project with the following dependency:

Next, just create a CustomPrincipal and a CustomLoginModule classes:

Note that we’re extending the org.jboss.security.SimplePrincipal present in PicketBox, but you can also implement java.security.Principal instead.

Here again we’re extending a PicketBox class, org.jboss.security.auth.spi.UsersRolesLoginModule. You can code your own login module by implementing javax.security.auth.spi.LoginModule, but I recommend to extend one of the PicketBox classes, since they already have a lot of the behaviour that you will need. org.jboss.security.auth.spi.UsersRolesLoginModule is a very simple login module that authenticates an user by matching his login and password to a file. You shouldn’t use it for production applications, but it’s very handy for prototypes.

CustomLoginModule is also overriding two methods. These are needed to access our CustomPrincipal in a JEE application. The login() method as the name says is called when the user is performing the login action, so in here we create our CustomPrincipal object. On the other hand, the getIdentity() method is called to return the Principal that corresponds to the user primary identity, so we return our own instance if the login was successful.

Ok, great. How do we test it now? We use Arquillian, JUnit and HttpUnit. Start by adding the needed Maven dependencies (these are all the project dependencies):

Note that we also included the javaee-api 7 dependency. Next, we’re creating a simple EJB to access our CustomPrincipal and a Servlet to perform the authentication:

Now the Servlet:

I think the code is self-explanatory, but we still need to wire everything together. The way we configure our login module to be used on Wildfly and on our application is by using Security Domains. You can add a Security Domain by hand using the standalone/configuration/standalone.xml and domain/configuration/domain.xml files on the Wildfly installation folder, but we’re going to do something more interesting.

Using the Command Line Interface (CLI), is really easy to make changes to the server configuration without modifying any XML. This also allows you to setup a test environment and clean up your changes in the end. To achieve that, create the following files:

jboss-add-login-module.cli

As you probably have guessed, jboss-add-login-module.cli contains the CLI commands to add our Security Domain to the Wildfly instance. We first add the Security Domain and then assign the login modules to the domain. Both commands should be able to be executed as a single command, but for some reason I was getting an error so I had to split them apart. The configuration is not available on the server unless you perform a reload command. For the login module, please note the FQN of our CustomLoginModule associated with the configuration. That’s how we wire the custom login module to the Security Domain. The configuration also references two other files: user.properties and roles.properties that are used to perform the user credential verification and load the user roles. Here are examples for both files:

user.properties

Define all valid usernames and their corresponding passwords.

roles.properties

Define the sets of roles for valid usernames.

We still need the CLI commands to remove the Security Domain at the cleanup phase:

jboss-remove-login-module.cli

Almost done? Not yet! We still need to associate our Security Domain to our JEE application so our custom code runs when we perform authentication or execute Principal related behaviour. We need the following files now:

jboss-web.xml

The previous file sets the Security Domain into Servlets.

jboss-ejb3.xml

This file sets the Security Domain in EJB’s.

Uff! Now we’re finally ready to see some action! We required a bit of setup to have this example working! Here is the test class:

That’s it! Now your servlet login method will authenticate using your custom login module and methods like getUserPrincipal() from the servlet request or getCallerPrincipal() from the EJBContext will return the CustomPrincipal instance.

Fire up a Wildfly instance and run the test using mvm test or just use your favourite IDE.

A few problems:

  • It should be possible to add the security domain using only one single CLI command, but for some reason I was getting an erro. I need to have a better look into this.
  • I couldn’t find a way to run code before and after the Arquillian deployment, so the code to add the Security Domain is inside the deployment method. I’ll try to find a way to do it.

If you want additional information, please check the following references:

If you’re too lazy to write the code on your own or just want a working sample, you can download it here. Enjoy!

Share with others!
  • Twitter
  • Facebook
  • LinkedIn
  • Google Plus
  • Reddit
  • Add to favorites
  • Email
  • RSS

First Coimbra JUG meeting – The new Java 8 Features

posted by Roberto Cortez on

Last Thursday, 19 December 2013, the first ever meeting of Coimbra JUG was held on the Department of Informatics Engineering of the University of Coimbra, in Portugal. I couldn’t be more proud, more than 50 people attended the event.

After a quick intro to the JUG by myself, explaining the JUG objective and purposes, we had Samuel Santos from PT.JUG to share some of his experience running and managing the biggest JUG in Portugal.

The highlight of the meeting was the my talk about the new features in Java 8, especially lambdas. I think that most of the people enjoyed it, but maybe it was not that interesting for the folks that already use lambdas or equivalents on other languages. Also a lesson learned for me.

If you’re curious, here are the materials (in portuguese):
Presentation
Code
YouTube Channel

You can find more photos of the event on our Meetup page. We also have a few videos that I’m uploading right now. I’ll update the post when I’m done.

A special thanks to Jetbrains for giving away 2 free licenses of IntelliJ 13 to raffle among the participants. Congratulations to the lucky winners of Math.random(), Hugo Lopes and Luis Rosa.

Feel free to comment :)

Share with others!
  • Twitter
  • Facebook
  • LinkedIn
  • Google Plus
  • Reddit
  • Add to favorites
  • Email
  • RSS

Hi Everyone!

posted by Roberto Cortez on
tags:

Hi Everyone!

Welcome to my blog, and thank you for the visit. Please take some time to read my About me page.

I have created this blog to share any Java related topic to anyone that may care. For me, it would be useful to improve my English and keep a record of stuff I work and do. I usually forget a lot of stuff!

Anyway… Enjoy!

Share with others!
  • Twitter
  • Facebook
  • LinkedIn
  • Google Plus
  • Reddit
  • Add to favorites
  • Email
  • RSS