Consuming a WCF Service in Java Application

This project provides an idea of how to consume a WCF service in a Java application. The concept of WCF is very similar to that of a web service. But in a broader sense, WCF is a much broader concept than that of a web service. It's a combination of COM, DCOM, COM+, Remoting & Web service technologies under one umbrella. Microsoft has simplified many things in WCF such as the creation of more than one endpoint for a service to be exposed, creation of service, security in service, diagnostics of service, etc. Today we will have a look at how to consume a .Net WCF service in our Java application. As we all know, WCF has various types of bindings, you must select the most appropriate binding that satisfies your needs. There are certain bindings that are meant for .Net to .Net communication whereas there are others that support interoperability. Now since we are talking about communication between WCF services and a Java application (in other words, two different platforms) we need to take a binding that provides interoperability because the two platforms are different and many of there data types may not be supported by each other. So while implementing/working on such scenarios we need to keep in mind how the communication should be done because your service helps all your .Net related classes or data types but it may not be supported by the Java application.
 
For instance, in your service, if you are having a function that returns a DataTable or any .Net supported type that is not supported by Java, and you want it to be consumed by your Java application, then this may not provide you the desired output and your service may fail while communicating with the service. Enough of the discussion. Now let's move on to our application. As I said, our front end is a Java application and the database that I'm using is an Oracle database and the service is a WCF service.
 
In my database, I've one table named Employee with certain fields (Empid, Name, Address, City, Salary). We have created a service that will try to add data to my Employee Table using an operation contract defined in a service contract. For hosting this service we are using Self Hosting that is basically a simple type of hosting supported by WCF. Self hosting can be used for testing your service and it requires no special resources such as IIS service or any other resource.
 
Our Java application is just a simple Console Application where we have added our service reference and just calls the service function from the main method by ing certain values to it.
 
I'm using Visual Studio to create the C# project and Netbeans to create the Java project.
 
Well now moving towards our service.
 
ServiceContract
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.ServiceModel;  
  6.   
  7. namespace EmpProcessingComp  
  8. {  
  9.     [ServiceContract]  
  10.     public interface IEmpService  
  11.     {  
  12.         [OperationContract]  
  13.         int AddNewEmployee(string id, string name, string address, string city, double salary);  
  14.     }  
  15. }  
Service
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Data;  
  6. using System.ServiceModel;  
  7. using System.Configuration;  
  8. using System.Data.OracleClient;  
  9. using System.Runtime.Serialization;  
  10.   
  11. namespace EmpProcessingComp  
  12. {  
  13.     public class EmpService : IEmpService  
  14.     {  
  15.         OracleConnection con;  
  16.         OracleDataAdapter da;  
  17.         DataSet ds;  
  18.         OracleCommand cmd;  
  19.         private string dbCon = ConfigurationManager.ConnectionStrings["myCon"].ConnectionString;  
  20.   
  21.         public int AddNewEmployee(string id, string name, string address, string city, double salary)  
  22.         {  
  23.             try  
  24.             {  
  25.                 con = new OracleConnection(dbCon);  
  26.                 cmd = new OracleCommand("prcAddEmp", con);  
  27.                 cmd.CommandType = CommandType.StoredProcedure;  
  28.                 cmd.Parameters.AddWithValue("v_eid", id);  
  29.                 cmd.Parameters.AddWithValue("v_ename", name);  
  30.                 cmd.Parameters.AddWithValue("v_eadd", address);  
  31.                 cmd.Parameters.AddWithValue("v_ecity", city);  
  32.                 cmd.Parameters.AddWithValue("v_esal", salary);  
  33.                 con.Open();  
  34.                 int rows = cmd.ExecuteNonQuery();  
  35.                 return rows;  
  36.             }  
  37.             catch (Exception e1)  
  38.             {  
  39.                 throw e1;  
  40.             }  
  41.             finally  
  42.             {  
  43.                 con = null;  
  44.             }  
  45.         }  
  46.     }  
  47. }  
ConsoleHost (Self Hosting)
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.ServiceModel;  
  6. using EmpProcessingComp;  
  7.   
  8. namespace ConsoleApplication1  
  9. {  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.             using (ServiceHost host = new ServiceHost(typeof(EmpService)))  
  15.             {  
  16.                 host.Open();  
  17.                 Console.WriteLine("Server is up and running");  
  18.                 Console.WriteLine("Press any key to terminate");  
  19.                 Console.ReadKey();  
  20.                 host.Close();  
  21.             }  
  22.         }  
  23.     }  
  24. }  
App.Config file
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2.   
  3. <configuration>  
  4.   <system.serviceModel>  
  5.     <behaviors>  
  6.       <serviceBehaviors>  
  7.         <behavior name="MyServiceBehavior">  
  8.           <serviceMetadata httpGetEnabled="true"/>  
  9.           <serviceDebug includeExceptionDetailInFaults="true"/>  
  10.         </behavior>  
  11.       </serviceBehaviors>  
  12.     </behaviors>  
  13.     <services>  
  14.       <service name="EmpProcessingComp.EmpService" behaviorConfiguration="MyServiceBehavior">  
  15.         <host>  
  16.           <baseAddresses>  
  17.             <add baseAddress="http://localhost:13258/"/>  
  18.           </baseAddresses>  
  19.         </host>  
  20.         <!--<endpoint address="net.tcp://localhost:32587/"  binding="netTcpBinding" contract="EmpProcessingComp.IEmpService"/>-->  
  21.         <endpoint address="http://localhost:54789/"  binding="basicHttpBinding" contract="EmpProcessingComp.IEmpService"/>  
  22.         <endpoint address="http://localhost:13258/" binding="mexHttpBinding" contract="IMetadataExchange"/>  
  23.       </service>  
  24.     </services>  
  25.   </system.serviceModel>  
  26.   <connectionStrings>  
  27.     <add name="myCon" connectionString="DATA SOURCE=XXX;WORD=XXX;PERSIST SECURITY INFO=True;USER ID=XXX" providerName="Oracle.DataAccess.Client"/>  
  28.   </connectionStrings>  
  29. </configuration>  
Now finally we will create our Java application.
 
I'm using Netbeans to create this project.
 
After creating the new project, in your project tab you'll find your project being listed. To Add the WCF service reference to your project right-click on the project then "New" -> WebserviceClient.
 
WCFService1.jpg 
 
On selection of the Webserviceclient you'll get another dialog box.
 
Before moving towards the next step kindly first run the ConsoleHost Application.
 
Select the WSDL URL from the WSDL file of the Web service and the WSL URL to it like the following.
 
WCFService2.jpg 
 
Finally click Finish. In this way you added your service reference to your Java application.
 
Note
  1. While adding the reference to your Java application, kindly ensure that your console host is running and the displaying message "Server is up and running" that we specified in the ConsoleHost main method.
  2. Always ensure that whenever you are running your application or testing your service your ConsoleHost is also running, this is because we are using Self Hosting.
  3. The following is the ConsoleHost output. You need to run it while adding the reference or downloading the WSDL of our WCF service.

    WCFService3.jpg
The following is the source code for it:
  1. /* 
  2.  * To change this template, choose Tools | Templates 
  3.  * and open the template in the editor. 
  4.  */  
  5. package javaapplication3;  
  6.   
  7. import java.io.BufferedReader;  
  8. import java.io.InputStreamReader;  
  9.   
  10. /** 
  11.  * 
  12.  * @author Vishal.Gilbile 
  13.  */  
  14. public class MyTestApp {  
  15.   
  16.     /** 
  17.      * @param args the command line arguments 
  18.      */  
  19.     public static void main(String[] args) {  
  20.         try  
  21.         {  
  22.         String name,add,city,eid;  
  23.         double sal;  
  24.         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
  25.   
  26.         System.out.println("Enter EID");  
  27.         eid=br.readLine();  
  28.   
  29.         System.out.println("Enter Name");  
  30.   
  31.         name=br.readLine();  
  32.   
  33.         System.out.println("Enter Address");  
  34.         add=br.readLine();  
  35.   
  36.         System.out.println("Enter City");  
  37.         city=br.readLine();  
  38.   
  39.         System.out.println("Enter Salary");  
  40.         sal=Double.parseDouble(br.readLine());  
  41.   
  42.         addNewEmployee(eid,name,add,city,sal);  
  43.         }  
  44.         catch(Exception e1)  
  45.         {  
  46.             System.out.println(e1.getMessage());  
  47.         }  
  48.     }  
  49.     private static Integer addNewEmployee(java.lang.String id, java.lang.String name, java.lang.String address, java.lang.String city, java.lang.Double salary) {  
  50.         org.tempuri.EmpService service = new org.tempuri.EmpService();  
  51.         org.tempuri.IEmpService port = service.getBasicHttpBindingIEmpService();  
  52.         return port.addNewEmployee(id, name, address, city, salary);  
  53.     }  
  54. }  
To call the service function, use the following strategry. 
  1. Right-click on the Neatbeans editor within the main method or within the class and select InsertCode context menu or press Alt+Insert.

    WCFService4.jpg

  2. On selection of the InsertCode context menu, a new box will appear; from here you must select callWebservice operations.

    WCFService5.jpg

  3. You'll get another dialog box. From here you must select the service and the binding that you want to use to establish a connection between the Java application and the service.

    WCFService6.jpg
     
  4. Press OK and your service methods will be added to your code, now you just need to call it.
The following is the output.
 
And finally just check-in the database you'll get the values.
 
Hope you all have liked the project.


Similar Articles