Showing posts with label Core Java. Show all posts
Showing posts with label Core 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;
      
    
  
 }
}

Sunday, September 4, 2016

How to set a static response or property in class mediator in WSO2 ESB

WSO2 ESB provides us luxury to create a custom functionality in java as class mediator. In class mediator we can write our desired functionality in java class and that can be called from the ESB synapse file. We can pass some property from ESB file to class mediator and in a same way we can set some property in java class and that can be read from synapse file.

Here is an example in which I need to reply a static response to customer. However this can be done from many ways but I am choosing class mediator just to show how this can be done from class mediator.


 I want below static response to be shown in as actual response of the service. I have put this “StaticEmployeeDetails.xml” file in “XX\wso2esb-4.0.3\repository\conf\stub\StubXml\ StaticEmployeeDetails.xml” location.

Static XML Code:

<EmployeeDetails xmlns="http://shriwithjava.blogspot.co.nz/">
   <EmployeeData>
      <EmployeeId>201</EmployeeId>
      <EmployeeName>Shri</EmployeeName>
      <EmployeeAddress>Auckland</EmployeeAddress>
      <Department>IT</Department>
   </EmployeeData>
   <EmployeeData>
      <EmployeeId>202</EmployeeId>
      <EmployeeName>Bhajan</EmployeeName>
      <EmployeeAddress>Wellington</EmployeeAddress>
      <Department>IT</Department>
   </EmployeeData>
</EmployeeDetails>



Here is the Class mediator code which will be called from the wso2 Synapse file.

Class Mediator Code:

package org.wso2.custom;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

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

public class CustomMediator extends AbstractMediator {

                private static String Response = "StaticResponse";
                private static String ResponseXml = "";
                private static String FileName = "";
                private static String FilePath = "F:\\Shri Kant\\WSO2\\wso2esb-4.0.3\\repository\\conf\\stub\\StubXml\\";
                public boolean mediate(MessageContext context) {
                                // TODO Implement your mediation logic here
                                //FileName=context.getProperty("").toString();
                                FileName=(String)context.getProperty("FileName");
                                BufferedReader br = null;
                                try {

                                                String sCurrentLine;

                                                br = new BufferedReader(new FileReader(FilePath+FileName+".xml"));

                                                while ((sCurrentLine = br.readLine()) != null) {
                                                                ResponseXml+=               sCurrentLine;
                                                }
                                                context.setProperty(Response, ResponseXml);
                                               
                                                System.out.println(context.getSoapAction()+" : This is the SOAP Action");
                                                System.out.println(context.getConfiguration()+" : This is the getConfiguration");
                                                System.out.println(context.getMessageID()+" : This is the getMessageID");
                                                System.out.println(context.getTracingState()+" : This is the getTracingState");
                                                System.out.println(context.getWSAAction()+" : This is the getWSAAction");
                                                System.out.println(context.getWSAMessageID()+" : This is the getWSAMessageID");
                                                System.out.println(context.getClass()+" : This is the getClass");
                                                System.out.println(context.getContextEntries()+" : This is the getContextEntries");
                                                System.out.println(context.getEnvelope()+" : This is the getEnvelope");
                                                System.out.println(context.getEnvironment()+" : This is the getEnvironment");
                                                System.out.println(context.getFaultSequence()+" : This is the getFaultSequence");
                                                System.out.println(context.getFaultStack()+" : This is the getFaultStack");
                                                System.out.println(context.getPropertyKeySet()+" : This is the getPropertyKeySet");
                                                System.out.println(context.getServiceLog()+" : This is the getServiceLog");
                                                System.out.println(context.isDoingGET()+" : This is the isDoingGET");
                                                System.out.println(context.isDoingMTOM()+" : This is the isDoingMTOM");
                                                System.out.println(context.isDoingPOX()+" : This is the isDoingPOX");
                                                System.out.println(context.isDoingSWA()+" : This is the isDoingSWA");
                                                System.out.println(context.isFaultResponse()+" : This is the isFaultResponse");
                                                System.out.println(context.isSOAP11()+" : This is the isSOAP11");
                                                System.out.println(context.isResponse()+" : This is the isResponse");
                                               
                                } catch (IOException e) {
                                                e.printStackTrace();
                                } finally {
                                                Response="";
                                                try {
                                                                if (br != null){
                                                                                br.close();
                                                                               
                                                                }
                                                } catch (IOException ex) {
                                                                ex.printStackTrace();
                                                }
                                }
                               
                               
                                return true;
                }
}




  • ·         Different property has been used in above code just to show that what all we can set from class mediator and use it in our synapse file.
  • ·         Create ja jar file of this above code and place it in the “X\ wso2esb-4.0.3\repository\components\lib\CustomMediator.jar”
  • ·         Now we need to provide the reference of this class from the synapse.xml file

I am creating a service “MyCustomProxy”. You can see that I have used “<class name="org.wso2.custom.CustomMediator"/>” code to call the class mediator. I have also used the javascript function which will change the response from string to xml. “<property name="StaticResponse" action="set" expression="get-property('StaticResponse')"/>” is used to get response from the class mediator which will be read from the static xml file.

Synpse.xml:

<localEntry key="StaticServiceScript" src="file:repository/conf/stub/StaticTransformResponse.js"/>
               
<proxy name="MyCustomProxy" transports="http" startOnLoad="true" statistics="enable" trace="disable">
                <target inSequence="MyCustom_IN" outSequence="MyCustom_OUT" faultSequence="CommonFaultHandler"/>
                <publishWSDL key="MyCustom_wsdl"/>
</proxy>
<localEntry key="MyCustom_wsdl" src="file:repository/conf/employee/OverseaseEmployee.wsdl"/>
<sequence name="MyCustom_IN">
                <property name="FileName" value="StaticEmployeeDetails" action="set"/>     
                <class name="org.wso2.custom.CustomMediator"/>
                <property name="StaticResponse" action="set" expression="get-property('StaticResponse')"/>
                <script language="js" key="StaticServiceScript" function="sendStaticResponse"/>
                <property name="RESPONSE" value="true"/>
                <header name="To" action="remove"/>
                <send/>
                <drop/>
</sequence>    




Java Script Code:
I am using a java script code which will be called from synapse.xml file. This will create a string text to xml content.

StaticTransformResponse.js


<x><![CDATA[  

                function sendStaticResponse(mc) {
                var StaticResponse = new XML(mc.getProperty("StaticResponse"));
                                                mc.setPayloadXML(StaticResponse);
               
                  }
]]></x>




Just restart the server to reflect the changes and hit the “MyCustomProxy” service and you will get the desired response. If you want to change the static response just change the content of the “StaticEmployeeDetails.xml” file located inside of “wso2esb-4.0.3\repository\conf\stub\StubXml” and restart the server.


Above image shows all the parameter what we have set in out java class. Same things we can get it in synapse.xml file as per our requirement.

Wednesday, August 14, 2013

How To Use Sort Method Of Collections In Java



Collections contains the sort(List<T>) method, which is used to sort the specified list into ascending order, according to the natural ordering of its element.

Declaration :

declaration of method - java.util.Collections.sort() method.

public static <T extends Comparable<? super T>> void sort(List<T> list) 
     
Parameters :

list - Ihis is the list to be sorted.

Example :

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

package org.javaIsEasy.collectionPrograms;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class SortListExample {
 public static void main(String[] args) {
  ArrayList<String> programmingLanguageList=new ArrayList<String>();
  programmingLanguageList.add("PHP");
  programmingLanguageList.add(".NET");
  programmingLanguageList.add("C++");
  programmingLanguageList.add("JAVA");
  programmingLanguageList.add("PERL");
 
  System.out.println("Display List Before Sorting\n");
  Iterator<String> it=programmingLanguageList.iterator();
  while(it.hasNext())
  {
   System.out.println(it.next());
  }
  Collections.sort(programmingLanguageList);
 
  System.out.println("Display List After Sorting\n");
  Iterator<String> itSwapped=programmingLanguageList.iterator();
  while(itSwapped.hasNext())
  {
   System.out.println(itSwapped.next());
  }
 }
}

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

OUTPUT :

******************************************************************************
Display List Before Sorting

PHP
.NET
C++
JAVA
PERL
Display List After Sorting

.NET
C++
JAVA
PERL
PHP

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


How To Find Number Of Occurrence Of An Object In List



The frequency(Collection<?>, Object) method is used to get the number of occurrence of an elements in the specified collection.

Declaration
declaration of method -  java.util.Collections.frequency().

public static int frequency(Collection<?> c, Object o)

Parameters

Collection<?> c  -  Pass the object of collection in which to determine the frequency of o.

Object o  -  Pass the object whose frequency is to be determined.


Example :

*********************************************************************************
package org.javaIsEasy.collectionPrograms;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class FrequencyExample {
 public static void main(String[] args) {
  ArrayList<String> programmingLanguageList = new ArrayList<String>();
  programmingLanguageList.add("PHP");
  programmingLanguageList.add(".NET");
  programmingLanguageList.add("PERL");
  programmingLanguageList.add("JAVA");
  programmingLanguageList.add("PERL");
  programmingLanguageList.add("PYTHON");
  programmingLanguageList.add("PERL");

  System.out.println("Display List Of Programming Language\n");
 
  Iterator<String> it = programmingLanguageList.iterator();
 
  while (it.hasNext()) {
   System.out.println(it.next());
  }
 
  int occurrences_Of_PERL = Collections.frequency(programmingLanguageList, "PERL");

  System.out.println("Display occurrences of 'PERL'---->"+ occurrences_Of_PERL);
 }
}

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


OUTPUT :

*********************************************************************************
Display List Of Programming Language

PHP
.NET
PERL
JAVA
PERL
PYTHON
PERL
Display occurrences of 'PERL'---->3

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


How To Use Swapping Method Of Collections In Java



Collections has swap(List<?>, int, int)  method, which is used to swap the elements at the specified position in the specify list.


Declaration of the Method:

This is the declaration of the method  -  java.util.Collections.swap()


public static void swap(List<?> list,int i,int j)


Parameters:

List - Pass the object of the list in which swapping method is to be performed.
int i - Pass the index of the one element which is to be swapped.
int j - Pass the index of the one element which is to be swapped with given int i index.


Example :


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

package org.javaIsEasy.collectionPrograms;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class SwapListExample {

 public static void main(String[] args) {
  ArrayList<String> programmingLanguageList=new ArrayList<String>();
  programmingLanguageList.add("PHP");
  programmingLanguageList.add(".NET");
  programmingLanguageList.add("C++");
  programmingLanguageList.add("JAVA");
  programmingLanguageList.add("PERL");

  System.out.println("Display List Before Swapping\n");
  Iterator<String> it=programmingLanguageList.iterator();
  while(it.hasNext())
  {
   System.out.println(it.next());
  }
  Collections.swap(programmingLanguageList, 0, 3);

  System.out.println("Display List After Swapping\n");
  Iterator<String> itSwapped=programmingLanguageList.iterator();
  while(itSwapped.hasNext())
  {
   System.out.println(itSwapped.next());
  }
 }
}


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

Output :


*******************************************************************************
Display List Before Swapping

PHP
.NET
C++
JAVA
PERL
Display List After Swapping

JAVA
.NET
C++
PHP
PERL

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

How to Read Excel File in Java using "Apache Poi" API.


Apache POI is a powerful Java library to work with different Microsoft Office file formats such as Excel, Power point, Visio, MS Word etc.

Let's create a Excel file and insert some data into this file and give this file name as "JavaIsEasy.xls".



Now we need to add library files to execute this program, as follows.


  • poi-3.7-beta1
  • poi-3.8-beta4-20110826
  • poi-ooxml-3.5-beta5


Add above jar in eclipse.





Now create a java class named as "ReadExcelFile.java".


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


import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadExcelFile {
 
  public static void main(String[] args) throws IOException {
      String fname = "C:/DATA/Software/LIFERAY/liferay data/Blogs Material/Core Java/JavaIsEasy.xls"; 
     //********************************************************************
      
      
      InputStream inp = new FileInputStream(fname);
      String fileExtn = GetFileExtension(fname);
      Workbook wb_xssf; 
      Workbook wb_hssf; 
      Sheet sheet = null; // sheet can be used as common for XSSF and HSSFWorkBook
      if (fileExtn.equalsIgnoreCase("xlsx"))
      {
        wb_xssf = new XSSFWorkbook(fname);
       log("xlsx="+wb_xssf.getSheetName(0));
       sheet = wb_xssf.getSheetAt(0);
      }
      if (fileExtn.equalsIgnoreCase("xls"))
      {
   POIFSFileSystem fs = new POIFSFileSystem(inp);
       wb_hssf = new HSSFWorkbook(fs);
       log("xls="+wb_hssf.getSheetName(0));
       sheet = wb_hssf.getSheetAt(0);
      }
      Iterator rows = sheet.rowIterator(); // Now we have rows ready fromthe sheet
      
   while (rows.hasNext()) 
       { 
           Row row = (Row) rows.next();
           log("row#="+row.getRowNum()+"");
           log("**********************");
    //log(row.getPhysicalNumberOfCells()+"");
    Iterator cells = row.cellIterator();
    String cellValue=null;
    while (cells.hasNext())
    {
        Cell cell = (Cell) cells.next();
     
     switch ( cell.getCellType() ) 
     {
     case Cell.CELL_TYPE_STRING:
         log(cell.getRichStringCellValue().getString());
         cellValue=cell.getRichStringCellValue().getString();
     break;
     case Cell.CELL_TYPE_NUMERIC:
           if(DateUtil.isCellDateFormatted(cell)) {
             log(cell.getDateCellValue()+"");
             cellValue=cell.getDateCellValue().toString();
           } else {
             System.out.println(cell.getNumericCellValue());
             cellValue=String.valueOf(cell.getNumericCellValue());
           }
           break;
     case Cell.CELL_TYPE_BOOLEAN:
           log(cell.getBooleanCellValue()+"");
           cellValue=cell.getBooleanCellValue()+"";
           break;
         case Cell.CELL_TYPE_FORMULA:
           log(cell.getCellFormula());
           cellValue=cell.getCellFormula();
           break;
     default:
     }
   
    
    }
       }
   inp.close();
  } 
  
  private static void log(String message)
  {
          System.out.println(message);
  }
  private static String GetFileExtension(String fname2)
  {
      String fileName = fname2;
      String fname="";
      String ext="";
      int mid= fileName.lastIndexOf(".");
      fname=fileName.substring(0,mid);
      ext=fileName.substring(mid+1,fileName.length());
      return ext;
  }
}



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

Now execute this program.

Output:-

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

xls=Sheet1
row#=0
**********************
Programming Language
Projects Done
Last Used

*
*
*
row#=4
**********************
PHP
0.0
Not Used

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

What is the use of Static Import?



Static Import is a new feature added in Java 5 specification.

let's first know, why do we use "import".
If we write as mentioned below

import form.ArtworkForm;

It gives access to use class 'ArtworkForm' inside whole program without using package reference.
'form' is a name of package here.

We can create any object of this class..
ArtworkForm obj=new ArtworkForm();

If we use * after package name in import statement, then it will give you access to use all classes
and it's method or members.

import form.*;

Now let's get into details with "Static import"...

double r = Math.cos(Math.PI * theta);

In the above line, we are using Math.cos and Math.PI. somewhere it looks awkward, to make it looks good
we can use as mentioned below.

import static java.lang.Math.PI;
import static java.lang.Math.cos;

now the code would be like this...

double r = cos(PI * theta); (It seems good)

Only advantage that I see is readability of the code. Instead of writing name of static class,
one can directly write the method or member variable name.

Static Class with an example

      To declare a Static class we need to have nested class, one single class cannot be declared static. To understand this let’s go through with the Top-level class or Outer Class and inner class.
Here we go…


Top-level classes:-
You declare a top-level class at the top level as a member of a package. Each top-level class corresponds to its own java file sporting the same name as the class name.

A top-level class is by definition already top-level, so there is no point in declaring it static; it is an error to do so. The compiler will detect and report this error.

Inner classes:-
You define an inner class within a top-level class.

Here we go with an example.

class MyStatic {
static class MyStaticInnerClass {
void innerClassObject() {
System.out.println("MyStaticInnerClass called");
}

}
}

class SecondClass {
static class MyStaticSecondInnerClass {
void secoundClassObject() {
System.out.println("MyStaticSecondInnerClass called");
}
}

public static void main(String[] args) {
MyStatic.MyStaticInnerClass objInnerClass = new MyStatic.MyStaticInnerClass();
SecondClass.MyStaticSecondInnerClass objSecondClass = new SecondClass.MyStaticSecondInnerClass();
objInnerClass.innerClassObject();
objSecondClass.secoundClassObject();
}
}


When we execute this code, we'll get below messages.

MyStaticInnerClass called
MyStaticSecondInnerClass called