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 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 ohter words, two different platforms) we need to take a binding that provide 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 your 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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace EmpProcessingComp
{
    [ServiceContract]
    public interface IEmpService
    {
        [OperationContract]
        int AddNewEmployee(string id, string name, string address, string city, double salary);
    }
}

Service

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.ServiceModel;
using System.Configuration;
using System.Data.OracleClient;
using System.Runtime.Serialization;

namespace EmpProcessingComp
{
    public class EmpService : IEmpService
    {
        OracleConnection con;
        OracleDataAdapter da;
        DataSet ds;
        OracleCommand cmd;
     
  private string dbCon = ConfigurationManager.ConnectionStrings["myCon"].ConnectionString;

        public int AddNewEmployee(string id, string name, string address, string city, double salary)
        {
            try
            {
                con = new OracleConnection(dbCon);
                cmd = new OracleCommand("prcAddEmp", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("v_eid", id);
                cmd.Parameters.AddWithValue("v_ename", name);
                cmd.Parameters.AddWithValue("v_eadd", address);
                cmd.Parameters.AddWithValue("v_ecity", city);
                cmd.Parameters.AddWithValue("v_esal", salary);
                con.Open();
                int rows = cmd.ExecuteNonQuery();
                return rows;
            }
            catch (Exception e1)
            {
                throw e1;
            }
            finally
            {
                con = null;
            }
        }
    }
}

ConsoleHost (Self Hosting)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using EmpProcessingComp;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(EmpService)))
            {
                host.Open();
                Console.WriteLine("Server is up and running");
                Console.WriteLine("Press any key to terminate");
                Console.ReadKey();
                host.Close();
            }
        }
    }
}

App.Config file

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

<configuration>
  <
system.serviceModel>
    <
behaviors>
      <
serviceBehaviors>
        <
behavior name="MyServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </
serviceBehaviors>
    </
behaviors>
    <
services>
      <
service name="EmpProcessingComp.EmpService" behaviorConfiguration="MyServiceBehavior">
        <host>
          <
baseAddresses>
            <
add baseAddress="http://localhost:13258/"/>
          </baseAddresses>
        </
host>
        <!--
<endpoint address="net.tcp://localhost:32587/"  binding="netTcpBinding" contract="EmpProcessingComp.IEmpService"/>-->
        <
endpoint address="http://localhost:54789/"  binding="basicHttpBinding" contract="EmpProcessingComp.IEmpService"/>
        <endpoint address="http://localhost:13258/" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </
services>
  </
system.serviceModel>
 
<
connectionStrings>
    <
add name="myCon" connectionString="DATA SOURCE=XXX;WORD=XXX;PERSIST SECURITY INFO=True;USER ID=XXX" providerName="Oracle.DataAccess.Client"/>
  </connectionStrings>
</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:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication3;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 *
 * @author Vishal.Gilbile
 */
public class MyTestApp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try
        {
        String name,add,city,eid;
        double sal;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Enter EID");
        eid=br.readLine();

        System.out.println("Enter Name");

        name=br.readLine();

        System.out.println("Enter Address");
        add=br.readLine();

        System.out.println("Enter City");
        city=br.readLine();

        System.out.println("Enter Salary");
        sal=Double.parseDouble(br.readLine());

        addNewEmployee(eid,name,add,city,sal);
        }
        catch(Exception e1)
        {
            System.out.println(e1.getMessage());
        }
    }
    private static Integer addNewEmployee(java.lang.String id, java.lang.String name, java.lang.String address, java.lang.String city, java.lang.Double salary) {
        org.tempuri.EmpService service = new org.tempuri.EmpService();
        org.tempuri.IEmpService port = service.getBasicHttpBindingIEmpService();
        return port.addNewEmployee(id, name, address, city, salary);
    }
}

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.

Up Next
    Ebook Download
    View all
    Learn
    View all