Welcome Serena Central users! CLICK HERE
The migration of the Serena Central community is currently underway. Be sure to read THIS MESSAGE to get your new login set up to access your account.

Tutorial: Reusing Existing COBOL Programs in a Java Web Services Environment

Tutorial: Reusing Existing COBOL Programs in a Java Web Services Environment

Introduction

With the advent of the World Wide Web and modern programming languages such as Java, the on-going importance of COBOL is sometimes misunderstood in today's culture of mobile technology. This tutorial shows how you can protect the investment in your COBOL business logic in a low-cost, risk-free manner.

Tutorial Project Goals

The goal of this tutorial is to show you how to invoke an existing COBOL program in a Java environment.

In this tutorial, you will learn how to:

  • Install supplementary software for the server runtime and web projects.
  • Obtain the COBOL and Java tutorial files.
  • Compile a legacy COBOL program in an Eclipse project.
  • Create the various Java components in the dynamic web project that drives the COBOL program.
  • Configure Java to recognize the COBOL JVM runtime.
  • Run and debug both the COBOL and Java elements using Eclipse.

Skills Requirements

To succeed with this tutorial, you need a basic understanding of COBOL and Java programming. A good knowledge of the Eclipse IDE will help. See Introduction to Eclipse in the product Help.

Audience

This tutorial is intended for COBOL programmers who wish to modernize their legacy systems using Java in a web-based environment.

System Requirements

Before running this tutorial, you need to have the following software installed:

  • A Java Enterprise Edition server. The tutorial explains how to obtain and install a server.

Expectations

On completion of this tutorial, you will have gained experience of using Enterprise Developer for Eclipse to compile, run and debug a COBOL program in a web-based Java environment, thereby assisting you to modernize your current systems. In addition, you will have an understanding of the workings of the Micro Focus Run Unit Manager and the Micro Focus smart linkage facility.

Setting Up the Tutorial Environment

Before you can run the tutorial, you must download and install some additional software and the tutorial files. The following sections describe the tasks you need to perform to do this. Once you complete these tasks, the tutorial is ready to use.

Installing a Java Server

You install a Java Enterprise Edition (JEE) server or servlet container so that the Micro Focus JVM COBOL runtime, under which your COBOL program runs, may be mapped to the server. Subsequently, your COBOL program is accessible in that environment.

Enterprise Developer includes the Web Tools Platform (WTP), which is a component of Eclipse that is designed for the creation of web applications. In particular, it has support for the JEE stack. Micro Focus COBOL JVM projects can interact with the WTP to expose COBOL functionality in JEE Web services.

Upon completion of the Java server installation, you will have the ability to create a dynamic web project.

Before You Begin

Determine which Java server or servlet container to install. You need install only one, and you need to choose which server best suits your requirements. The Micro Focus JVM COBOL runtime supports many of these: refer to the Application server support for JVM COBOL section of the Additional Software Requirements topic in your product Help.

Note: The server selected might require a specific version of Java to run correctly. See Additional Software Requirements for more information.

If you are new to Java, Micro Focus recommends that you choose Apache Tomcat, as it is a lightweight, open-source servlet container.

Support for other servers is also included, but is not detailed here. If you wish to install an alternate server, you will need to refer to the external supplier's documentation. In addition, you may need to configure your projects differently.

Your projects must target that same Java version used by the server you choose. By default, this tutorial uses Java 8 which is provided with Enterprise Developer:

  • Installing Apache Tomcat. This section details the steps you take to install Apache Tomcat version 7.
  • Installing JBoss Enterprise Application Platform. This section details the steps you take to install JBoss Enterprise Application Platform (EAP).
  • Installing the IBM WebSphere Plug-in. This section details the steps you take to install the IBM WebSphere server plug-in.
  • Installing the Oracle WebLogic Plug-in. This section details the steps you take to install the Oracle WebLogic server plug-in.

Installing Apache Tomcat

This section details the steps you take to install Apache Tomcat version 7.

Procedure:

  1. Create a new folder on your computer, for example, C:\Tomcat (Windows) or ~/tomcat/ (UNIX).
  2. You need to install Apache Tomcat - click here to download the software. If the link fails, do a web search for "apache tomcat 7 download".
  3. Navigate to the Binary Distributions - Core section and click on 32-bit Windows zip or 64-bit Windows zip depending on your OS, .zip (Windows), or .tar.gz (UNIX).
  4. Extract the distribution files into the folder created in step 1.
    Note: Ensure that the option to retain folder names is selected.

On UNIX and Linux platforms no further action is required at this stage, but on Windows you need to register the service. Do this by taking the following steps:

  1. Launch a command prompt (cmd.exe) with administrator privileges.
  2. Change to the bin folder of your Apache Tomcat installation, for example, C:\Tomcat\InstalledVersionPath\bin, where InstalledVersionPath is the folder name of the installed version from the zip file.
  3. Before you run the next command, you need to set either of these environment variables: JRE_HOME or JAVA_HOME. Micro Focus suggests that you set JRE_HOME, and ensure that it points to your Java Runtime Environment (JRE) folder. Typically, in a 32-bit system, the command is:
    set JRE_HOME=C:\Program Files (x86)\Java\jre7
    Note: Ensure that the file path is not enclosed in quotation marks.
  4. Register the service with the command:
    service.bat install

Installing JBoss Enterprise Application Platform

This section details the steps you take to install JBoss Enterprise Application Platform (EAP).

Download and install JBoss

  1. In a browser, open the 3.3. DOWNLOAD AND INSTALL JBOSS EAP USING THE ZIP page located on the Red Hat Web site.
  2. Follow the instructions provided to download and install the Red Hat JBoss Enterprise Application Platform. See Additional Software Requirements in your product Help for a list of supported versions.
    Note: Ensure that the file path is not enclosed in quotation marks.

Install JBOSS tools plugins in Eclipse

To enable Eclipse to manage JBoss Application Server, you need to install the JBoss tools plugin in Eclipse:

  1. Start Eclipse.
  2. Click Help > Eclipse Marketplace.

    This opens the Eclipse Marketplace dialog box.

  3. In the Find field, type JBoss Tools, and then press Enter.
  4. Find the JBoss Tools 4.5.3.Final plugin in the returned results list, and then click Install.
  5. In the Confirm Selected Features page, click Confirm.
  6. Accept the license agreement, and then click Finish.

    If you receive a security warning, click Install anyway.

  7. When prompted to restart Eclipse, click Restart Now.
    Note: If this is the first time the workspace settings have been changed then Eclipse might prompt you to store preference information.

Install JBOSS AS tools in Eclipse

To enable Eclipse to manage JBoss Application Server, you need to add the server runtime environment:

  1. Click Window > Preferences > Server > Runtime Environments.
  2. Click Add.

    This opens the New Server Runtime Environment dialog box.

  3. Expand Red Hat JBoss Middleware, and then click Red Hat JBoss Enterprise Application Platform 7.1 Runtime.
  4. Click Next.

    This opens the New Server Runtime Environment dialog box.

  5. Next to the Home Directory field, click Browse, and then select the folder containing JBoss EAP.
  6. Click OK.
  7. Ensure that you are using a Java 8 JRE runtime.
  8. Click Finish.
  9. Click Apply and Close.

Installing the IBM WebSphere Plug-in

The Eclipse Web Tools Platform (WTP) has support for only a limited number of deployment targets by default. To enable the use of IBM WebSphere with JVM COBOL Web services, you need to install a plug-in, which is available via the Eclipse Marketplace. To install the plug-in:

  1. Launch an instance of Eclipse.
  2. Click Help > Eclipse Marketplace.
  3. In the Find field, type IBM WebSphere Application Server and press Enter.
  4. Click Install next to the adapter called IBM WebSphere Application Server v8.5 Developer Tools for Oxygen.
  5. On the Confirm Selected Features page, click Confirm.
  6. On the Review Licenses page, accept the license agreement, then click Finish.

    The WebSphere Developer Tools are installed for Eclipse.

  7. Click Yes when prompted to restart Eclipse, to finish the installation.

You now have the ability to create a dynamic web project, which links to an IBM WebSphere server instance.

Note: This is not a full installation of IBM WebSphere; it simply allows you to enable WebSphere with JVM COBOL Web services. The full installation of IBM WebSphere is beyond the scope of this tutorial.

Installing the Oracle WebLogic Plug-in

The Eclipse Web Tools Platform (WTP) has support for only a limited number of deployment targets by default. To enable the use of Oracle WebLogic with JVM COBOL Web services, you need to install a plug-in, which is available via the Eclipse Marketplace. To install the plug-in:

  1. Launch an instance of Eclipse.
  2. Click Help > Eclipse Marketplace.
  3. In the Find box, type WebLogic and press Enter.
  4. Click Install next to the adapter called Oracle WebLogic Server Tools.
  5. On the Confirm Selected Features page, uncheck Oracle WebLogic Scripting Tools, and ensure Oracle WebLogic Server Tools is selected.
  6. Click Confirm.
  7. On the Review Licenses page, accept the license agreement, then click Finish.

    The WebSphere Developer Tools are installed for Eclipse.

  8. Click Restart Now when prompted to restart Eclipse, to finish the installation.

You now have the ability to create a dynamic web project, which links to an Oracle WebLogic server instance. If you cannot see the dynamic web project option, click Show All Wizards in the new project window. The software installation can sometimes disable certain project options, but you can enable them this way.

Note: This is not a full installation of Oracle WebLogic; it simply allows you to enable WebLogic with JVM COBOL Web services. The full installation of Oracle WebLogic is beyond the scope of this tutorial.

 Copying the Tutorial Files

To download your sample files:

  1. Create a folder to contain the sample files, for example, C:\myfiles (Windows) or ~/myfiles/ (UNIX).
  2. To download the sample files, click Download at the top of this tutorial.
  3. Extract all the files in the archive to the folder that you created in step 1.
    Note: The archive contains folder names for the tutorial files. You do not have to keep these folder names, as you will be creating the project from the start.

Creating the COBOL Components

You now have a Java server and the tutorial files. In this section you learn how to build the COBOL components in a JVM COBOL project:

Creating the JVM COBOL Project

First you need to create a project to contain the procedural COBOL program, and make it available for execution from a Java program:

  1. Start Enterprise Developer for Eclipse.
  2. When prompted for the workspace name, type the name of a folder into which you wish to store the tutorial project, for example, C:\projects (Windows) or ~/projects/ (UNIX).
  3. If you are presented with the Welcome page, click Open Team Developer Perspective.
  4. In the Application Explorer view, expand the Enterprise Developer node and click Enterprise Development Projects.
  5. Click File > New > Other.

    This opens the New dialog box.

  6. Click Micro Focus COBOL > COBOL JVM Project.
  7. Click Next.

    This opens the New COBOL JVM Project dialog box.

  8. Type CobolBook in the Project name field.
  9. In the JRE section, select a Java 8 JRE. If Java 8 JRE is not already available, click Configure JREs and add one.
  10. Click Finish.

This creates a JVM COBOL project to contain the sample procedural COBOL program that you will import into the Web application later in this tutorial.

Specifying a Java package

By default, COBOL programs are placed in the default root Java package. JVM servlet containers do not always allow root package classes to be loaded, so you must set up a package for the program.

Note: The Java package system is equivalent to the JVM COBOL namespace system; these two terms are interchangeable.

To set up the package:

  1. In the Application Explorer view, right-click the CobolBook project, and click New > Folder > COBOL JVM Package.

    This opens the New COBOL JVM Package dialog box.

  2. In the Name field, type com.microfocus.book and then click Finish to create the package.

    Note: To see the new folder structure in the Application Explorer view:

    1. Click View Menu > Filters and Customzation.

      This opens the Filters and Customization dialog box.

    2. Uncheck Empty folders outside categories.
    3. Click OK.

This process creates a folder structure in the workspace, in which to store the COBOL program, and informs Java where to find it. You are now ready to set up the COBOL program.

Creating the Copybook File

In this section you create a COBOL copybook. This file is created from the sample archive file that you downloaded previously.

  1. In the Application Explorer view, right-click the CobolBook project, and click New > File > COBOL Copybook.
  2. Ensure that the Containing project field contains CobolBook/src.
  3. In the New file name field, type book-rec.cpy, and then click Finish to create the copybook.
  4. Replace the contents of the opened file with the downloaded copy of book-rec.cpy.
  5. Click File > Save.

Creating the COBOL Program

In this section you create a COBOL program. This file is created from the sample archive file that you downloaded previously:

  1. Right-click the CobolBook project in Application Explorer view, and click New > File > COBOL Program.
  2. Ensure that the Source folder field contains CobolBook/src.
  3. Ensure that the Package field contains com.microfocus.book.
  4. Type book.cbl in the Name field. Click Finish to create the COBOL program.
  5. The file opens in the COBOL editor view with some skeleton text. Replace the entire contents of the program with the downloaded copy of book.cbl.
  6. Click File > Save. The project is built.

In addition to building the project, the compilation generates a class file, BookLegacy.class, which interacts with Java, and is located in the bin folder.

The bin folder is not the correct location, and, as such, the program will not execute successfully. You need to correct this problem by setting the COBOL Compiler directives.

Setting the COBOL Compiler Directives

The ILNAMESPACE Directive

COBOL Compiler directives are statements that determine how the program is compiled and behaves. To ensure that the program in the tutorial executes as expected, you need to set these. To do this, you need to:

  • Alter the program to specify the correct namespace as a qualified program name.
  • Alternatively, set a Compiler directive, either globally to the project or in the program using the $SET syntax.

For this tutorial you set a global Compiler directive.

You need to specify the ILNAMESPACE directive to ensure that you put the program in the right folder structure, and use the right package. When you import the program into Java, the namespace will then interact correctly with Java packages.

Procedure:

  1. In the Application Explorer view, right-click the CobolBook project, and then click Properties.
  2. Click Micro Focus > Build Configuration.
  3. Uncheck Each part of the package name corresponds to a subdirectory.
  4. In the Additional directives field, type:
    ilnamespace(com.microfocus.book)
  5. Click Apply and Close.

    The project is rebuilt.

Checkpoint:

This time, the COBOL program is built in the specified namespace. Observe that the file, BookLegacy.class, is now located in the bin/com/microfocus/book folder.
 

 The ILSMARTLINKAGE Directive

In addition, you need to specify the ILSMARTLINKAGE directive to ensure that the linkage between the COBOL program and the Java code is handled correctly. The Micro Focus SmartLinkage tool converts between traditional COBOL group item types and Java types. For example, a field defined as PIC X(99) will be exposed as a Java STRING, and a COMP-5 field will become a Java int. This feature makes calling COBOL programs from Java much easier.

Procedure:

  1. Repeat the steps you performed to specify the ILNAMESPACE directive, only this time add the following as another new line in the Additional directives field:
    ilsmartlinkage
  2. Click Apply and Close.

    The project is rebuilt.

Checkpoint:

You will see additional files in bin/com/microfocus/book. These are LnkBDetails.class, LnkFilename.class, and LnkFileStatus.class. These are classes generated to represent the linkage items in the book.cbl program. The BookLegacy.class file will now have an entry point that takes these wrapper classes rather than just taking a generic reference class that gives direct byte access.

The ILCUTPREFIX Directive

Micro Focus recommends that you specify the ILCUTPREFIX directive. You use this directive to remove any prefixes that may be present in COBOL linkage section data-names. This feature ensures legibility in the generated code.

If you open book.cbl and press F4, you can see the contents of the copybooks in this program. If you navigate down to the linkage section there are group items lnk-filename, lnk-file-status, and lnk-b-details. These map directly onto the generated classes mentioned above.

Procedure:

  1. Repeat the steps you performed to specify directives, only this time add the following lines in the Additional directives field:
    ilcutprefix(lnk-b-)

    and:

    ilcutprefix(lnk-)
  2. Click Apply and Close.

    The project is rebuilt.

Checkpoint:

Observe the class files in bin/com/microfocus/book. These files are now called Details.class, BookLegacy.class, and FileStatus.class. Note that the prefixes LnkB and Lnk are no longer present in the class filenames.

The JVMDECIMAL Directive

You need to specify the JVMDECIMAL directive. You use this directive to ensure that COBOL decimal data type is treated as an integer numeric item. The use of this directive is a result of specifying the ILSMARTLINKAGE directive.

Procedure:

  1. Repeat the steps you performed to specify the ILNAMESPACE directive, only this time add the following as another new line in the Additional directives field:
    jvmdecimal(scaledinteger)
  2. Click Apply and Close.

    The project is rebuilt.

Adding the Data File

The sample program, book.cbl, reads an indexed file to satisfy its I/O requests. You need to add this file to the project. It is located in the archive file that you downloaded previously.

Procedure:

  1. In the Application Explorer view, right-click the CobolBook project, and then click Import.

    This opens the Import dialog box.

  2. Expand General, and click File System. Click Next.
  3. Click Browse against the From directory field to locate the folder containing the bookfile.dat file, for example, C:\myfiles\COBOL_JSP_2_2_SRC\CobolBook (Windows), or /home/myfiles/ (UNIX). Click OK.
  4. Ensure that the entry for bookfile.dat is the only checked item. Click Finish.

    The file is added to the project.

This section completes the creation of the COBOL project.

Creating the Java Components

Previously, you created a number of components in a COBOL JVM project. You are now ready to create your first Web application using Java, and specifically using Java Server Pages (JSP). In this section you learn how to build the Java components in a dynamic web project. In addition, you learn how to incorporate the COBOL components into the dynamic web project.

Understanding Run Units and Sessions

Before you delve into the fundamentals of Web applications, you need to understand the concept of Micro Focus run units and sessions.

Many COBOL applications are single-user programs, so adapting these programs into a multi-user Java environment can be problematic. You may experience a problem such as file locking or memory isolation breaking down because the same resource set is being used by many users. Often, fixing this contention requires a significant rewriting of code.

Micro Focus solves this with a construct called a run unit, and is specified by the JVM COBOL runtime class com.microfocus.cobol.runtimeservices.RunUnit. Each run unit is a new session object, and contains its own memory space and file lock table. A JVM COBOL program in one run unit will not normally access the memory of a program in another run unit. There is isolation between them. In addition, file locks are held for each run unit. If a program in one run unit holds a file lock, it will not be accessible to a file handling program in another run unit in the same process.

This feature is implemented using the concept of a Run Unit Manager. Each manager controls the life-cycle of run unit objects in Java environments with a notion of a session. A manager:

  • Creates a run unit when a session starts.
  • Retrieves a run unit already attached to a session.
  • Ensures that a run unit is stopped and its resources cleaned up when a session ends.

The class com.microfocus.cobol.runtimeservices.servlet.ServletRunUnitManager in the JVM COBOL runtime exists to handle the life-cycle of run units in the context of servlet API HttpSession objects.

Creating the Dynamic Web Project

Create a new project

As you will be using features such as servlets and JSP files in this tutorial, you need to create a dynamic web project to contain these resources. This is in contrast to a static web project that does not contain any dynamic content:

  1. Click File > New > Other.
  2. Expand the Web node and select Dynamic Web Project. Click Next.
  3. Enter JSPBookDemo in the Project name field.
  4. Ensure Use default location is selected.
  5. In the Target runtime field, either select an already existing servlet container runtime, or, if you have <None> showing, set one up as follows:
    1. Click New Runtime.
    2. You now need to choose the runtime of the Java servlet that you installed previously, then click Next:
      • Tomcat - Expand Apache, and select Apache Tomcat v7.0.
      • JBoss - Expand Red Hat JBoss Middleware, and select Red Hat JBoss Enterprise Application Platform 7.1 Runtime.
      • IBM - Select WebSphere Application Server v8.5 or later.
      • Oracle - Select Oracle WebLogic Server 12.1.1 or later.
    3. In the Home Directory (or Tomcat installation directory) field, click Browse and choose the location where you installed the servlet for Apache Tomcat, JBoss or IBM WebSphere, or enter the installation path for Oracle WebLogic.
    4. For Apache Tomcat or IBM WebSphere, select an appropriate JRE (usually the same one as the project).
    5. Click Finish.
  6. Set the Dynamic web module version to 2.5.
  7. Click Finish.

    Open the Java EE perspective if prompted to do so; all commands involving JSPBookDemo will be expected in the Java EE perspective.

Add appropriate references to the JVM COBOL project

You need to add a reference to the COBOL project in both the build options, so that the Java compiler can find the appropriate classes to build against, and in the deployment assembly, so that the JVM COBOL program will be exported into the created Web archive. To do this:

  1. In the Project Explorer, right-click the JSPBookDemo project, and then click Properties.
  2. Click Java Build Path, and then click the Projects tab.
  3. In the Required projects on the build path list, click Classpath.
  4. Click Add.

    This opens the Required Project Selection dialog box.

  5. Check the CobolBook project, and then click OK.
  6. Click the Libraries tab.
  7. In the JARs and class folders on the build path list, click Classpath.
  8. Click Add Library.

    This opens the Add Library dialog box.

  9. Click COBOL JVM Runtime System, and then click Next.
  10. Click Finish.
  11. Click Apply.
  12. While you are still in the properties for JSPBookDemo, click Deployment Assembly.
  13. Click Add, then select Project, and click Next.
  14. On the next page click CobolBook, and then click Finish.

    This adds an entry to the Web Deployment Assembly list to indicate that the CobolBook project classes are included in the WEB-INF/lib directory of the Web archive. The project is also built.

  15. Click Add, then select Java Build Path Entries, and then click Next.
  16. On the next page, select COBOL JVM Runtime System, and then click Finish.
  17. Click Apply and Close to exit the project's properties dialog box. Once again, the project is built.

With these steps you created a dynamic Web project that incorporates your COBOL project.

Creating a JSP View

Java Server Pages (JSPs) are a technology used to create dynamically generated web pages based on HTML, XML, or other document types. The standard way to create a view in a JSP application is to have a JSP that takes a Java bean, which is an ordinary Java data class, as an attribute. The JSP then inserts the properties from that bean into the appropriate places in the output HTML.

In this tutorial you now create a JSP view to map the book application:

  1. Expand the JSPBookDemo project, right-click the WebContent node, and click New > JSP File.
  2. Type BookJsp.jsp in the File name field.
  3. Click Finish.
  4. Overwrite the skeleton contents of the file with the BookJsp.jsp file that you downloaded previously (located in C:\myfiles\COBOL_JSP_DEMO_2_2_SRC\JSPBookDemo\WebContent).
  5. Click File > Save.

Comments

Examine the BookJsp.jsp file, and you will see several variables, which are elements that start with a $ sign and are enclosed in braces, for example ${book.stockno}. The example variable states that the JSP will insert the value contained in the stockno property of the book attribute at this point.

There are also other non-book variables, an example of which is ${rununitid}. These variables are more direct text attributes that are not directly related to a book entry, and are kept separate. In the case of ${rununitid}, the program is demonstrating its use in the title of the display.

Once all the variables have been processed, the JSP becomes a simple HTML page containing a form.

Creating the Java Bean

You now create a Java bean, which is associated with the view that you have just created:

  1. In Project Explorer, right-click Java Resources in the JSPBookDemo project, and select New > Class.
  2. Type com.microfocus.book in the Package field, and BookBean in the Name field.
  3. Click Finish to create the BookBean class file.
  4. Overwrite the skeleton contents of the file with the contents from the BookBean.java file that you downloaded previously (the file is stored in C:\myfiles\COBOL_JSP_DEMO_2_2_SRC\JSPBookDemo\src\com\microfocus\book).
  5. Click File > Save.

Comments

A bean is used to separate the business logic from the presentation logic, and a bean is simply an instance of a class. This class contains the information that will be displayed in the JSP view.

In this tutorial, at run time, the dispatching servlet binds an appropriate bean to the attribute "book" before calling the JSP. For example, in the book.stockno variable that was created previously in the JSP file, the JSP invokes the getStockno method on BookBean, and inserts the return value into the JSP output.

Converting Status Codes to Exceptions

Error handling in Java is different from procedural languages such as COBOL. Java uses exceptions, as opposed to error codes or status codes, to deal with failure and unexpected conditions. As the COBOL book tutorial program returns a status code, you need to convert this status code into a Java exception to make it suitable for the JVM:

  1. Create a new Java class using the same package as the bean, but call it JavaBookException.

    If you cannot remember how to create a new class, refer to the previous topic, Creating the Java Bean.

  2. Change the Superclass to java.lang.Exception.
  3. Click Finish to create the file.
  4. Overwrite the skeleton contents of the file with the contents of the JavaBookException.java file that you downloaded previously (the file is stored in C:\myfiles\COBOL_JSP_DEMO_2_2_SRC\JSPBookDemo\src\com\microfocus\book).
  5. Click File > Save.

Comments

In this Java code sample, note that there is a constructor that takes a string:

public JavaBookException(String statusCode)

The following string maps the file status field in the COBOL program:

01 ls-file-status   pic xx.

Using this statusCode construct, the Java program translates known COBOL status codes to appropriate error messages via its Map<String, String> construct, with a static string for any unknown error. Finally, the error exception is passed to the superclass constructor, and the status code is stored internally.

Note: The element serialVersionUId is used by the Java serialization mechanism to distinguish between different versions of a class, and it has no impact on the program.

Creating a Session Management Class

This part of the tutorial details the most relevant class for invoking a JVM COBOL program from a JSP Web application. This class handles session management and integration into a Java environment. It also handles the interaction between the view bean (BookJsp.jsp) and the COBOL program's smart details linkage class, which was generated when you used the ILSMARTLINKAGE compiler directive previously:

  1. Create a new Java class as before. Put it in the com.microfocus.book package, and give it the name BookInterface.
  2. Overwrite the skeleton contents of the file with the BookInterface.java file that you downloaded previously (the file is stored in C:\myfiles\COBOL_JSP_DEMO_2_2_SRC\JSPBookDemo\src\com\microfocus\book).
  3. Click Edit > Find/Replace to find the BOOK_FILE definition:
    private static final String BOOK_FILE =
  4. Change the path to match the location of the bookfile.dat file that you downloaded previously.
    Note: Windows users must use a forward slash to delineate folder names; using a back slash results in an error.
  5. Click File > Save.

Specifying the Java Build Path

To ensure that the BookInterface.java does not contain errors you need to add the COBOL JVM runtime system library and the CobolBook project to the build path. To do this:

  1. In Project Explorer, right-click the JSPBookDemo project, and then click Properties.

    This opens the Properties for JSPBookDemo dialog box.

  2. Click Java Build Path, and then click the Projects tab.
  3. Click Add.

    This opens the Required Project Selection dialog box.

  4. Click CobolBook.
  5. Click OK.
  6. Click the Libraries tab, and then click Add Library.

    This opens the Add Library dialog box.

  7. Click COBOL JVM Runtime System, and then click Next.
  8. Click Finish.
  9. Click Apply and Close.

Comments

The sample code contains some important concepts, which are explained here. Note the two constructors listed below:

    
  public BookInterface(HttpSession session)
  {
    this(ServletRunUnitManager.getManager().GetSessionRunUnit(session));
  }
  
  public BookInterface(IRunUnit runUnit)
  {
    this.runUnit = runUnit;
    BookLegacy bookLegacy = (BookLegacy) runUnit.GetInstance(BookLegacy.class);
    
    if(bookLegacy == null)
    {
      bookLegacy = new BookLegacy();
      runUnit.Add(bookLegacy);
    }
    
    this.bookLegacy = bookLegacy;
  }

These constructors handle two separate functions:

  • The first constructor deals with the servlet's HTTP session object (HttpSession) and its run unit manager (ServletRunUnitManager).
  • The second constructor handles the linking of this interface class to a run unit, and gets the program instance of BookLegacy.

The interaction here is: get the ServletRunUnitManager (which is a singleton) and then call GetSessionRunUnit with the session object. The manager will create a run unit if this is the first call with this particular session. It will also manage the shutdown handling routines, so that when this session is invalidated the manager will call StopRun on the run unit attached to that session. In summary, this short section of code manages both program isolation and session life cycles.

Note also that the function parameter has been split into separate method calls:

public BookBean readBook(String stockNo) throws JavaBookException
public BookBean addBook(BookBean book) throws JavaBookException
public BookBean deleteBook(String stockNo) throws JavaBookException
public BookBean nextBook(String stockNo) throws JavaBookException

This style ensures compact and discrete functions, and is good coding practice.

Creating the Servlet

The servlet is the final Java class that you need to create for this tutorial. The servlet interprets the incoming POST and GET requests, and dispatches them to the correct interface method. The servlet also binds the output BookBean into the request, and forwards that request to the JSP for response:

  1. Create a new Java class as before. Put it in the com.microfocus.book package, and give it the name BookServlet.
  2. Overwrite the skeleton contents of the file with the BookServlet.java file that you downloaded previously (the file is stored in C:\myfiles\COBOL_JSP_DEMO_2_2_SRC\JSPBookDemo\src\com\microfocus\book).
  3. Click File > Save.

Comments

As before, the sample code contains some important concepts, which are explained here. There are four significant parts to the servlet class.

The interpretation of the POST parameters

The doProcessing method includes the following code:

    String subValue = req.getParameter(SUBMIT_PARAMETER);

    ...
      
    if(subValue.equals(READ_PARAMETER))
    {
      performRead(req, res);
    }
    else if(subValue.equals(ADD_PARAMETER))
    {
      performAdd(req, res);
    }
    else if(subValue.equals(DELETE_PARAMETER))
    {
      performDelete(req, res);
    }

This code interprets the value of the submit parameter from the request object, and invokes the appropriate method in the application for each known request. An example of one of the methods is performRead, and is explained next.

The resulting calls into BookInterface

The performRead method contains the following code:

    BookInterface bookInterface = getBookInterface(req.getSession());
    String bookId = getStockNo(req, res);
    
    try
    {
      BookBean book = bookInterface.readBook(bookId);
      
      outputBook(req, res, book);
    }
    catch(JavaBookException e)
    {
      outputBookException(req, res, e);
    }
    catch (Exception e)
    {
      outputException(req, res, e);
    }

This code defines a BookInterface class by passing the session object from the request object to the constructor of BookInterface.java. Then it gets the stock number from the request parameters, and makes a call to readBook on the interface. Finally, it registers the BookBean object with the JSP by calling outputBook.

Binding an output BookBean into the request attributes

The outputBook method includes the following code:

private void outputBook(HttpServletRequest req, HttpServletResponse res,
      BookBean book)
    if(book != null)
    {
          req.setAttribute("book", book);
    }
    else
    {
          req.setAttribute("book", BookBean.msgBook("ERROR! book is null in output book"));
    }

This method binds the book as a request attribute to our JSP view, namely BookJsp.jsp. The JSP unpacks this book object and outputs its values.

Forwarding the request onto the JSP so it can create the response

The doProcessing method also contains the following code:

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(VIEW_URL);
    try
    {
      dispatcher.forward(req, res);
    }
    catch(Exception e)
    {
      throw new RuntimeException(e);
    }

This method gets a dispatch object for the JSP view, and then forwards the request to it. With all the necessary attributes set up, the JSP view can output the book record correctly.

The Servlet Deployment Descriptor

The deployment descriptor is the file used by the servlet container to define which servlets match up with which URLs. It also defines which servlet or resource provides the landing page for the root of the service.

If it doesn't already exist, create the file web.xml in the JSPBookDemo project:

  1. Expand WebContent, right-click the WEB-INF folder in Project Explorer, and then click New > File.
  2. Type web.xml in the File name field, and click Finish.
    Note: If Finish is greyed out, check for the message 'web.xml' already exists, and click Cancel. Expand WEB-INF to locate the file.
  3. Open the file, and ensure it is in source mode by clicking the Source tab at the bottom left side of the XML Editor window.
  4. Overwrite the skeleton contents of the file with the web.xml file that you downloaded previously (the file is in C:\myfiles\COBOL_JSP_DEMO_2_2_SRC\JSPBookDemo\WebContent\WEB-INF). Perform this task even if the file exists.
  5. Save the file.

This is a deployment descriptor with the following elements:

<web-app>

    Defines the specific version of the servlet API in use.

<display-name>

    Defines the internal name of this web application that will appear in the servlet container management system.

<servlet>

    Binds a name to a particular servlet class, in this case BookServlet.

<servlet-mapping>

    Binds a particular servlet to a URL from the root of the servlet. As such, any call to localhost:8080/JSPBookDemo/view, for example, is directed to BookServlet.

<welcome-file-list>

    Defines a set of files to use as the landing page for the servlet. In this case, the view is set to be the landing page.

Running and debugging

Run the application

Now that you have created and built the COBOL and Java programs in Eclipse projects, you can run the completed application.

To run the application:

  1. Ensure that you are in the Java EE perspective.
  2. Right-click on JSPBookDemo, and click Run As > Run on Server.

    Eclipse displays a window containing the servlet containers it knows about.

  3. Select the one you want to deploy to, which in this case is Apache Tomcat v7.0 Server, and click Finish.

    This action launches the servlet container, builds the Web application, and deploys it to the server. It then opens a Web page displaying the application.

  4. To test it, type 1111 in the Stock Number field, and click Read.

If you have followed the instructions carefully, and built the projects correctly, the system will respond by displaying the book Oliver Twist by Charles Dickens. If so, click End Session and proceed to the debug task.

If, for some reason, the application fails to deploy, you will need to retrace your steps and re-check what you have done. It may be necessary to start from the beginning.

Debug the application

Having successfully run the sample application, you can now use the debugger to control the execution of both the Java and COBOL code by setting breakpoints, step through the code, and examine the contents of variables.

  1. While in the JavaEE perspective, set some break points in the source files by double-clicking in the left hand margin of the editor next to a line you want to stop at. For example:
    • Set a break point in BookServlet.java in the performRead function.
    • Set another in BookInterface.java in the readBook method.
    • Set a third in book.cbl in the do-read-record section.
  2. To launch the debugger, right-click on the JSPBookDemo project, and click Debug As > Debug on Server.
  3. If you are debugging immediately following running the application, the server is already running, and you need take no action. Otherwise, select the one you used for running the application previously. Click Finish.
  4. If you are asked to switch modes, click OK to do so.

    The web interface appears.

  5. Type 1111 in the Stock Number field, and click Read.
  6. Click Yes to confirm perspective switch.

    If you have set the break points as instructed, the debugger will stop in BookInterface.java in the readBook method.

  7. Press F6 to step through line by line.
  8. Press F8 to resume execution. The debugger stops at the break points that you selected, and eventually switches from Java code into the COBOL program.
  9. Press F6 to step over the open instruction.
  10. Hover over ls-file-status to examine its value.
  11. Click Run > Terminate to stop the session.

You have now completed the tutorial.

Summary

In this tutorial you have learned how to add a COBOL program to an Eclipse project, and build the program with appropriate compiler directives for use in a web-based environment. You then learned how to incorporate this COBOL project into a dynamic web project, in which you created a JSP and a bean as a view of the COBOL program. In addition, using the Micro Focus session management class you learned how to create a Java interface class to the COBOL program, a servlet and a deployment descriptor to drive the COBOL program in a web-based environment. Finally, you learned how to debug both the COBOL and Java code in Eclipse.

Attachments

DISCLAIMER:

Some content on Community Tips & Information pages is not officially supported by Micro Focus. Please refer to our Terms of Use for more detail.
Version history
Revision #:
1 of 1
Last update:
‎2018-11-13 05:50
Updated by:
 
The opinions expressed above are the personal opinions of the authors, not of Micro Focus. By using this site, you accept the Terms of Use and Rules of Participation. Certain versions of content ("Material") accessible here may contain branding from Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company. As of September 1, 2017, the Material is now offered by Micro Focus, a separately owned and operated company. Any reference to the HP and Hewlett Packard Enterprise/HPE marks is historical in nature, and the HP and Hewlett Packard Enterprise/HPE marks are the property of their respective owners.