Showing posts with label Advance Java. Show all posts
Showing posts with label Advance Java. Show all posts

Sunday, August 6, 2017

How to implement NTLM security in WSO2 ESB

Unfortunately, WSO2 does not provide any plugins or mediator directly to implement NTLM security. However, this can be done by using the custom mediator. You can write a java class with this security handler and call it from WSO2 container.

In order to write a Class mediator, you can follow this blog and put the custom jar into the WSO2 lib folder.  



package poc.ntlm;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;

public class NLTMSecurity {

 public static void main(String[] args) throws HttpException, IOException {
  System.out.println("started");
  String result = invokeService();
  System.out.println("output  : " + result);

 }

 public static String invokeService()
   throws HttpException, IOException {
  String responseString = null;
  try {
   HttpClient client = new HttpClient();

   String URL = "http://XXX.XXX.XXX/XX/XXX/2011/OrganizationData.svc/ListSet?$select=ListId,ListName,StateCode";
   GetMethod getMethod = new GetMethod(URL);
   NTCredentials credentials = new NTCredentials("USER_NAME", "PASSWORD", "HOST_NAME", "DOMAIN");
   client.getState().setCredentials(new AuthScope(null, -1, null),
     credentials);
   int status = client.executeMethod(getMethod);

   System.out.println("Status : " + status);

   responseString = getMethod.getResponseBodyAsString();

   System.out.println("responseString : " + responseString);

  } catch (Exception e) {
   System.out.println(e);
  }

  return responseString;

 }

}




You can set this response and the HTTP code in the WSO2 ESB container.



import org.apache.synapse.MessageContext;
import org.apache.synapse.mediators.AbstractMediator;


public class NTLMSecurityMediator extends AbstractMediator { 

 public boolean mediate(MessageContext context) { 

 context.setProperty("Response", responseString );
      
context.setProperty("HTTP_STATUS", status );      return true;
      
    
  
 }
}

Thursday, April 3, 2014

Spring tutorial 05- Initializing and injecting value in Bean property

To start this blog, lets understand the Beans.

The beans:
A Spring IoC container manages one or more beans. These beans are created using the configuration metadata that has been supplied to the container (typically in the form of XML <bean/> definitions). Beans are represented as beanDefintion objects which contains following meadata.



  • a package-qualified class name: typically this is the actual implementation class of the bean being defined.
  • bean behavioral configuration elements, which state how the bean should behave in the container (scope, lifecycle callbacks, and so forth).
  • references to other beans which are needed for the bean to do its work; these references are also called collaborators or dependencies.
  • other configuration settings to set in the newly created object. An example would be the number of connections to use in a bean that manages a connection pool, or the size limit of the pool.




In Spring, InitializingBean is a marker interface, which is used to initialize the bean.

  • For bean implemented InitializingBean, it will run afterPropertiesSet() after all bean properties have been set
  • For bean implemented DisposableBean, it will run destroy() after Spring container is released the bean.

Example :

In below example we can see, how property can be initialized.

Let's create a project say "SpringTutorial" now add the required jar support to spring, to add the jar  you can follow the Spring Tutorial 02 -My First 'Hello World' Program in Spring blog

Now create a package with the name of "org.javaIsEasy.springPropertyInitializationExample".
Create a java file in this package with the name of "Area.java".

Area.java
*******************************************************************************

package org.javaIsEasy.springPropertyInitializationExample;

public class Area {

private String areaOf;

 public String getAreaOf() {
 return areaOf;
}

public void setAreaOf(String areaOf) {
 this.areaOf = areaOf;
}

 public void calculateArea()
 {
  System.out.println(getAreaOf()+" Area Has been calculated");
 }
}

*******************************************************************************
Now create another file in the same folder with the name of "CallAreaApplication.java".

CallAreaApplication.java
*******************************************************************************

package org.javaIsEasy.springPropertyInitializationExample;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CallAreaApplication {
public static void main(String[] args) {


 ApplicationContext context=new ClassPathXmlApplicationContext("org/javaIsEasy/springPropertyInitializationExample/Beans.xml");
 Area area=(Area)context.getBean("area");
 area.calculateArea();
}
}

*******************************************************************************

Now at last one more file is need to be created in which we define beans, so let's create "Beans.xml" file in the same folder again.

Beans.xml 

*******************************************************************************

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="area" class="org.javaIsEasy.springPropertyInitializationExample.Area">
      <property name="areaOf" value="Rectangle"></property>
   </bean>

</beans>

*******************************************************************************

in the above xml file we have injecting the value to the "areaOf" object of the Area class, and giving the value of "Rectangle".

Structure of the project :




Lets run this program to get the result:

Output:

*******************************************************************************
Rectangle Area Has been calculated
*******************************************************************************

Spring Tutorial 04 - Write Spring Program Using ApplicationContext

Before starting program let's get into details of the 'ApplicationContext'.

What is ApplicationContext?

ApplicationContext is an interface for providing configuration information to an application. There are multiple classes provided by springframework that implements this interface and helps us use configuration information in applications.

The lowest level implementation of the IoC container is the BeanFactory, but it is recommended to use an ApplicationContext for your application. The ApplicationContext is a subclass of the BeanFactory interface so it has all the functionality a BeanFactory has and more. Unless you are writing an application that needs an extremely small memory footprint, BeanFactory shouldn't be used directly.




An ApplicationContext provides:


  • ApplicationContext provides all the method of the beanfactory, because it extends BeanFactory.
  • The ability to load file resources in a generic fashion. Inherited from the ResourceLoader interface.
  • The ability to publish events to registered listeners. Inherited from the ApplicationEventPublisher interface.
  • The ability to resolve messages, supporting internationalization. Inherited from the MessageSource interface.
  • Inheritance from a parent context. Definitions in a descendant context will always take priority. 

This means, for example, that a single parent context can be used by an entire web application, while each servlet has its own child context that is independent of that of any other servlet.

public interface ApplicationContext
extends ListableBeanFactory, HierarchicalBeanFactory, MessageSource, ApplicationEventPublisher, ResourcePatternResolver

Above interface is used in Spring.

The most commonly used ApplicationContext implementations are:

FileSystemXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor.

ClassPathXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.

WebXmlApplicationContext: This container loads the XML file with definitions of all beans from within a web application.



Let's create a program to understand the concept of ApplicationContext.

Create a java file with the name of 'Area' inside the package 'org.javaIsEasy.springApplicationContextExample' and copy below code.

Area.java
*******************************************************************************
package org.javaIsEasy.springApplicationContextExample;

public class Area {

 public void calculateArea()
 {
  System.out.println("Area Has been calculated");
 }
}

*******************************************************************************

Create a java file with the name of 'CallAreaApplication' inside the package 'org.javaIsEasy.springApplicationContextExample' and copy below code.

CallAreaApplication.java

*******************************************************************************
package org.javaIsEasy.springApplicationContextExample;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CallAreaApplication {
public static void main(String[] args) {


 ApplicationContext context=new ClassPathXmlApplicationContext("org/javaIsEasy/springApplicationContextExample/Beans.xml");
 Area area=(Area)context.getBean("area");
 area.calculateArea();
}
}

*******************************************************************************

Create a xml file with the name of 'Beans.xml' inside the package 'org.javaIsEasy.springApplicationContextExample' and copy below code.

Beans.xml

*******************************************************************************
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="area" class="org.javaIsEasy.springApplicationContextExample.Area">
      
   </bean>

</beans>

*******************************************************************************
Structure of the project.




Now let's run this program and what results comes. Open 'CallAreaApplication.java' file---> right click---> run as java application.

OUTPUT:
*******************************************************************************
Area Has been calculated
*******************************************************************************

Spring Tutorial 03 - Write Spring Program Using BeanFactory

Before using the the BeanFactory in our Spring tutorial, let's first look into details of the this.

        There are 2 important packeges in the Spring which provides Inversion of Control (alternately called Dependency Injection) features.The BeanFactory provides an advanced configuration mechanism capable of managing beans (objects) of any nature, using potentially any kind of storage facility.


  • org.springframework.beans
  • org.springframework.context


The BeanFactory is the actual container which instantiates, configures, and manages a number of beans. These beans typically collaborate with one another, and thus have dependencies between themselves. A BeanFactory is represented by the interface org.springframework.beans.factory.BeanFactory, for which there are multiple implementations. The most commonly used simple BeanFactory implementation is org.springframework.beans.factory.xml.XmlBeanFactory. We need to instantiated the object mannually, this can be achieved as mentioned below.




ApplicationContexts are a subclass of BeanFactory, and most users end up using XML variants of ApplicationContext


BeanFactory factory=new XmlBeanFactory(new FileSystemResource("Beans.xml"));


Let's understand above feature with the program.

Create a Java project with your desired name Let's say "springTutorial".

Add the required spring lib files, if you want to take reference, please follow Spring Tutorial 02 -My First 'Hello World' Program in Spring blog.

Create a package with name "org.javaIsEasy.springBeanFactoryExample".

Create a class with name of "Area.java".
Write below code in this file.
**********************************************************************
package org.javaIsEasy.springBeanFactoryExample;

public class Area {

 public void calculateArea()
 {
  System.out.println("Area Has been calculated");
 }
}


**********************************************************************

now create another class in the same package with name of "CallAreaApplication.java".
Write below code in this file.
**********************************************************************
package org.javaIsEasy.springBeanFactoryExample;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.FileSystemResource;

public class CallAreaApplication {
public static void main(String[] args) {

 BeanFactory factory=new XmlBeanFactory(new FileSystemResource("Beans.xml"));

 Area area=(Area)factory.getBean("area");
 area.calculateArea();
}
}

**********************************************************************

Now create a "Bean.xml" file, in which we write beans mapping. Put this file in the Root folder.
write below code in the Beans.xml file.

**********************************************************************

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="area" class="org.javaIsEasy.springBeanFactoryExample.Area">
      
   </bean>

</beans>
**********************************************************************

Structure of the project.




Now let's run this program and what results comes. Open 'CallAreaApplication.java' file---> right click---> run as java application.

Output:

**********************************************************************
17 Jun, 2013 11:21:59 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [C:\DATA\work\WorkSpace_Spring\SpringTutorial\Beans.xml]
Area Has been calculated

**********************************************************************

'Area Has been calculated' is printed in the output.

Wednesday, March 26, 2014

Spring Tutorial 02 - My First 'Hello World' Program in Spring

Before writing any program in spring, let’s first setup our Spring environment in eclipse.


Step 1 - Create Java Project:
The first step is to create a simple Java Project using Eclipse. Go to the option File -> New -> Project and select Java Project from the wizard list.







Now name your project as ‘SpringTutorial_02’ using the wizard window as follows:



The structure of the project would be like as follows.




Step 2 - Add Required Libraries:

Now we need to add the libraries of spring to give support of the spring in this project. Select the project ---> Right Click --->Property --->Java Build Path as follows.





Now add the spring libraries.



List of Libraries.


  • antlr-runtime-3.0.1
  • org.springframework.aop-3.1.0.M2
  • org.springframework.asm-3.1.0.M2
  • org.springframework.aspects-3.1.0.M2
  • org.springframework.beans-3.1.0.M2
  • org.springframework.context.support-3.1.0.M2
  • org.springframework.context-3.1.0.M2
  • org.springframework.core-3.1.0.M2
  • org.springframework.expression-3.1.0.M2
  • commons-logging-1.1.1

Step 3 - Create Source Files:


Now let’s create source files in this project. First we need to create a package called org.javaIsEasy.springTutorial. To do this, right click on src in package explorer section and follow the option : New -> Package. Next we will create HelloWorld.java and MainClass.java files under the org.javaIsEasy.springTutorial package.

HelloWorld.java


package org.javaIsEasy.springTutorial;

public class HelloWorld {
    private String message;

    public void setMessage(String message){
       this.message  = message;
    }

    public void getMessage(){
       System.out.println("Your Message : " + message);
    }
 }


MainClass.Java


package org.javaIsEasy.springTutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainClass {

 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext("org/javaIsEasy/springTutorial /Beans.xml");

  HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

  obj.getMessage();
 }
}

***********************************************************************************

Java files have been created now we need to create 

There are following two important points to note about the main program:


  • First step is to create application context where we used framework API ClassPathXmlApplicationContext(). This API loads beans configuration file and eventually based on the provided API, it takes care of creating and initializing all the objects ie. beans mentioned in the configuration file.
  • Second step is used to get required bean using getBean() method of the created context. This method uses bean ID to return a generic object which finally can be casted to actual object. Once you have object, you can use this object to call any class method.



Step 4 - Create Bean Configuration File:
You need to create a Bean Configuration xml file which would be created in org.javaIsEasy.springTutorial package.



We have given 'Beans.xml' to this configuration file. We can give any name to this file as we want to. Only the classpath and the name of this configuration file needs to be maintained which is being used in the java files. 

The Beans.xml is used to assign unique IDs to different beans and to control the creation of objects with different values without impacting any of the Spring source files. For example, using below file you can pass any value for "message" variable and so you can print different values of message without impacting HelloWorld.java and MainClass

After creating the Beans.xml file, our project structure would be as follows.




Beans.xml


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="helloWorld" class="org.javaIsEasy.springTutorial.HelloWorld">
       <property name="message" value="Java Is Easy !!"/>
   </bean>

</beans>


When Spring application gets loaded into the memory, Framework makes use of the above configuration file to create all the beans defined and assign them a unique ID as defined in <bean> tag. You can use <property> tag to pass the values of different variables used at the time of object creation.


Step 5 - Running the Program:
Let's run this program and see what result would be coming.




************************************************************************************************
OUTPUT : Your Message : Java Is Easy !!
************************************************************************************************


Congratulations, you have created your first Spring Application successfully. You can see the flexibility of above Spring application by changing the value of "message" property and keeping both the source files unchanged. Further, let us start doing something more interesting in next few chapters.