Thursday 10 August 2017

LDAP Authentication using Spring

Spring LDAP Example:

In this code example we will learn about how to authenticate LDAP user through Spring. This code gives the details about using Spring LDAP for authenticating LDAP user.


1. First of all add Maven dependency to load Spring supported LDAP dependency.
<dependency>
       <groupId>org.springframework.ldap</groupId>
       <artifactId>spring-ldap-core</artifactId>
       <version>2.1.0.RELEASE</version>
</dependency>

2. Place Key store file in application (e.g. Keystore.jks) if it is required. I have saved this in folder to src/main/resources/keystore

3. Configure LDAP bean in spring context file.

 <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:ldap="http://www.springframework.org/schema/ldap"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans    
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/ldap
        http://www.springframework.org/schema/ldap/spring-ldap.xsd  ">
      
<bean id="poolingConnManager" class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager">
       <property name="defaultMaxPerRoute" value="20"/>
       <property name="maxTotal" value="20"/>
</bean>
      
<bean id="ldapUrl" class="java.lang.String">
       <constructor-arg value="${ldapUrl}"/>
</bean>

       <ldap:context-source url="${ldapUrl}"
              username="${ldapUserName}" password="${ldapPassword}" />

       <ldap:ldap-template id="ldapTemplate" />

       <bean id="ldapAuthenticator" class="com.ldap.LdapAuthenticator">
       <constructor-arg ref="ldapTemplate"/>
       </bean>
</beans>


4. Create new LdapAuthenticator Java class. This class contends the code for authenticating uses from LDAP server.

@Service("ldapAuthenticator")
public class LdapAuthenticator {

    private final static String KEY_STORE_FILE = "keystore/KeyStore.jks";
    private final static String KEY_STORE_PASSWORD = "changeit";
   
    private LdapTemplate ldapTemplate;
    private String base = "ou=dummy,ou=user,o=dummy";
   
    public LdapAuthenticator(){
    }

    public LdapAuthenticator(final LdapTemplate ldapTemplate) {
       this.ldapTemplate = ldapTemplate;
    }

    public boolean authenticateUser(String userName, String password) {
       boolean isUserAuthenticated = true;
try {

    String keyStorePath = getKeyStoreFilePath();
    System.setProperty("javax.net.ssl.trustStore", keyStorePath);
    System.setProperty("javax.net.ssl.trustStorePassword", KEY_STORE_PASSWORD);
   
           ldapTemplate.authenticate(query().base(base).where("uid").is(userName), password);
       } catch (final org.springframework.ldap.AuthenticationException e) {
           isUserAuthenticated = false;
           throw e;
       }
       return isUserAuthenticated;
    }

    private String getKeyStoreFilePath() {
       ClassLoader classLoader = getClass().getClassLoader();
       File file = new File(classLoader.getResource(KEY_STORE_FILE).getFile());
       return file.getAbsolutePath();
    }
}



5. Create Java Main class to call created method here and to validate LDAP user by passing username and password.

@Service("ldapUserAuthService")
public class LDAPUserAuthService {

@Autowired
private LdapAuthenticator ldapAuthenticator;

public void validateLDAPUser() { 

   boolean isUserValid = false;
   isUserValid = ldapAuthenticator.authenticateUser(“ldap_test”, “123”);
   System.out.println(“Is user authenticated: “+isUserValid);
}


}

Wednesday 22 February 2017

Merging PDF files in Java Using Apache PDFBox

The codes below illustrate how to merge all PDF files and create new one.

We will user Apache PDFBox with Java to merge all PDF files and create new one. To use Apache PDFBox we need to download required jar or add dependency if using Maven build tool.
Here we will add dependency in project POM.xml file.

1. Add Maven dependency for Apache PDFBox.
<dependency>
              <groupId>org.apache.pdfbox</groupId>
              <artifactId>pdfbox</artifactId>
              <version>2.0.4</version>
</dependency>

2. code:

import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;

public class PDFMerger {

    public static void main(String[] args){
       File file1 = new File("D:\\pdf\\filePDF1.pdf");
       File file2 = new File("D:\\pdf\\filePDF2.pdf");
       File file3 = new File("D:\\pdf\\filePDF2.pdf");
      
       File[] pdfFiles = {file1,file2,file3};
      
       PDDocument pdDocument = null;
       PDFMergerUtility pdfMergerUtil = new PDFMergerUtility();
      
       try {
           for (File pdf : pdfFiles) {
              PDDocument pdDoc = null;
              try {
                  if(null == pdDocument){
                     pdDocument = PDDocument.load(pdf);
                  }else{
                     pdDoc = PDDocument.load(pdf);
                     pdfMergerUtil.appendDocument(pdDocument, pdDoc);
                  }
              } catch (InvalidPasswordException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  e.printStackTrace();
              } finally {
                  if (pdDoc != null) {
                     pdDoc.close();
                  }
              }
           }
           System.out.println("PDF merging done....");
           pdDocument.save("D:\\pdf\\merged.pdf");
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           try {
              if (pdDocument != null) {
                  pdDocument.close();
              }
           } catch (IOException ioe) {
              ioe.printStackTrace();
           }
       }
    }
   

}