Pages

Monday, November 23, 2015

OIM 11g R2 SPML Client using JAX-WS

Step 1: down load jax-ws (jaxws-ri-2.2.8) jar file to convert wsdl to stub classes  and run the following command to get  the sub classes.

wsimport -keep -p com.thejavageek.client http://yourhostname:14000/spml-xsd/SPMLService?WSDL


Step 2:  create a client program in your package

import java.util.List;
import javax.xml.soap.SOAPException;

import javax.xml.ws.Binding;
import javax.xml.ws.BindingProvider;


import oracle.iam.wsschema.model.spmlv2custom.username.ValidateUsernameRequestType;
import oracle.iam.wsschema.model.spmlv2custom.username.ValidateUsernameResponseType;

public class TestOIMSPML
{
  public static void main(String args[])
    throws SOAPException
  {
 
   // WebServiceContext ctx=null;
   // SOAPFactory sf = SOAPFactory.newInstance();
   // SOAPMessageContext context = (SOAPMessageContext)(ctx.getMessageContext());
   //HeaderHandlerResolver hh =new HeaderHandlerResolver("xelsysadm","Password");
 
      SPMLService ss = new SPMLService();
   
 
       
    SPMLRequestPortType port = ss.getSPMLServiceProviderSoap();
 
    Binding binding = ((BindingProvider) port).getBinding();
    List handlers = binding.getHandlerChain();
    handlers.add(new HeaderHandlerResolver("xelsysadm","********"));
    binding.setHandlerChain(handlers);
 
 
 
 
  //  ctx.getMessageContext();
 
   
      ValidateUsernameRequestType validateUser = new ValidateUsernameRequestType();
       validateUser.setUsername("sbeynon");
     
        ValidateUsernameResponseType retValUser = port.spmlValidateUsernameRequest(validateUser);
      System.out.println("spml validate user =" + retValUser.isValid());
 
  }
}

Step 3: when you  try to execute the above program you will get an error like security header is missing, to avoid this error. you need to append the security header in your request, for this develop the following class,
this class will generate security header.

import java.util.Collections;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
public class HeaderHandlerResolver
  implements SOAPHandler
{
  String userid;
  String passowrd;
  SOAPHeader soapHeader = null;

  public HeaderHandlerResolver(String userid, String password)
  {
    this.userid = userid;
    this.passowrd = password;
  }

  public Set getHeaders()
  {
    return Collections.emptySet();
  }

  public boolean handleMessage(MessageContext pcontext)
  {
    try
    {

      SOAPMessageContext context = (SOAPMessageContext) pcontext;
      SOAPMessage message = context.getMessage();
      SOAPHeader header = message.getSOAPHeader();
      SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
      if (header == null)
      {
        header = envelope.addHeader();
      }
      QName qNameUserCredentials =
        new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security");
      SOAPHeaderElement userCredentials =
        header.addHeaderElement(qNameUserCredentials);
   
      QName qUsernameToken =
        new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "UsernameToken");
      SOAPHeaderElement UsernameToken =
        header.addHeaderElement(qUsernameToken);
      userCredentials.addChildElement(UsernameToken);

      QName qNameUsername = new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Username");
      SOAPHeaderElement username = header.addHeaderElement(qNameUsername);
      username.addTextNode(this.userid);
      QName qNamePassword =
        new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Password");
      SOAPHeaderElement password = header.addHeaderElement(qNamePassword);
      password.addTextNode(this.passowrd);

      UsernameToken.addChildElement(username);
      UsernameToken.addChildElement(password);

      message.saveChanges();
   
  System.out.println(message.getSOAPHeader().getTextContent());
   
   
             
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return true;
  }


  public boolean handleFault(MessageContext pContext)
  {
    return false;
  }

  public void close(MessageContext pContext)
  {
  }
}





Friday, December 10, 2010

webservics by using axis2 with eclipse

Introduction
Recently I was reading through SOA and I wanted to develop few services using Axis. Since I was already comfortable with eclipse as j2ee development IDE (I use eclipse 3.4 – Ganymede for development purposes). When I started with axis, I wanted to use eclipse for development of web-services too. I struggled couple of hours googling to find best way to write, debug, deploy and distribute web services.



I googled and finally I would an acceptable way to do development and debug. These are information I put together from my own experience and various sources from internet.

Before starting, I want to mention my development environment.


Development environment
Java – J2ee SDK 1.4.
Jre 1.5.
Eclipse 3.4 Ganymede.
Axis2 - 1.4


Create Web Service
For better clarity, I will take you through one service creation and one client creation using eclipse. For simplicity I will create a simple calculator service with 4 simple service functions.


· add
· divide
· substract
· multiply



Step 1: Create a dynamic web project.
File -> New -> Project ->








Press Finish and you have a new dynamic web project.


Step 2: Create a simple Calculator class.



package org.bpt.Services;

/**
*
* @author GOPI GOLLA
*
* Axis Service Sample.
*
*
*/

public class Calculator {

public double add(double arg1, double arg2){
return arg1 + arg2;
}

public double substract(double arg1, double arg2){
return arg1 - arg2;
}

public double multiply(double arg1, double arg2){
return arg1 * arg2;
}

public double divide(double arg1, double arg2){
if(arg2 != 0)
return arg1 / arg2;
else return -1;
}
}




Step 3: Create an axis service from this class.


Right click Calculator.java
New -> Other -> Web Service







Next



Click on the link and select Axis 2.







Click OK and click Next in Web service Dialog.












Now click on Start Server and wait for few seconds.
Press Next



Finish. You have created a new axis service, deployed it and started the server now.

Check Services



To check the deployed service, check the following URL in a browser.
http://localhost:8080/CalculatorService/services/listServices


You see the following screen with the newly created service listed.



To check whether service is working properly, check the following URLs


To see the service definition, click the following link.
http://localhost:8080/CalculatorService/services/Calculator?wsdl


Add Service:

http://localhost:8080/CalculatorService/services/Calculator/add?arg1=12&arg2=13



You see an xml file containing result as below. You can change the arguments to see the service working.




Substract Service

http://localhost:8080/CalculatorService/services/Calculator/substract?arg1=12&arg2=13


You see an xml file containing result as below. You can change the arguments to see the service working.



Multiply Service

http://localhost:8080/CalculatorService/services/Calculator/multiply?arg1=12&arg2=13

You see an xml file containing result as below. You can change the arguments to see the service working.



Divide Service

http://localhost:8080/CalculatorService/services/Calculator/divide?arg1=12&arg2=13


You see an xml file containing result as below. You can change the arguments to see the service working.




Cool and easy ..isn’t it?


Creating a Java Client for the web Service
Now we will create a Java client which used the services we created now. There are many ways to create clients and I will explain one of them.

File -> New -> Project -> Dynamic Web project










Click Finish and now you have a dynamic web project “CalculatorServiceClient”.
Now select on your Calculator.java file in CalculatorService project.

File -> New -> Other -> Web Service Client




Next



Set it to Axis 2.




Add service definition URL - http://localhost:8080/CalculatorService/services/Calculator?wsdl






Select Calculator client project




Next



Keep the default setting s and press finish. You see that new classes are created for the client.




Now we will write a simple console application which uses these generated classes to access the services – CalculatorServiceClient.java.


package org.bpt.services;

import org.apache.axis2.AxisFault;

public class CalculatorServiceClient {

public static void main(String[] args) {
try {
CalculatorStub stub = new CalculatorStub();
double val = add(stub, 12,13);
System.out.println("Got response from add service. result = " +val);
} catch (AxisFault e) {
e.printStackTrace();
}

}

/* fire and forget */
public static double add(CalculatorStub stub, double arg1, double arg2) {
try {
CalculatorStub.Add req = new CalculatorStub.Add();
req.setArg1(arg1);
req.setArg2(arg2);
CalculatorStub.AddResponse res = stub.add(req);

return res.get_return();
} catch (Exception e) {
e.printStackTrace();
System.err.println("\n\n\n");
}
return -1;
}


}


Run the application and you see the result in the console. Congratulations. You have created your first web service in eclipse. You are now ready to fly to the heights. All the best for a great fly.

webservices



Web services are a handy method of integrating independent systems. Apache Axis is one of the best free tools available for implementing and deploying web services, and also for implementing the web service clients.

In this article we will create a simple, but complete web service and a client for this service step-by-step. Article will be explanatory as much as possible to succeed you in implementing it yourself alone after completing this tutorial.

Prerequisites

* Must be familiar with Java
* Familiar with basics on a web server like Tomcat
* Some knowledge in configuring Axis will be an added advantage

System Configuration Requirements
We will be discussing the configuration in brief as our scope is mainly on web services. (If Axis already configured, jump to implementation). If you find any issues on the configuration part, you can refer to Apache Axis site for troubleshooting. (But if you can not solve it yourself do not worry, post the issue under the comments section in this article, and we’ll get back to you).

JDK installation
These examples have been tested on a machine with JDK 1.6 version.

Web Server
You must have a web server
installed; and we will be using Tomcat (5.5 version) web server. If you are not having one, better download Tomcat here{link} and install it yourself (it is quite easy to install Tomcat). Now your CATALINA_HOME environment variable should point to the Tomcat installation directory.

Apache Axis 1.4
Download Apache Axis 1.4 here{link}. Extract the downloaded file and you’ll find a folder named “axis” inside webapps folder.
%Axis_1.4_dir%\webapps\axis
Copy this “axis” folder into your web server’s webapps folder.
%CATALINA_HOME%\webapps

CLASS PATH
Now you must add following libraries into your CLASSPATH environment variable. All of these are available under %Axis_1.4_dir%\lib folder.

* activation.jar
* mail.jar
* axis.jar
* commons-discovery.jar
* commons-logging.jar
* jaxrpc.jar
* log4j-1.2.8.jar
* saaj.jar
* wsdl4j.jar

That’s all for configuring Axis 1.4 on your system, quite easy isn’t it? Let’s move on to the implementation part.

Implementation - web service and client
The implementation will consist of two parts. First we will implement web service part; a Calculator will be exposed as a web service. Next a client to use this Calculator web service will be implemented. (Client part starts from here).

Calculator Web Service
Implementing the web service consists of 7 steps. We will be explaining each step in detail.

1. Functionality provider
2. Web service’s interface
3. Java2WSDL - Generate WSDL file
4. WSDL2Java - Generate server side and client side classes for web service
5. Bind Web service with Functionality provider
6. Bundle required classes
7. Register web service with axis


Project structure
Before starting coding, we'll have a look at the project structure. We are using a separate folder for the project, called "WS-Sample". We will be creating source (.java) files under "WS-Sample\src" folder and storing generated class (.class) files under a "WS-Sample\classes" folder.



1. Functionality provider
First we need to write class with calculator functionality before exposing it as a web service. We have implemented it as a pretty complex high end calculator class, named SimpleCalculator and it's listed below. (It is just a pretty simple class with three methods). This class has no information related to a web service and has been written as a simple independent class. So in the time this class was written, no one has thought of any web service stuff. But we will expose this class as a web service. (Yes, what you guessed is correct. Later you can expose your existing Java classes as web services.)

package org.kamal.wssample;

public class SimpleCalculator {

public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
}


We'll compile above class using following command so that the generated .class file will reside in a folder named "classes" while preserving the package structure.

WS-Sample\src> javac -d ..\classes
org\kamal\wssample\SimpleCalculator.java


2. Web service’s interface
Now we should write an interface that defines the services that will be provided by our web service. We will expose only two methods through our service; add() and subtract() methods (although we can expose any number of services within one web service). We did choose only two methods to emphasize the fact that we can control which methods we expose. And we will write this class in a separate package; org.kamal.wssample.ws.

package org.kamal.wssample.ws;

public interface Calculator {
int add (int x, int y);
int subtract(int x, int y);
}


And compile using following command.

WS-Sample\src> javac -d ..\classes
org\kamal\wssample\ws\Calculator.java


3. Java2WSDL - Generate WSDL file

Axis has a tool called Java2WSDL, which generates a WSDL file for a web service using a Java class. We should use the Calculator interface and generate WSDL file as follows. Java2WSDL file requires the Calculator.class file (not Calculator.java) for the operation. Also we will provide the following information.

* o – name for WSDL file -> calculator.wsdl
* n – target namespace -> urn:org.kamal.calculator
* l – url of web service -> http://localhost:8080/axis/services/calculator

WS-Sample\classes> java org.apache.axis.wsdl.Java2WSDL
-o ..\calculator.wsdl
-n urn:org.kamal.calculator
-l http://localhost:8080/axis/services/calculator
org.kamal.wssample.ws.Calculator


This command will generate a file named calculator.wsdl inside your project folder.

4. WSDL2Java - Generate server side and client side classes for web service
Axis has another tool named WSDL2Java, which can generate server side and client side Java classes using a WSDL file. These classes are needed for deploying the web service and for accessing the service by a Java client. This tool must be provided with WSDL file that we generated in the previous step. It needs the following information as well.

* o – output folder -> src
* p – package for generated classes -> org.kamal.wssample.ws.generated
* s – generate server side classes as well

WS-Sample> java org.apache.axis.wsdl.WSDL2Java
-o src
-p org.kamal.wssample.ws.generated
-s
calculator.wsdl


Generated java classes will be saved in org.kamal.wssample.ws.generated package. This tool will generate five Java classes in this case with two .wsdd files as listed below.

* Calculator.java
* CalculatorService.java
* CalculatorServiceLocator.java
* CalculatorSoapBindingImpl.java
* CalculatorSoapBindingStub.java
* deploy.wsdd
* undeploy.wsdd

Now we should compile those generated classes using the following command.

WS-Sample\src> javac –d ..\classes
org\kamal\wssample\ws\generated\*.java


5. Bind Web service with Functionality provider
As you may have noted; even though we wrote org.kamal.wssample.SimpleCalculator class at the start, we have not used it so far. Now we are going to bind it to the web service.

There is a class named CalculatorSoapBindingImpl inside org.kamal.wssample.ws.generated package. This is the class used to bind our existing SimpleCalculator class to the web service calls. In CalculatorSoapBindingImpl class, there are two methods; add() and subtract(). In this class, we can use the SimpleCalculator to call the actual methods as follows.

package org.kamal.wssample.ws.generated;

import org.kamal.wssample.SimpleCalculator;

public class CalculatorSoapBindingImpl
implements org.kamal.wssample.ws.generated.Calculator{

private SimpleCalculator calc = new SimpleCalculator();

public int add(int a, int b) throws java.rmi.RemoteException {
return calc.add(a, b);
}

public int subtract(int from, int x) throws java.rmi.RemoteException {
return calc.subtract(from, x);
}
}


Just analyze the above class, all method calls are delegated to the actual implementation class SimpleCalculator inside this binding class.

6. Bundle required classes
Now we will create a jar file with all these classes, so that we can use it for deploying our web service. Use the jar command as follows.

WS-Sample\classes> jar cvf ..\calculatorServerSide.jar
org\kamal\wssample\*.class
org\kamal\wssample\ws\*.class
org\kamal\wssample\ws\generated\*.class


Now copy this jar file into %CATALINA_HOME%\webapps\axis\WEB-INF\lib folder.

WS-Sample> copy calculatorServerSide.jar
"%CATALINA_HOME%\webapps\axis\WEB-INF\lib"


We will create another jar file to use in the client side. For the client side we only need the classes that were generated by the WSDL2java tool (which are located inside org\kamal\wssample\ws\generated package), except the CalculatorSoapBindingImpl class.

WS-Sample\classes> jar cvf ..\calculatorClientSide.jar
org\kamal\wssample\ws\generated\CalculatorSoapBindingStub.class
org\kamal\wssample\ws\generated\CalculatorServiceLocator.class
org\kamal\wssample\ws\generated\CalculatorService.class
org\kamal\wssample\ws\generated\Calculator.class


7. Register web service with axis
Axis comes with a tool for registering web services with Axis; it is called AdminClient. Look into org\kamal\wssample\ws\generated folder and you will find two WSDD (web service deployment descriptor) files; deploy.wsdd and undeploy.wsdd. These files were generated by WSDL2Java tool and as used in deploying/undeploying a web service.

Note: (Tomcat) Server must be started before executing the following command.

WS-Sample\src> java org.apache.axis.client.AdminClient
org\kamal\wssample\ws\generated\deploy.wsdd


This command will deploy the web service into axis. Now restart (Tomcat) server.

To verify our web service is deployed correctly; try following url from your browser
.
http://localhost:8080/axis/services/calculator?wsdl
(change the port 8080 in url to match the port on your machine)

This will show up a complete wsdl file, and it is the complete definition of the web service that we have deployed.

Now everything on web service (server side) is completed and our web service is successfully deployed.

Web Service client
Now it’s time for us to write a client to access this web service and use provided services. For this we need the calculatorClientSide.jar file that we created in an earlier step.

For the client side we will create a new project folder named “WS-Client” with sub folders named src, classes and lib. Copy the generated calculatorClientSide.jar file into the "WS-Client\lib" folder.


We will create the client as follows. Since our web service exposed two methods, add() and subtract(); client class will use the service and call those add() and subtract() methods.

package org.kamal.wsclient;

import org.kamal.wssample.ws.generated.Calculator;
import org.kamal.wssample.ws.generated.CalculatorService;
import org.kamal.wssample.ws.generated.CalculatorServiceLocator;

public class CalcClient {

public static void main(String[] args) throws Exception {
CalculatorService service = new CalculatorServiceLocator();
Calculator calc = service.getcalculator();

System.out.println("15 + 6 = " + calc.add(15, 6));
System.out.println("15 - 6 = " + calc.subtract(15, 6));
}
}


The above class has not used even a single class that we wrote for Calculator implementation, only a few classes that WSDL2Java tool generated. We have not exposed the server side classes, but just provided a way to get the service from those classes.

Compile the class with following command.

WS-Sample-Client\src> javac
-classpath %CLASSPATH%;..\lib\calculatorClientSide.jar
-d ..\classes
org\kamal\wsclient\CalcClient.java


Now we can run our web service client using following command.

WS-Sample-Client\classes> java
-cp %CLASSPATH%;.;..\lib\calculatorClientSide.jar
org.kamal.wsclient.CalcClient


You would see the following as the result.

15 + 6 = 21
15 – 6 = 9


Our web service client, CalcClient has accessed the web service and received the results from the operations done by SimpleCalculator class (which is running on server side).

As you can see, generating the client side is much easier than the server side.

struts tutorials


Struts MVC Architecture

The model contains the business logic and interact with the persistance storage to store, retrive and manipulate data.

The view is responsible for dispalying the results back to the user. In Struts the view layer is implemented using JSP.

The controller handles all the request from the user and selects the appropriate view to return. In Sruts the controller's job is done by the ActionServlet.



The following events happen when the Client browser issues an HTTP request.

* The ActionServlet receives the request.
* The struts-config.xml file contains the details regarding the Actions, ActionForms, ActionMappings and ActionForwards.
* During the startup the ActionServelet reads the struts-config.xml file and creates a database of configuration objects. Later while processing the request the ActionServlet makes decision by refering to this object.

When the ActionServlet receives the request it does the following tasks.

* Bundles all the request values into a JavaBean class which extends Struts ActionForm class.
* Decides which action class to invoke to process the request.
* Validate the data entered by the user.
* The action class process the request with the help of the model component. The model interacts with the database and process the request.
* After completing the request processing the Action class returns an ActionForward to the controller.
* Based on the ActionForward the controller will invoke the appropriate view.
* The HTTP response is rendered back to the user by the view component.



-------------------------------------------------------------------------------


Hello World Example in Eclipse

In this tutorial you will learn how to create a Struts hello world application in eclipse. First create a new project, go to File->New and select DynamicWebProject.






http://www.vaannila.com/struts/struts-tutorial/struts-tutorial-using-eclipse-1.html

http://viralpatel.net/blogs/2008/12/tutorial-creating-struts-application-in-eclipse.html


other best java tutorials


http://www.tutorialspoint.com/index.htm

JSTL Tutorials

http://www.java2s.com/Tutorial/Java/0380__JSTL/Catalog0380__JSTL.htm

http://www.javamex.com/tutorials/java/objects.shtml