Useful Linux SHELL Commands

  • wsimport = use wsimport to generated java files from the wsdl
    • Generate only .class files –
      /cygdrive/c/Program\ Files/Java/jdk1.8.0_60/bin/wsimport.exe -p com.rampal.abhi.generated IdentityManager.wsdl
    • Generate both .class and .java files –
      /cygdrive/c/Program\ Files/Java/jdk1.8.0_60/bin/wsimport.exe -keep -p com.rampal.abhi.generated IdentityManager.wsdl
    • Generate only .java files –
      /cygdrive/c/Program\ Files/Java/jdk1.8.0_60/bin/wsimport.exe -keep -Xnocompile -p com.rampal.abhi.generated IdentityManager.wsdl 
  • Importing a certificate into your keystore
    • Navigate to the bin directory of your jre e.g. …./jre1.6.0_20/win/bin
    • Type the below command
      keytool -import -file /u01/liferay-portal-6.1.1-ce-ga2/my-cert.crt -alias secureldapcert -keystore /u01/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/jre1.6.0_20/win/lib/security/cacerts
  • Remove all CVS directories from the directory tree
    • first run
    •  find . -name CVS -exec ls '{}' \;
    • then run
      find . -name CVS -exec rm -rf '{}' \;
  • Display the command history
    •  history 
  • Git check status
    • git status 
  • Git commit
    • git commit -m "your commit log message here" 
  • Git push
    • git push
  • Git add new file to repository
    • git add
    • Pressing tab after entering add makes git search for files that are worth adding and it presents them
  • Git diff file
    •  git diff 

      without any arguments

    • will compare each modified files in your file system against the files in the current checked-out branch (or) tag.
  • Git View config file
    •  vi .git/config 

      – this opens the config file in the vi editor

    • Use

      to exit the vi editor

    • You also need to press Esc button before before

      if you have edited the file.

  • Checkout a git repository
    •  git clone ssh://abhi@mygitserver:22/git/myproject
    • This will also create the folder for the project automatically.
  • Compare file
    •  git diff -- "src/main/your/path/to/"
  • Git Switch from master to a specific branch
    • Assuming master is already checked out
    •  git checkout your_branch_name
  • Git Create local branch
    • git checkout -b feature/versioning
  • Git push local branch to remote repo
    •  git push --set-upstream origin feature/versioning
  • Git list all remote branches
    •  git branch -a 
  • Create Tag
    •  git tag -a my_tag_name -m "release to SIT"
    •  git push origin my_tag_name 
  • Copy Git Repository
    • sudo cp -r source_repo_name.git dest_repo_name.git
    • cp -r means recursice copy (including hidden files)
  • Create Git Respository
    • sudo mkdir my_respository_name.git 
      cd my_repository_name.git 
      sudo git init --bare 
       sudo chown -R git my_repository_name.git
  • Git Merge branch with master
    • Make sure you checkout the master with
       git checkout master
    •  git merge your_branch_name 


Transaction Management with Spring Transactions

Spring Transactions library is useful for transaction management in your Spring-Hibernate application. A transaction is a single unit of work, in other words – a group of database interactions that should happen together. If any one of these ‘database interactions’ fail then the changes of the previous interactions in the set should be undone.

Transactions are usually (depending on granularity) declared at the service layer of your application. Service layer is the logical place where your transaction should start and a typical service layer method would call 1 or more DAO layer methods.

Spring @Transantional annotation allows the developer to declare a transaction. The typical usage of @Transactional annotation would look like below:

public class ApplicationServiceImpl implements ApplicationService {

    private static final Logger logger = Logger.getLogger(ApplicationServiceImpl.class);

    @Autowired private ApplicationDao applicationDao;

    @Autowired private QueueDao queueDao;

    @Autowired private UserDao userDao;

    public void saveApplication(Application app) throws Exception {"saving app");

Important to remember while using @Transactional is to define the condition for rollback. It is a common to incorrectly assume that because you’ve used @Transactional, Spring will take care of rolling back the whole transaction if something fails. This is not true. Spring only rolls back the transaction if your method throws an unchecked transaction i.e. Runtime Exception. It is much better practice to use the rollbackFor attribute instead. The rollbackFor attribute tells Spring what other situation (in addition to a runtime exception) to rollback for. In the example below I specify that transaction should be rolled back if any exception is thrown using attribute rollbackFor=Exception.class.

public class ApplicationServiceImpl implements ApplicationService {
private static final Logger logger = Logger.getLogger(ApplicationServiceImpl.class);
@Autowired private ApplicationDao applicationDao;

    @Autowired private QueueDao queueDao;

    @Autowired private UserDao userDao;

    public void saveApplication(Application app) throws Exception {"saving app");

In addition to above, one way to ensure that DAO methods are always part of an existing transaction initiated at the service layer is to use propagation = Propagation.MANDATORY attribute in your DAO method. If all your transactions are initiated at the service layer it would be good idea of put this attribute on all your DAO methods. With this annotation in place, whenever a DAO method is called without the caller service starting a transaction, you would get an exception stating that no active transactions existed when method was invoked.

public class ApplicationDaoImpl implements ApplicationDao {

    private static final Logger logger = Logger.getLogger(ApplicationDaoImpl.class);

    @Autowired private SessionFactory sessionFactory;

    @Transactional(propagation = Propagation.MANDATORY)
    public void saveApplication(Application app) throws Exception {
        Session session = sessionFactory.getCurrentSession();;

Spring Security customising method level authorization

If you’ve used Spring Security before you’ve probably used @Secured or @PreAuthorize annotations to enable method level security. These annotations are specifically useful for preventing your web applications being attacked by malicious users. Method level security makes sure that only authorized users can execute the specific method.

Depending upon the specific problem you can either use @Secured

void updateUser(){



Or you can use @PreAuthorize

@PreAuthorize("hasRole('ADMIN', 'ROLE_DBA', 'ROLE_SUPER_ADMIN')")
void updateUser(User user){


However, the limitation with the above annotations is that rely on GrantedAuthorities of the in session user. In other words, you are limited to the just the roles of the user to control the access to a specific method.

What about when you want to use another attribute, lets says a STATUS determined by an external service?

Or perhaps you have there is a reasonable amount to logic involved before deciding a particular user has access to a specific controller level method of your Spring app?

Under such circumstances you can leverage the ability to call custom methods through the @PreAuthorize annotation.  You can create a custom AccessManager spring managed bean (or something else suitably named for your app)


public class AccessManager{ 

	MyThirdPartyService myThirdPartyService;

	public boolean hasAccess(Authentication authentication, String... statusesNotAllowed) {
	//Complex logic can be performed here.
	//1. Access user's data with the authentication object
	//2. Access third party service to access data not available (or shouldn't be part of) in the session
	//3. statusesNotAllowed an example paramter, can have more or less


The AccessManager.hasAccess() method can be called in the @PreAuthorize annotation anywhere in your application. Only when AccessManager.hasAccess method returns true with the parameters specified in the annotation, the updateUser method would get executed.

@PreAuthorize("@accessManager.hasAccess(authentication, {'CANCELLED', 'BLOCKED', 'TERMINATED'})")
public String updateUser(User user){


Spring LDAP Authentication

What is LDAP? LDAP stands for Lightweight Directory Access Protocol. It’s designed to query and interact with directory data. As most enterprises use Microsoft directory service provider called Active Directory or AD, LDAP is commonly used to ‘talk’ to an Active Directory.

Developers tend to be confused about the difference between AD and LDAP. In short, AD is a database and LDAP is a protocol used to talk to an AD database.

The Java JNDI API can also be used for LDAP programming. If you’ve used JNDI API you may realize that it requires a lot more boilerplate code for even for the most simple tasks. Using Spring LDAP template on the other hand is a much more efficient way of implementing all of your LDAP related functionality.

How to use Spring-ldap? Before you write any code, you will need to import the following Spring Framework jars into your Java project. These are:

  • spring-ldap-core.jar
  • spring-core.jar and
  • spring-beans.jar

After importing the above jars, you need to create the ldapTemplate bean in spring context file. For example, I declared my ldapTemplate in the context xml as below.

<bean id="contextSource" class="">
 <property name="url" value="ldap://" />
 <property name="base" value="dc=your,dc=base,dc=dn" />
 <property name="userDn" value="${ad.username}" />
 <property name="password" value="${ad.password}" />
 <property name="referral" value="follow" />

 <bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
 <constructor-arg ref="contextSource" />

url: the url property should be either the IP address or the URL of the Active Directory you’re using. Please make sure that you use port 689 in production. Port 689 ensures communication through LDAPS protocol which is more secure than standard LDAP. You will need to import the certificate of the Active Directory you are connecting to into your java trust store.

After you have correctly set the above properties, you will need to inject the ldapTemplate bean in your java class. In the example below I use the Spring @Autowired annotation to inject the bean into my controller class.

@Autowired LDAPTemplte ldapTemplate;

Once, you’ve injected the bean, you can finally write the java code to enable LDAP Authentication. In the snippet below I write a simple method called authenticate which authenticates a user if the correct username and password combination is supplied.

private boolean authenticate(String username, String password){
 AndFilter filter = new AndFilter();
 filter.and(new EqualsFilter("sAMAccountName", username));
 boolean authenticated = ldapTemplate.authenticate("", filter.toString(), password);
 return authenticated;

The above piece of code would work for you if

  • the username supplied is always be correct and
  • the user is always be enabled

This is obviously not going to be the case in real life. So we need some additional information to be returned by this method. It would nice if the method could return information related to failed password count and locked out time. This would help you understand why a user is not authenticated.

We’ll use the user search function provided by spring-ldap to return the user’s attributes. We’ll add the below code to the function we just created above.

List<Object> templates ="", filter.toString(),new AttributesMapper() {
 public List<Object> mapFromAttributes(Attributes attrs) throws NamingException {
 List output = new ArrayList<>();
 return output;

List<Object> output = (List)templates.get(0);"Failed Login Count: "+output.get(0).toString());
if (output.get(1) == null || output.get(1) == 0){"Account is not locked");
} else {"Account is locked")

The above code snippet shows how we can use the sAMAccountName attribute to search for the user. The sAMAccountName usually corresponds to the username given to the user. There is a slight chance that this might not be the case for the active directory you’re using so please just verify that sAMAccountName does actually correspond to the username used by users for logging in.

Another thing to note here is that lockoutTime returns a null value if the account has never been locked before and 0 if it’s been locked before but is not locked currently.

Obviously, the method can modified to return the values of other attributes if needed.

Firewall config for Java Web App hosted on AWS EC2 Windows 2012 server

According to AWS documentation, creating the right security group configuration should be sufficient to allow for desired communication between your AWS EC2 instance and public internet. However, that’s not quite the case when you provision a Microsoft Windows 2012 VM as an EC2 instance.

I provisioned a windows 2012 EC2 instance and opened the following ports on it (Security Group Configuration Image below).

  • Port 80 for HTTP communication
  • Port 3389 for RDP communication
  • Port 443 for HTTPS communication
  • Port 8080 for TCP communication over port 8080. This was primarily because my Java app was a Liferay web app which comes bundled together with Tomcat 8 server and deploys to port 8080 by default. You can modify server.xml to change this port.

Configure Security Group of AWS EC2 Instance

After configuring the security group settings above and provisioning the EC2 instance, I needed to be able to access a very basic web app deployed on a Tomcat 8 server from the public internet. Navigating to http://localhost:8080 worked fine from within the Windows VM, however, if I accessed http://<vm-public- ip-address>:8080 from my web browser on the public internet I was not able to navigate to the app.

Turns out the only way to fix this is to modify the windows firewall rules on the VM in addition to the security group configurations above.

To modify the firewall rules on your windows server:

  1. Navigate to Control Panel -> System and Security -> Windows Firewall
  2. Click on Advanced Settings. This should open Windows Firewall with Advanced Security windows.
Windows 2012 Firewall Rules wizard

Windows 2012 Firewall Rules wizard

  • Click on Inbound Rules. This should display all the inbound rules for the firewall on the server.
  • Click on New Rule… This should open ‘New Inbound Rule Wizard’.
  • Select ‘Port’ radio button -> Click Next -> Enter 8080, 80, 443 in ‘Specific local ports’ -> Click Next -> Select ‘allow the connection’ -> Click Next -> Click Next -> Enter “Custom Inbound rules” under Name -> Click Finish.


  • If you try to access your app web app from the public network, you should be able to access it.

Disable SSL v3 on JBoss AS 7.1.1

SSLv3 is vulnerable to POODLE attacks. If you’re running your web application on JBoss AS 7.1, you need to disable SSLv3 in order to protect your web application from POODLE attacks. JBoss AS 7.1 does support more recent versions of TLS but it is still subject to a downgrade attack i.e. the attacker tricks the browser into connecting with SSL v3.

How to test if your JBoss Server still uses SSL v3

Before attempting to disable SSL v3, you should make sure that your application can indeed be accessed via SSL v3. In order to do that:

  1. Open Internet Explorer
  2. On the browser, under options, turn off TLS 1.2, TLS 1.1, TLS 1.0 and SSL 2.0 and only allow SSL v3 (In Internet Explorer this is under Internet Options & Advanced tab)
  3. Try to access the web page of your app deployed on JBoss AS 7.1 server.
    • If you can successfully navigate to the page that means SSL v3 is enabled.
    • If you cannot navigate to the page that means SSL v3 is disbaled. This means your web application is already protected against POODLE and you don’t need to do anything.
  4. Now turn TLS back on, try to access the web page again, you should be able to access the site.
Configure IE to only use SSL v3

Configure IE to only use SSL v3

How to disable SSL v3

To disable SSLv3 in JBoss you need to make sure SSLv3 is not listed in the list of protocols in standalone.xml on your JBoss server.

  1. Open standalone.xml file
    • It is located in the configuration folder of your JBoss App server directory.
  2. Modify https connector config.
    • Change the value of protocols attribute to TLSv1, TLSv1.1, TLSv1,2.
    • Notice below in the original config – protocol list only contains TLSv1 and protocol is changed to protocols in the modified xml.

Code snippet from original configuration file.

<connector name="https" protocol="HTTP/1.1" scheme="https" socket-binding="https" secure="true">
        <ssl name="foo-ssl" key-alias="foo" password="secret" certificate-key-file="your\file\path\to\the\certificate" protocol="TLSv1"/>

Modified code snippet.

<connector name="https" protocol="HTTP/1.1" scheme="https" socket-binding="https" secure="true">
        <ssl name="foo-ssl" key-alias="foo" password="secret" certificate-key-file="your\file\path\to\the\certificate" protocol="TLSv1,TLSv1.1,TLSv1.2"/>

Please note that if you’re running Java 6(JDK or JRE), you can only run TLS v1.0. TLSv1.1 and TLSv1.2 require Java 7 (minimum) to be running on your server.

Liferay LDAP Export to Active Directory disabled user bug.

Liferay 6.1 LDAP tool has a bug where the Liferay user is exported into Active Directory but is disabled by default. After much deliberation I found a workaround where we can write a hook to export users instead of using the out of the box tool. The hook uses a Model Listener on the User Model to look for changes to the user object i.e. the custom code is triggered when anything about the User object changes. The custom code uses the Java JNDI interface to create and or update users in Active Directory.

	public void onAfterCreate(User user) throws ModelListenerException {
		LDAPUtil util = new LDAPUtil();	

				try {"Attempting to create user: Screen Name: "
							+ user.getScreenName() + " :First Name: "
							+ user.getFirstName() + " : LastName: "
							+ user.getLastName() + " Email:"
							+ user.getEmailAddress()+ " OpenID: "
					+ user.getOpenId()+ " JobTitle: "
					+ user.getJobTitle());
							user.getPasswordUnencrypted(), user.getFirstName(),
							user.getLastName(), user.getEmailAddress(),
							user.getOpenId(), user.getJobTitle());

				} catch (Exception e) {
					throw new ModelListenerException(e);

 	public void createAdUser(String screenName, String password, String firstName, String lastName, String emailAddress, String openID, String jobTitle) {
		try {

			// Create the initial directory context
			LdapContext ctx = getLdapContext();
			String userDn = getUserDN(screenName);

			// Create attributes to be associated with the new user
			Attributes attrs = new BasicAttributes(true);

			// These are the mandatory attributes for a user object
			// Note that Win2K3 will automagically create a random
			// samAccountName if it is not present. (Win2K does not)
			List<String> objectClasses =  Arrays.asList(PropsUtil.get("your.object.classes").split(","));
			for (String objectClass: objectClasses){
				attrs.put("objectClass", objectClass);
			//attrs.put("samAccountName", screenName);
			attrs.put("cn", screenName);
			attrs.put("mail", emailAddress);
			// These are some optional (but useful) attributes
			attrs.put("sn", lastName);
			attrs.put("displayName", screenName);
			if (openID != null && openID.trim().length() > 0){"AD User: Setting emplyeeID to: "+openID);
				attrs.put("employeeID", openID);
			if (jobTitle != null && jobTitle.trim().length() > 0){"AD User: Setting emplyeeNumber to: "+openID);
				attrs.put("employeeNumber", jobTitle);
			//attrs.put("userPrincipalName", username);

			// Note that the user object must be created before the password
			// can be set. Therefore as the user is created with no
			// password, userAccountControl must be set to the following
			// otherwise the Win2K3 password filter will return error 53
			// unwilling to perform.
			attrs.put("userAccountControl", Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWD_NOTREQD + UF_PASSWORD_EXPIRED + UF_ACCOUNTDISABLE));"Creating AD user: " + userDn);
			// Create the context
			Context result = ctx.createSubcontext(userDn, attrs);"Created account: " + userDn);

			// Set password is a ldap modfy operation
			// and we'll update the userAccountControl
			// enabling the account and forcing the password to never expire
			if (password != null) {
				ModificationItem[] mods = new ModificationItem[2];

				//Replace the "unicdodePwd" attribute with a new value
				//Password must be both Unicode and a quoted string
				String newQuotedPassword = "\"" + password + "\"";
				byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");

				mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", newUnicodePassword));
				mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userAccountControl", Integer.toString(UF_NORMAL_ACCOUNT + UF_DONT_EXPIRE_PASSWD)));

				// Perform the update
				ctx.modifyAttributes(userDn, mods);"Successfully set password and updated userAccountControl");


		} catch (NamingException e) {"NamingException while creating AD user " + screenName);
			throw new RuntimeException(e);
		} catch (IOException e) {"IOException while creating AD user " + screenName);
			throw new RuntimeException(e);