Sales
Click for numbers
Welcome User Tools Developer Tools Prices Help Sign up Login
You are here: Home > Developer Tools > Fax Web Service > Samples > Java Web Service Tutorial

InterFAX Java Web Service Tutorial

Outline

Introduction

This tutorial will walk you through the process of building a Java program to send faxes using the Interfax web service. It's assumed that you are familiar with the Java programming language, have a good grasp of the basic skills involved in writing, building, and testing Java programs, and that you also have a good understanding of the Internet and the basic set of protocols encountered in Internet programming today.

This tutorial assumes that you are beginning to explore the world of Web Services and have little or no experience with web services specifically. If you already feel comfortable with web services you can skip the Web Services Primer below.

The full source code for this tutorial is available here:

InterfaxJavaTutorial.zip

InterfaxJavaTutorial.tar.gz

Web Services Primer

The Wikipedia entry for web service (http://en.wikipedia.org/wiki/Web_service) is a good place to start learning about web services and the family of standards and technologies that make them happen. In a nutshell, a web service is a program made available by its author to other programs on a computer network. Web services usually do useful things--today there are web services that provide real-time stock quotes, translate text to braille, perform complex statistical analyses, and all sorts of other things. For a big list of some available webservices, see http://www.xmethods.net.

Interfax provides a webservice that programmers can use to add faxing capabilities to their applications. You will see in this tutorial that using the Interfax web service in your Java programs is fairly straightforward and much more practical than attempting to write your own faxing software.

The goal of web services is to enable one computer program to communicate with and benefit from using another computer program. This is the essence of distributed computing and is not a new idea. With the recent incredible growth of the Internet, and the World Wide Web specifically, progammers suddenly find themselves on the same network with thousands of other programmers. This Internet growth has fueled lots of innovation in distributed computing and the newest generation of software applications is built by programmers who understand the power of this computing paradigm.

Motivations for Modern Web Services

Java programmers have had excellent tools for distributed programming for some time. The Remote Method Invocation (RMI) library, released with Java 1.1, made it incredibly easy for Java programs to talk to eachother, essentially allowing one program to call a method on a class running in another program. With the RMI library came Java serialization, an automated framework for sending object instances over a network connection. RMI is one of the greatest Java successes and the most popular way for Java programmers to build distributed programs.

The Internet poses a new and difficult problem because in the real world programmers have dozens of programming languages and operating systems to choose from and making these programs work together is not easy. Java RMI is great for connecting one Java program to another Java program but it's useless for connecting a Java program to a C++, Python, Perl, or C# program, all of which are very common. Another problem is that the Internet is very security conscious--firewalls block most of the ports two computers could communicate on, including 1099, the default RMI port.

The solution to connecting these varied programs in this restricted Internet environment depends on finding a lowest common denominator, a communication protocol that is as simple as possible and available to all programmers regardless of their operating system or programming language. Also important is to find a protocol that can be used on the Internet without having to worry about firewalls. With these goals in mind, HTTP is an obvious choice as it is extremely simple to use, it's available on virtually every operating system and every programming language, and it's the protocol of the World Wide Web itself, which most firewalls do not block.

Simple Object Access Protocol (SOAP)

Having chosen HTTP, it's important to decide on the types of messages two programs would send back and forth to do meaningful things together. The original designers came up with the Simple Object Access Protocol, or SOAP, to address the structure of these messages. They decided that the messages should be simple to produce and consume and should be human-readable. To accomplish this, they chose an Extensible Markup Language (XML) message format.

As a simple illustration, let's assume you want to access a web service to find the current weather forecast for Chicago. Such a web service exists, and a program wishing to use it would produce an XML message that looks like the following:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetWeatherByPlaceName xmlns="http://www.webservicex.net">
      <PlaceName>Chicago</PlaceName>
    </GetWeatherByPlaceName>
  </soap:Body>
</soap:Envelope>

The webservice would receive this message, and would produce an XML response for the client that looks something like this:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema"
               xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetWeatherByPlaceNameResponse xmlns="http://www.webservicex.net">
      <GetWeatherByPlaceNameResult>
        <Latitude>41.8858452</Latitude>
        <Longitude>87.6181259</Longitude>
        <AllocationFactor>0.000401</AllocationFactor>
        <FipsCode>17</FipsCode>
        <PlaceName>CHICAGO</PlaceName>
        <StateCode>IL</StateCode>
        <Details>
          <WeatherData>
            <Day>Friday, November 18, 2005</Day>
            <WeatherImage>http://www.nws.noaa.gov/weather/images/fcicons/nsn.jpg</WeatherImage>
            <MaxTemperatureF>39</MaxTemperatureF>
            <MinTemperatureF>20</MinTemperatureF>
            <MaxTemperatureC>4</MaxTemperatureC>
            <MinTemperatureC>-7</MinTemperatureC>
          </WeatherData>
          <WeatherData>
            <Day>Saturday, November 19, 2005</Day>
            <WeatherImage>http://www.nws.noaa.gov/weather/images/fcicons/bkn.jpg</WeatherImage>
            <MaxTemperatureF>43</MaxTemperatureF>
            <MinTemperatureF>33</MinTemperatureF>
            <MaxTemperatureC>6</MaxTemperatureC>
            <MinTemperatureC>1</MinTemperatureC>
          </WeatherData>
        </Details>
      </GetWeatherByPlaceNameResult>
    </GetWeatherByPlaceNameResponse>
  </soap:Body>
</soap:Envelope>

There's really nothing magical going on here. One computer program sends an XML-formatted text message asking for weather information for Chicago to another program using HTTP. That program responds with an XML-formatted text document which includes some weather forecast information for Chicago. This is a very simple conduit between two different programs which don't need to be written in the same programming language, and don't need to be running on the same operating system. All SOAP communications happen like this, with the simple passing of XML messages between programs.

Web Service Description Language (WSDL)

While these messages look simple enough, a programmer has to know ahead of time how to format an XML SOAP message before sending it to another program. Also, a programmer would need to know what information to expect in the response document and how it will be formatted. In SOAP, each web service is described by an XML document formatted according to a standard known as Web Service Description Language (WSDL). When a programmer builds a web service, they provide a WSDL document which specifically describes how request and response messages should be formatted and also provides additional information. For example, the types of "faults" or exceptions that the caller ought to expect if the service was unable to fullfill a given request. As an example, here's an abridged version of the WSDL for the weather web service above. Don't worry too much about the details now, just notice that it describes what the web service does, how it can be called, and how request and response messages should be formatted. (For the curious, the full WSDL can be found here):

<wsdl:definitions targetNamespace="http://www.webservicex.net">
<wsdl:types>
<s:schema elementFormDefault="qualified" targetNamespace="http://www.webservicex.net">

<s:complexType name="WeatherForecasts">
   <s:sequence>
      <s:element minOccurs="1" maxOccurs="1" name="Latitude" type="s:float"/>
      <s:element minOccurs="1" maxOccurs="1" name="Longitude" type="s:float"/>
      <s:element minOccurs="1" maxOccurs="1" name="AllocationFactor" type="s:float"/>
      <s:element minOccurs="0" maxOccurs="1" name="FipsCode" type="s:string"/>
      <s:element minOccurs="0" maxOccurs="1" name="PlaceName" type="s:string"/>
      <s:element minOccurs="0" maxOccurs="1" name="StateCode" type="s:string"/>
      <s:element minOccurs="0" maxOccurs="1" name="Status" type="s:string"/>
      <s:element minOccurs="0" maxOccurs="1" name="Details" type="tns:ArrayOfWeatherData"/>
   </s:sequence>
</s:complexType>
<s:complexType name="ArrayOfWeatherData">
   <s:sequence>
      <s:element minOccurs="0" maxOccurs="unbounded" name="WeatherData" type="tns:WeatherData"/>
   </s:sequence>
</s:complexType>
<s:complexType name="WeatherData">
   <s:sequence>
      <s:element minOccurs="0" maxOccurs="1" name="Day" type="s:string"/>
      <s:element minOccurs="0" maxOccurs="1" name="WeatherImage" type="s:string"/>
      <s:element minOccurs="0" maxOccurs="1" name="MaxTemperatureF" type="s:string"/>
      <s:element minOccurs="0" maxOccurs="1" name="MinTemperatureF" type="s:string"/>
      <s:element minOccurs="0" maxOccurs="1" name="MaxTemperatureC" type="s:string"/>
      <s:element minOccurs="0" maxOccurs="1" name="MinTemperatureC" type="s:string"/>
   </s:sequence>
</s:complexType>

<s:element name="GetWeatherByPlaceName">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="PlaceName" type="s:string"/>
</s:sequence>
</s:complexType>
</s:element>

<s:element name="GetWeatherByPlaceNameResponse">
<s:complexType>
<s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="GetWeatherByPlaceNameResult" type="tns:WeatherForecasts"/>
</s:sequence>
</s:complexType>
</s:element>
<s:element name="WeatherForecasts" type="tns:WeatherForecasts"/>
</s:schema>
</wsdl:types>

<wsdl:message name="GetWeatherByPlaceNameSoapIn">
   <wsdl:part name="parameters" element="tns:GetWeatherByPlaceName"/>
</wsdl:message>
<wsdl:message name="GetWeatherByPlaceNameSoapOut">
   <wsdl:part name="parameters" element="tns:GetWeatherByPlaceNameResponse"/>
</wsdl:message>

<wsdl:portType name="WeatherForecastSoap">
   <wsdl:operation name="GetWeatherByPlaceName">
      <documentation>
         Get one week  weather forecast for a place name(USA)
      </documentation>
      <wsdl:input message="tns:GetWeatherByPlaceNameSoapIn"/>
      <wsdl:output message="tns:GetWeatherByPlaceNameSoapOut"/>
   </wsdl:operation>
</wsdl:portType>

<wsdl:binding name="WeatherForecastSoap" type="tns:WeatherForecastSoap">
   <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
      <wsdl:operation name="GetWeatherByPlaceName">
         <soap:operation soapAction="http://www.webservicex.net/GetWeatherByPlaceName" style="document"/>
            <wsdl:input>
               <soap:body use="literal"/>
            </wsdl:input>
            <wsdl:output>
               <soap:body use="literal"/>
            </wsdl:output>
         </wsdl:operation>
</wsdl:binding>

<wsdl:service name="WeatherForecast">
   <documentation>
      Get one week weather forecast for valid zip code or Place name in USA
   </documentation>

   <wsdl:port name="WeatherForecastSoap" binding="tns:WeatherForecastSoap">
      <soap:address location="http://www.webservicex.net/WeatherForecast.asmx"/>
   </wsdl:port>
</wsdl:service>

</wsdl:definitions>

Fortunately, you don't need to master the ins and outs of SOAP, WSDL, or even XML to use web services. In fact, you can use web services with very little background in any of these standards, with the help of great tools that alleviate the need to hand-process WSDL or SOAP messages. While you're encouraged to learn as much as you can about SOAP, WSDL, XML Schema, and the family of standards that commonly enable web services, this tutorial will not go into more detail on these topics. Please see these great references for more background information:

Learn By Doing: Building a Web Service Client

The best way to learn about web services is to get first-hand experience with them. Let's write a Java program to use a real web service, the Interfax web service. All of the steps outlined above are done for you in the distribution that accompanies this tutorial. In the tutorial distribution, you will find a fully-working copy of the demo program we're about to build below.

Workspace Setup

First, we need to create a workspace for our Java program. Following convention, let's build a sensible set of directories to hold our source code and documentation. You can do this in a new directory if you like, these directories already exist in the distribution of this tutorial:

/tutorial
   /src
   /doc

We will build our project using Apache ANT. You should have ANT installed on your system--you can get the latest version here. We will need a simple ANT build file to get us started. Below is a slightly modified copy of the sample build.xml file from the ANT manual. We'll put this build file (build.xml) in our tutorial directory:

/tutorial/build.xml

<project name="MyProject" default="dist" basedir=".">
    <description>
        Interfac Tutorial build file
    </description>
  <!-- set global properties for this build -->
  <property name="src" location="src"/>
  <property name="build" location="build"/>
  <property name="dist"  location="dist"/>

  <target name="init">
    <!-- Create the build directory structure used by compile -->
    <mkdir dir="${build}"/>
  </target>

  <target name="compile" depends="init"
        description="compile the source " >
    <!-- Compile the java code from ${src} into ${build} -->
    <javac srcdir="${src}" destdir="${build}"/>
  </target>

  <target name="dist" depends="compile"
        description="generate the distribution" >
    <!-- Create the distribution directory -->
    <mkdir dir="${dist}"/>

    <!-- Put everything in ${build} into the MyProject.jar file -->
    <jar jarfile="${dist}/MyProject.jar" basedir="${build}"/>
  </target>

  <target name="clean"
        description="clean up" >
    <!-- Delete the ${build} and ${dist} directory trees -->
    <delete dir="${build}"/>
    <delete dir="${dist}"/>
  </target>
</project>

Interfax Account Creation

Please be sure to create an account with Interfax at this point. Registration is free and can be done online http://www.interfax.net/Scripts/Reg_BP.asp. You will need your Interfax username and password to send faxes through the Interfax web service, be sure to have both handy. To avoid typing them over and over again, it's a good idea to put them in one place where we can reference them. We'll create a TestConstants class for this as shown below.

/*
 * These are constants used throughout our tests.  Moved there here to avoid
 * repeating them in each test.
 */
public class TestConstants {

    // Replace with your Interfax username and password.
    public static final String USERNAME = "username";
    public static final String PASSWORD = "password";
}

Apache Axis Toolkit

Connecting to a web service involves several steps. You have to first have the WSDL document describing the service you're going to connect to. The WSDL for the Interfax web service is available here: http://ws.interfax.net/dfs.asmx?wsdl. (Note: If you want to use SSL to securely communicate with the Interfax web service, use an https URL instead: https://ws.interfax.net/dfs.asmx?wsdl).

WSDL documents can be difficult to interpret and they are often quite complicated. One popular example, the WSDL for Ebay's web services, is 1.92 MB big in its latest version! Fortunately, you don't have to learn how to read and decipher WSDL to use webservices. In fact, you don't usually have to learn how to parse XML, make HTTP connections, or read XML Schema. Programmers have automated these processes in SOAP toolkits, special software that can be used to generate a set of Java classes that you can use directly to call a web service. Several SOAP toolkits exist for Java programmers, and the most popular and capable today is the Axis toolkit from the Apache Organization. This toolkit is nothing more than a set of Java classes itself which reads a WSDL, interprets it, and generates a set of Java classes which will call the web service specified in the WSDL.

You can download the latest Axis 1.x distribution from Apache here: http://ws.apache.org/axis/ or you can use the version in the distribution of this tutorial (1.4). Either way, you should have a set of jar files from the Axis distribution in a new lib directory in your workspace that looks like the listing below. (Note that Apache has release Axis 2 which is completely new SOAP implementation and not what we're using for this tutorial. For best results, use Axis 1.4).

tutorial/lib/
    axis-ant.jar
    axis.jar
    commons-discovery-0.2.jar
    commons-logging-1.0.4.jar
    jaxrpc.jar
    log4j-1.2.8.jar
    log4j.properties
    saaj.jar
    wsdl4j-1.5.1.jar

At this point, we'll make a couple of additions to our build.xml file to add these jar files to our classpath and to enable a special ANT task that will generate our web service client starter code for us. Additions are in red. Don't be alarmed the only changes we made were the following:

  • Added a lib directory
  • Added a generated directory for Java classes generated by Axis
  • Established a classpath that simply includes everything in our lib directory
  • Added a hardcoded reference to the Interfax WSDL URL
  • Imported the ANT tasks that come with Axis, including the WSDL-to-Java task which we will use
  • Created a new target called code.generation to call the axis-wsdl2java task on the Interfax WSDL
  • Updated our compile task to build the Java code generated by Axis as well as the Java code in our src directory
<project name="MyProject" default="dist" basedir=".">
    <description>
        Interfac Tutorial build file
    </description>
  <!-- set global properties for this build -->
  <property name="lib" location="lib"/>
  <property name="generated" location="generated"/>
  <property name="src" location="src"/>
  <property name="build" location="build"/>
  <property name="dist"  location="dist"/>

  <!-- Establish a classpath we can use in the compile target.-->
  <path id="compile.classpath">
      <fileset dir="${lib}">
        <include name="**/*.jar" />
      </fileset>
  </path>

  <!-- Hardcoded Interfax service URL -->
  <property name="wsdl.url" value="http://ws.interfax.net/dfs.asmx?WSDL"/>

  <!-- Apache Axis comes with a pre-built wsdl-to-java ANT task.  The following
       path and taskdef make this ANT task available to us. -->
  <taskdef resource="axis-tasks.properties" classpathref="compile.classpath" />

  <target name="init">
    <!-- Create the build directory structure used by compile -->
    <mkdir dir="${build}"/>
    <mkdir dir="${generated}"/>
  </target>

  <target name="code.generation" depends="init" description="generate the Java stubs for accessing the InterFAX web service">
  <axis-wsdl2java
      output="${generated}"
      testcase="false"
      verbose="true"
      nowrapped="true"
      url="${wsdl.url}" >
      <mapping
          namespace="http://axis.apache.org/ns/interop"
          package="interop" />
  </axis-wsdl2java>
  </target>

  <target name="compile" depends="code.generation"
        description="compile the source " >
    <!-- Compile the java code from ${generated} into ${build} -->
    <javac srcdir="${generated}" destdir="${build}">
        <!-- Compilation Classpath -->
        <classpath>
            <path refid="compile.classpath" />
        </classpath>
    </javac>
    <!-- Compile the java code from ${src} into ${build} -->
    <javac srcdir="${src}" destdir="${build}">
        <!-- Compilation Classpath -->
        <classpath>
            <path refid="compile.classpath" />
        </classpath>
    </javac>
  </target>

  <target name="dist" depends="compile"
        description="generate the distribution" >
    <!-- Create the distribution directory -->
    <mkdir dir="${dist}"/>

    <!-- Put everything in ${build} into the MyProject.jar file -->
    <jar jarfile="${dist}/MyProject.jar" basedir="${build}"/>
  </target>

  <target name="clean"
        description="clean up" >
    <!-- Delete the ${build} and ${dist} directory trees -->
    <delete dir="${build}"/>
    <delete dir="${dist}"/>
    <delete dir="${generated}"/>
  </target>
</project>

Here's the output from building with the updated build file:

$ ant
Buildfile: C:\workspace\InterfaxJavaTutorial\build.xml
init:
    [mkdir] Created dir: C:\workspace\InterfaxJavaTutorial\build
    [mkdir] Created dir: C:\workspace\InterfaxJavaTutorial\build\dist
    [mkdir] Created dir: C:\workspace\InterfaxJavaTutorial\build\test
    [mkdir] Created dir: C:\workspace\InterfaxJavaTutorial\generated
code.generation:
[axis-wsdl2java] - Unable to find required classes (javax.activation.DataHandler and javax.mail.internet.MimeMultipart). Attachment support is disabled.

[axis-wsdl2java] WSDL2Java http://ws.interfax.net/DFS.asmx?WSDL
[axis-wsdl2java] Parsing XML file:  http://ws.interfax.net/DFS.asmx?WSDL
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\CancelFileUpload.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\ReSendFaxResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendfaxEx_2Response.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\GetSupportedFileTypes.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\Sendfax.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendfaxEx_2.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\IsSupportedFileTypeResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatusXML.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxQueryResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\HideFaxResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendCharFaxResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxItem.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatus.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\CancelFileUploadResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendfaxEx.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatusExResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatusResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\HideFax.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxItemEx.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\GetFaxImage.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxQuery.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\IsSupportedFileType.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatusXMLResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\GetFaxImageResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendCharFax.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\UploadFileChunk.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatusEx.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendfaxResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendfaxExResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\GetSupportedFileTypesResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\StartFileUpload.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\StartFileUploadResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\UploadFileChunkResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\ReSendFax.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\InterFaxSoap.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\InterFaxSoapStub.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\InterFax.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\InterFaxLocator.java

compile:
    [javac] Compiling 38 source files to C:\workspace\InterfaxJavaTutorial\build\dist
    [javac] Note: Some input files use unchecked or unsafe operations.
    [javac] Note: Recompile with -Xlint:unchecked for details.
    [javac] Compiling 11 source files to C:\workspace\InterfaxJavaTutorial\build\test
dist:
    [mkdir] Created dir: C:\workspace\InterfaxJavaTutorial\dist
      [jar] Building jar: C:\workspace\InterfaxJavaTutorial\dist\Interfax.jar
BUILD SUCCESSFUL
Total time: 12 seconds

The important thing to notice above is that Axis did a lot of the hard work for us. It downloaded the Interfax web service WSDL, parsed it, and generated several new Java classes that we can use to call the Interfax web service. This has saved us tons of time and frustrating trial and error. With a little more effort, we'll be ready to use the Interfax SOAP service from Java programs.

Of all the files Axis generated, InterFaxSoapStub.java is the most important because, as its name implies, it acts as a stub that can be used to call the Interfax web service. This stub class has various methods on it (listed below) which correspond to the methods described in the Interfax WSDL file. Axis translated the WSDL into methods we can call from our code without having to worry about the details of how each call gets made. This is very similar to RMI, which also allows you to make simple method calls that hide the details of the remote call that's happening under the hood.

All of the methods in InterFaxSoapStub are documented on the Interfax website--keep in mind that each method (and the description that appears for each one) came directly from the WSDL that Axis interpreted for us.

/**
 * This is the simplest method to fax ASCII text.  Also allows
 * structured text documents, such as HTML, PostScript, etc.  (To fax
 * an attachment simply - use the SendFax method.)
 */
public cc.interfax.www.SendCharFaxResponse sendCharFax(cc.interfax.www.SendCharFax parameters) throws java.rmi.RemoteException;

/**
 * This is the simplest method to fax an attached file.  Five
 * parameters are all that's required.  (To fax a simple text message
 * - use the SendCharFax method.)
 */
public cc.interfax.www.SendfaxResponse sendfax(cc.interfax.www.Sendfax parameters) throws java.rmi.RemoteException;

/**
 * [Retained for backward-compatibility; replaced by SendfaxEx_2]
 */
public cc.interfax.www.SendfaxExResponse sendfaxEx(cc.interfax.www.SendfaxEx parameters) throws java.rmi.RemoteException;

/**
 * The most feature-filled fax sending method.  Allows full control
 * over all aspects of fax transmission.  Adds page-control features
 * not previously found in the SendfaxEx method.
 */
public cc.interfax.www.SendfaxEx_2Response sendfaxEx_2(cc.interfax.www.SendfaxEx_2 parameters) throws java.rmi.RemoteException;

/**
 * This is a simple method to resend a fax. Four parameters are
 * all that's required
 */
public cc.interfax.www.ReSendFaxResponse reSendFax(cc.interfax.www.ReSendFax parameters) throws java.rmi.RemoteException;

/**
 * Returns full information (27 fields - see Reference)
 * regarding a fax transaction's current status.
 */
public cc.interfax.www.FaxStatusExResponse faxStatusEx(cc.interfax.www.FaxStatusEx parameters) throws java.rmi.RemoteException;

/**
 * Returns full information (27 fields - see Reference)
 * regarding a population determined by Verb.
 */
public cc.interfax.www.FaxQueryResponse faxQuery(cc.interfax.www.FaxQuery parameters) throws java.rmi.RemoteException;

/**
 * Returns quick and minimal information (11 fields - see Reference)
 * regarding a fax transaction's current status.
 */
public cc.interfax.www.FaxStatusResponse faxStatus(cc.interfax.www.FaxStatus parameters) throws java.rmi.RemoteException;

/**
 * Similar to FaxStatusEx, however, returns information in XML-formatted
 * structure.
 */
public cc.interfax.www.FaxStatusXMLResponse faxStatusXML(cc.interfax.www.FaxStatusXML parameters) throws java.rmi.RemoteException;

/**
 * Returns a TIF file of a transactions rendered document.
 */
public cc.interfax.www.GetFaxImageResponse getFaxImage(cc.interfax.www.GetFaxImage parameters) throws java.rmi.RemoteException;

/**
 * A utility method to obtain the currently supported file types.
 */
public cc.interfax.www.GetSupportedFileTypesResponse getSupportedFileTypes(cc.interfax.www.GetSupportedFileTypes parameters) throws java.rmi.RemoteException;

/**
 * A utility method to verify if a given file type is supported.
 */
public cc.interfax.www.IsSupportedFileTypeResponse isSupportedFileType(cc.interfax.www.IsSupportedFileType parameters) throws java.rmi.RemoteException;

/**
 * This is a simple method to hide a transaction in the log
 */
public cc.interfax.www.HideFaxResponse hideFax(cc.interfax.www.HideFax parameters) throws java.rmi.RemoteException;

/**
 * Start an Upload session; Returns a Session ID string, to be
 * used by subsequent calls.
 */
public cc.interfax.www.StartFileUploadResponse startFileUpload(cc.interfax.www.StartFileUpload parameters) throws java.rmi.RemoteException;
public cc.interfax.www.UploadFileChunkResponse uploadFileChunk(cc.interfax.www.UploadFileChunk parameters) throws java.rmi.RemoteException;
public cc.interfax.www.CancelFileUploadResponse cancelFileUpload(cc.interfax.www.CancelFileUpload parameters) throws java.rmi.RemoteException;

LoadSupportedFileTypes

Let's make our first web service call. We'll start off simple with a call that asks the Interfax SOAP service for the list of file types it understands. Below is a simple class that uses the InterFaxSoapStub class generated by Axis to call the GetSupportedFileTypes SOAP method. The web service call is highlighted in red.

import cc.interfax.www.GetSupportedFileTypes;
import cc.interfax.www.GetSupportedFileTypesResponse;

public class GetSupportedFileTypesTest {

    public void run() throws Exception {
        cc.interfax.www.InterFaxSoapStub theBinding;

        try {
           theBinding = (cc.interfax.www.InterFaxSoapStub)
                         new cc.interfax.www.InterFaxLocator().getInterFaxSoap();
        }
        catch (javax.xml.rpc.ServiceException jre) {
            if(jre.getLinkedCause()!=null)
                jre.getLinkedCause().printStackTrace();
            throw new RuntimeException("JAX-RPC ServiceException caught: " + jre);
        }

        // Time out after a minute
        theBinding.setTimeout(60000);

        GetSupportedFileTypesResponse response =
            theBinding.getSupportedFileTypes(new GetSupportedFileTypes());
        
        String theSupportedFileTypesStr = response.getGetSupportedFileTypesResult();
        System.out.println(theSupportedFileTypesStr);
    }


    public static void main(String[] anArgs) {
        try {
            new GetSupportedFileTypesTest().run();
        } catch(Exception theE) {
           System.out.println("Error encountered while running GetSupportedFileTypesTest:");
           theE.printStackTrace();
        }
     }
}

We'll add the following target to our ANT build script so we can run our test program using ANT.

<target name="run-get-supported-types-test" depends="dist" description="Test that makes a GetSupportedFileTypes call" >
    <java classname="GetSupportedFileTypesTest">
       <arg value="-h"/>
       <classpath>
         <pathelement location="dist/Interfax.jar"/>
         <pathelement path="${build}/test/"/>
         <pathelement path="${java.class.path}"/>
         <path refid="compile.classpath"/>
       </classpath>
    </java>
</target>

Invoking this target should produce output similar to what appears below.

$ ant run-get-supported-types-test
Buildfile: C:\workspace\InterfaxJavaTutorial\build.xml
init:
code.generation:
[axis-wsdl2java] - Unable to find required classes (javax.activation.DataHandler and javax.mail.internet.MimeMultipart). Attachment support is disabled.
[axis-wsdl2java] WSDL2Java http://ws.interfax.net/DFS.asmx?WSDL
[axis-wsdl2java] Parsing XML file:  http://ws.interfax.net/DFS.asmx?WSDL
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\CancelFileUpload.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\ReSendFaxResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendfaxEx_2Response.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\GetSupportedFileTypes.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\Sendfax.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendfaxEx_2.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\IsSupportedFileTypeResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatusXML.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxQueryResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\HideFaxResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendCharFaxResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxItem.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatus.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\CancelFileUploadResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendfaxEx.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatusExResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatusResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\HideFax.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxItemEx.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\GetFaxImage.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxQuery.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\IsSupportedFileType.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatusXMLResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\GetFaxImageResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendCharFax.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\UploadFileChunk.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatusEx.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendfaxResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendfaxExResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\GetSupportedFileTypesResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\StartFileUpload.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\StartFileUploadResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\UploadFileChunkResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\ReSendFax.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\InterFaxSoap.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\InterFaxSoapStub.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\InterFax.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\InterFaxLocator.java
compile:
    [javac] Compiling 38 source files to C:\workspace\InterfaxJavaTutorial\build\dist
    [javac] Note: Some input files use unchecked or unsafe operations.
    [javac] Note: Recompile with -Xlint:unchecked for details.
dist:
      [jar] Building jar: C:\workspace\InterfaxJavaTutorial\dist\Interfax.jar
run-get-supported-types-test:
     [java] - Unable to find required classes (javax.activation.DataHandler and javax.mail.internet.MimeMultipart). Attachment support is disabled.
     [java] ,XML,RTF,DOC,DOT,TXT,PDF,HTM,HTML,TIF,TIFF,GIF,PNG,JPG,JPEG,PS,EPS,URL,XLS,PPT,PCX,SNP,MHT,BMP
BUILD SUCCESSFUL
Total time: 16 seconds

The response from the web service is this String which verifies that PDF is a supported file type, along with many others: ,XML,RTF,DOC,DOT,TXT,PDF,HTM,HTML,TIF,TIFF,GIF,PNG,JPG,JPEG,PS,EPS,URL,XLS,PPT,PCX,SNP,MHT,BMP

We cam access all of the Interfax web service calls using the Axis-generated stub class. Our ultimate goal is to send a fax and there are various methods in the Interfax web service to do that. Below we'll use SendCharFax and SendFax to fax a simple text message and a PDF document.

Sending a Fax

SendCharFaxTest

The InterFax sendCharFax() web service method lets you fax a text document. We'll build a simple class that calls that method to demonstrate sending a simple Java String instance as a fax message using the sendCharFax() web service. The actual service call is again highlighted in red.

import cc.interfax.www.SendCharFax;
import cc.interfax.www.SendCharFaxResponse;

public class SendCharFaxTest {

    public void run() throws Exception {
        cc.interfax.www.InterFaxSoapStub theBinding;
        try {
           theBinding = (cc.interfax.www.InterFaxSoapStub)
                        new cc.interfax.www.InterFaxLocator().getInterFaxSoap();
        }
        catch (javax.xml.rpc.ServiceException jre) {
            if(jre.getLinkedCause()!=null)
                jre.getLinkedCause().printStackTrace();
            throw new RuntimeException("JAX-RPC ServiceException caught: " + jre);
        }

        // Time out after a minute
        theBinding.setTimeout(60000);

        // Send a simple text fax using the InterFax sendCharFax() web service method.
        System.out.println("Sending Fax using sendCharFax()");
        SendCharFax theParams = new SendCharFax(TestConstants.USERNAME,
              TestConstants.PASSWORD,
              TestConstants.FAX_NUMBER,
              "This is a test fax message.",
              "TXT");

        SendCharFaxResponse theResponse = theBinding.sendCharFax(theParams);

        long theReturnCode = theResponse.getSendCharFaxResult();
        System.out.println("sendCharFax() call returned with code: " + theReturnCode);
    }

    public static void main(String[] anArgs) {
        try {
            new SendCharFaxTest().run();
        } catch(Exception theE) {
           System.out.println("Error encountered while running SendCharFaxTest:");
           theE.printStackTrace();
        }
     }
}

We'll again add a target to our ANT build script so we can run this test program using ANT.

<target name="run-send-char-fax-test" depends="dist" description="Test that makes a SendCharFaxTest call" >
    <java classname="SendCharFaxTest">
       <arg value="-h"/>
       <classpath>
         <pathelement location="dist/Interfax.jar"/>
         <pathelement path="${build}/test/"/>
         <pathelement path="${java.class.path}"/>
         <path refid="compile.classpath"/>
       </classpath>
    </java>
</target>

When you run this test, you should see output similar to the output below indicating a successful fax transmission.

$ ant run-send-char-fax-test
Buildfile: C:\workspace\InterfaxJavaTutorial\build.xml
init:
code.generation:
[axis-wsdl2java] - Unable to find required classes (javax.activation.DataHandler and javax.mail.internet.MimeMultipart). Attachment support is disabled.
[axis-wsdl2java] WSDL2Java https://ws.interfax.net/DFS.asmx?WSDL
[axis-wsdl2java] Parsing XML file:  https://ws.interfax.net/DFS.asmx?WSDL
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\CancelFileUpload.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\ReSendFaxResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendfaxEx_2Response.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\GetSupportedFileTypes.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\Sendfax.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendfaxEx_2.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\IsSupportedFileTypeResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatusXML.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxQueryResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\HideFaxResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendCharFaxResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxItem.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatus.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\CancelFileUploadResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendfaxEx.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatusExResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatusResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\HideFax.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxItemEx.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\GetFaxImage.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxQuery.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\IsSupportedFileType.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatusXMLResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\GetFaxImageResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendCharFax.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\UploadFileChunk.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\FaxStatusEx.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendfaxResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\SendfaxExResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\GetSupportedFileTypesResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\StartFileUpload.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\StartFileUploadResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\UploadFileChunkResponse.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\ReSendFax.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\InterFaxSoap.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\InterFaxSoapStub.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\InterFax.java
[axis-wsdl2java] Generating C:\workspace\InterfaxJavaTutorial\generated\cc\interfax\www\InterFaxLocator.java
compile:
    [javac] Compiling 38 source files to C:\workspace\InterfaxJavaTutorial\build\dist
    [javac] Note: Some input files use unchecked or unsafe operations.
    [javac] Note: Recompile with -Xlint:unchecked for details.
    [javac] Compiling 2 source files to C:\workspace\InterfaxJavaTutorial\build\test
dist:
      [jar] Building jar: C:\workspace\InterfaxJavaTutorial\dist\Interfax.jar
run-send-char-fax-test:
     [java] - Unable to find required classes (javax.activation.DataHandler and javax.mail.internet.MimeMultipart). Attachment support is disabled.
     [java] Sending Fax using sendCharFax()
     [java] sendCharFax() call returned with code: 45196105
BUILD SUCCESSFUL
Total time: 18 seconds

Full documentation for SendCharFax can be found online here: SendCharFax API documentation.

If you need to send a PDF document, or a Microsoft Word document, you would not use the sendCharFax() method. Instead, you would use an alternate method, like sendFax(). We'll demonstrate how to do this below.

SendFaxTest

Faxing a PDF document with the sendFax web service method is much the same as faxing a character data using sendCharFax, except that we're sending a binary file which we manipulate as an array of bytes. We'll create and use a utility method to get the byte[] representation of the file we're going to fax, then simply hand this representation to our Axis-generated SOAP stub which will send it out as a fax message.

import cc.interfax.www.Sendfax;
import cc.interfax.www.SendfaxResponse;

public class SendFaxTest {

    public void run() throws Exception {
        cc.interfax.www.InterFaxSoapStub theBinding;
        try {
           theBinding = (cc.interfax.www.InterFaxSoapStub)
                        new cc.interfax.www.InterFaxLocator().getInterFaxSoap();
        }
        catch (javax.xml.rpc.ServiceException jre) {
            if(jre.getLinkedCause()!=null)
                jre.getLinkedCause().printStackTrace();
            throw new RuntimeException("JAX-RPC ServiceException caught: " + jre);
        }

        // Time out after a minute
        theBinding.setTimeout(60000);

        // Encode the File.
        byte[] theFileData = TestUtils.transformToBytes(TestConstants.PDF_FILENAME);

        System.out.println("Sending Fax using sendFax().  Document size: " + theFileData.length);

        Sendfax theParams = new Sendfax(TestConstants.USERNAME,
                TestConstants.PASSWORD,
                TestConstants.FAX_NUMBER,
                theFileData,
                "PDF");
        SendfaxResponse theResponse = theBinding.sendfax(theParams);
        System.out.println("sendFax() call returned with code: " + theResponse.getSendfaxResult());
    }

    public static void main(String[] anArgs) {
        try {
            new SendFaxTest().run();
        } catch(Exception theE) {
           System.out.println("Error encountered while running SendFaxTest:");
           theE.printStackTrace();
        }
     }
}

Here's the utility method TestUtils.transformToBytes that does basic Java IO to get a byte[] representation of a specified file.

public static byte[] transformToBytes(String aFilename)
    throws Exception {

    if(null==aFilename) {
        throw new NullPointerException("aFilename is null");
    }
    File theFile = new File(aFilename);
    if(!theFile.isFile()) {
        throw new IllegalArgumentException("Path doesn't represent a file: " + aFilename);
    }
    if(!theFile.exists()) {
        throw new IllegalArgumentException("File not found: " + aFilename);
    }

    InputStream theIs = new BufferedInputStream(new FileInputStream(theFile));
    ByteArrayOutputStream theRawData = new ByteArrayOutputStream();

    byte theBuffer[] = new byte[1024];
    int theBytesRead;

    try {
        while((theBytesRead=theIs.read(theBuffer)) != -1) {

            //System.out.println("read: " + theBytesRead + " bytes.");

            if( theBytesRead < 1024 ) {
                byte theSlice[] = new byte[theBytesRead];
                System.arraycopy(theBuffer, 0, theSlice, 0, theBytesRead);
                theRawData.write(theSlice);
            } else {
                theRawData.write(theBuffer);
            }
        }
    } finally {
        theIs.close();
        theRawData.close();
    }

    return theRawData.toByteArray();
}

You can run this test of the SendFax method like we've run the previous test--by adding an ANT task to run it or by running it like any Java class with a main() method.

Full documentation for SendFax can be found online here: SendFax API documentation.

These examples should be enough to get you started with the InterFax Web Services API. The API itself does much more than what has been shown in this tutorial and you can study the online documentation learn more: http://www.interfax.net/en/dev/webservice/index.html. You will see that you can send multiple faxes at once, schedule fax transmission for a later time, decorate your faxes with page headers, query for the status of your fax submissions, and lots more. All of these features are very easy to access because you have already generated a stub class to call all of the InterFax web service methods using the same approach we've used in the examples above. The code bundle that goes along with this tutorial has examples of how to use many of the API methods not described in this tutorial, it's a great place to look for more detail.

If you find that you need additional help with your Java programs that use the InterFax web service, you can post to the developer forums online: http://forum.interfax.net/viewforum.php?id=2.




About | Contact | Privacy | Terms | Partners | Login | System Status

© Interfax Inc