04
Mon, Nov
1 New Articles

Discover the Missing Link to RPG and Java

Java
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Much has been written and discussed about Java and its interoperability with RPG legacy applications. With Java spreading faster than office gossip and the AS/400 able to run Java and host Web sites, the content of these articles, white papers, and discussions grows increasingly important. Fortunately, developers concerned with providing Web-based business applications while keeping the back-end business rules of RPG have received good news concerning RPG communication with Java and, subsequently, the Internet.

However, two problems have come out of this information. One is that the technology related to Java seems to be a moving target. Just as you decide which technology to implement, something better and faster comes along. I realize that this is common in the IT industry as a whole, but it occurs even faster with Java. The other problem is that, because so many potential solutions are available to solve RPG-Java interoperability, developers have no time to test which ones might work the best. Therefore, before you make your decision, you should consider things such as portability, speed, and ease of implementation. One tool that fits these criteria is sockets.

Sockets 101

A socket is basically an endpoint, a port that can be addressed in a network. You can use sockets to communicate with other sockets in a communication area. This area can be as large as the Internet or as small as any two points that can connect using TCP/IP. You can even use sockets to communicate between programs on the same machine, something I have done using RPG and Java on the AS/400.

I chose sockets to solve my interoperability dilemma because they meet my selection criteria. First, sockets are portable; they are part of Java’s core API and go everywhere Java goes. No extra toolkit or extensions are necessary to implement them. I even compiled and ran a Java Socket client servlet on the AS/400 to communicate with an RPG Socket host on the same AS/400. I then moved the servlet to a Windows/NT server; the servlet worked just as well with the Socket host on the AS/400. Second, sockets are fast. How fast? Well, results may vary, but I consistently get my desired data in less than a second. As for my third criterion, ease of implementation, you will soon see that implementing Socket classes in a Java program is very easy.

The Example

Figure 1 shows a Java servlet using Socket classes. This is a simple servlet that throws a Web page after sending a request to a socket and receiving an answer back. I’ll touch briefly on what makes this Java code a servlet but won’t go into too much detail about servlets. (Don Denoncourt’s article from the August issue of MC, “Serving Up Host-based Java Apps,” does that nicely.) Label A of Figure 1 shows the import statements required for servlets. The code marked by Label B is the remainder of code that really makes this a servlet.

I’ve created a class called testServlet, which inherits, extends, or is a child of (pick your term) class HttpServlet. The servlet engine calls the doGet method based on the URL request. The doGet method requires two parameters. The first parameter, HttpServletRequest, contains information about the request, and the second parameter, HttpServletResponse, houses the dynamically generated HTML response. The socket client starts at the code in Label C.

A lot is going on here, but you wouldn’t know it from the code. First, you need to declare the Socket objects you are going to use. In my example, I’ve declared the Socket object as testSocket, the PrintWriter object as toServer, and the BufferedReader object as fromServer. The Socket object defines the host and port number; PrintWriter sends requests to the socket; and BufferedReader receives information from the socket. Once the objects are declared, they are instantiated at the three lines marked by Label D. The testSocket object is set to a new socket with the TCP/IP address or host name of the server from which you are requesting information and to which the Socket host code will run. The port number (3004 in this case) is the remote port that listens for the request, and the client uses any local port it can bind to. The toServer object instance of the PrintWriter class contains the request to the socket, and the fromServer object contains information received from the Socket host. The fromServer object is constructed a little differently from testSocket and toServer because Sun recommends wrapping the InputStreamReader into BufferedReader for performance. Who am I to argue with Sun?

Next is to send the request to the socket and wait for the response. Label E denotes the two lines of code that accomplish that. In this example, I am sending the string “My test message” to the Socket host and waiting for a response, which I am storing in the string named temp. The fromServer object waits for the response before going to the next line of code that displays the response on the Web page. The last thing to do in testServlet is to close the socket connections; Label F shows the code for doing that.

The Java Host Socket Class

Now, I’ll take a look at the Java host Socket class. Label G shows the entire myHost class, which is a separate class and not part of the Socket client servlet. I’ve coded both the Socket host and the Socket client classes as part of testServlet.java. When you compile this Java code, you create two classes: testServlet.class and myHost.class. You don’t have to do it this way; I did it for simplicity. What’s interesting about coding them in the same source member is that the two classes may run on different machines. (You’ll have to excuse my excitement, but, for an RPG-learning-Java programmer like me, this is pretty cool.)

OK, back to myHost. You first declare ServerSocket and Socket classes, instantiating the ServerSocket class to port 3004. The accept method waits for a connection request from a client to the host and port of your server (in this example, port 3004). When you request and successfully establish a connection, the accept method returns a new Socket object bound to a new local port. The server can then communicate with the client over this new socket and continue to listen for client connection requests on the ServerSocket bound to port 3004. After the request is accepted, it is read by using the readLine method, which returns the request to the clientData object. In my example, the request reads “My Servlet Test Page.” You then append the string “- Success” to the

clientData object and send that string back to the client through a new port. Finish by closing the socket connections.

To run the servlet and have it communicate successfully with a host socket, you must first run the myHost class on the AS/400. You can run myHost interactively by using the RUNJVA or JAVA command, or you can submit the RUNJVA command to batch by using Submit Job (SBMJOB). As soon as myHost is running on the AS/400, you can load your servlet to whatever Web application server you’re using. I used WebSphere on the AS/400 for my example. When the servlet is loaded, bring up your browser and type the URL to your server, followed by the /servlet/ directive and name of your servlet (i.e., http://MyServer/servlet/testServlet). If all goes well, you should see a Web page similar to the one in Figure 2 with the message “My Test Servlet Page - Success.”

A Recipe for E-business Success

By understanding how to implement sockets in RPG and Java, you possess a powerful tool that allows interoperability between the two. (See “TCP/IP Socket Programming in RPG? Cool!” MC, February 1999.) Add servlets and their dynamic Web pages into the mix, and you’re well on your way to a full-fledged e-business solution that takes advantage of your legacy applications on the AS/400. For more information on the Socket classes available in Java, visit Sun’s tutorial site at www.java.sun.com/docs/books/tutorial/networking/Sockets/index.html.

Author’s Note: I would like to thank Java programmer extraordinaire Will Houck of Boise Cascade Office Products, who provided me with much-needed code examples, some Java training, and a little HTML.

References

• “Lesson: All About Sockets,” The Java Tutorial: www.java.sun.com/docs/ books/tutorial/networking/sockets/index.html
• ”Serving Up Host-based Java Apps,” Don Denoncourt, MC, August 1999
• “TCP/IP Socket Programming in RPG? Cool!” Jim D. Barnes, MC, February 1999

Related Material

OS/400 Sockets Programming V4R4 (SC41-5422-03, CD-ROM QB3ANN03)

A B

C

D

E

import javax.servlet.http.*;
import javax.servlet.*;

import java.io.*;
import java.net.*;
import java.lang.String.*;

public class testServlet extends HttpServlet {

//Handle the HTTP GET method by building a simple web page.
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, UnknownHostException {

// Set the content type first
response.setContentType("text/html");

PrintWriter htmlOut = response.getWriter();
String title = "My Servlet Test Page";
String temp = null;

Socket testSocket = null;
PrintWriter toServer = null;
BufferedReader fromServer = null;

testSocket = new Socket("YourServer", 3004);
toServer = new PrintWriter(testSocket.getOutputStream(), true);
fromServer = new BufferedReader(new InputStreamReader(
testSocket.getInputStream()));

// Write the response headings
htmlOut.println("" + title + "" +

"

" + title + "

");

toServer.println("My test message");
temp = fromServer.readLine();

}

class myHost {
public static void main(String[] args) throws IOException,

UnknownHostException,
ClassNotFoundException {

ServerSocket hostSocket = new ServerSocket(3004);
Socket clientSocket = null;
String clientData = null;
String hostData = null;

clientSocket = hostSocket.accept();

PrintWriter toClient = new PrintWriter(
clientSocket.getOutputStream(), true);
BufferedReader fromClient = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));

clientData = fromClient.readLine();
hostData = clientData + " - Success!";

toClient.println(hostData);

toClient.close();
fromClient.close();
clientSocket.close();
hostSocket.close();
}

}

htmlOut.println("

" + temp + "

");

toServer.close();
fromServer.close();
testSocket.close();

F

G

}

Figure 1: Servlets dynamically construct HTML to communicate with Web users and can communicate with legacy applications through Java's simple Sockets API.




Figure 2: A servlet responds to remote requests from URLs and HTML form submissions.



Discover_the_Missing_Link_to_RPG_and_Java04-00.png 600x400
BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: