java barcode reader library PrintWriter in Java

Maker Quick Response Code in Java PrintWriter

PrintWriter
Drawing Denso QR Bar Code In Java
Using Barcode printer for Java Control to generate, create QR Code ISO/IEC18004 image in Java applications.
QR Code 2d Barcode Recognizer In Java
Using Barcode reader for Java Control to read, scan read, scan image in Java applications.
outprintln("<head><title>TracerServlet</title></head>"); outprintln("<body>"); outprintln("<H1>"+enum+" <BR>"); outprintln((enum / denom) + "</H1>"); outprintln("</body>"); outprintln("</html>"); outclose(); } catch (Exception ex) { traceLogexception(RASITraceEventTYPE_ERROR_EXC, this, "doGet", ex); } if (traceLogisLoggable(RASITraceEventTYPE_ENTRY_EXIT)) { traceLogexit(RASITraceEventTYPE_ENTRY_EXIT, "doGet"); } } } this, divided by "+denom+" is:
Bar Code Encoder In Java
Using Barcode encoder for Java Control to generate, create bar code image in Java applications.
Scan Barcode In Java
Using Barcode decoder for Java Control to read, scan read, scan image in Java applications.
Log Analyzer While the logs and traces generated by JRas are readable by humans, WebSphere also provides a graphical log-analyzing tool The Log Analyzer, shown in Figure 21-3, takes one or more activity or trace logs, merges all the traces, and then displays all entries grouped under UnitOfWork (UOW) elements It is important to note that the Log Analyzer cannot parse message logs; these logs can have arbitrary formats, as their content is controlled by resource bundles and is subject to localization
Paint QR Code In Visual C#
Using Barcode drawer for .NET Control to generate, create Quick Response Code image in Visual Studio .NET applications.
Quick Response Code Generator In .NET Framework
Using Barcode encoder for ASP.NET Control to generate, create QR image in ASP.NET applications.
Figure 21-3: Viewing merged trace information in the Log Analyzer The main Log Analyzer window includes three panes in addition to the standard status bar, toolbar, and menu bar On the left side of the window, the sorting pane shows the list of log records, which by default are grouped according to their Units of Work Each UOW has a folder icon, under which all trace records associated with it are shown Records without UOW identification are grouped under a single folder in this tree The UOW folders are sorted according to their timestamps, the most recent appearing at the top of the tree Similarly, entries within a UOW are shown in reverse order Note that the time ordering is done after the Log Analyzer merges entries from several files (if several files are loaded) You can sort your log records on a field other tha n UOW by making a different selection in the Analyzer Preferences dialog box (see Figure 21-4) Here you can choose to group your files by process ID, thread ID, server name, or function name, among other options
Painting QR-Code In VS .NET
Using Barcode creation for .NET framework Control to generate, create QR Code 2d barcode image in .NET applications.
Quick Response Code Creation In Visual Basic .NET
Using Barcode maker for VS .NET Control to generate, create Quick Response Code image in .NET applications.
Figure 21-4: Setting sorting sequence using the Analyzer Preference dialog box Trace records are color coded for quick identification, as summarized in the following table You can modify these colors in the Analyzer Preferences dialog box by selecting the General option in the left pane and setting the appearance values
Data Matrix 2d Barcode Printer In Java
Using Barcode maker for Java Control to generate, create Data Matrix 2d barcode image in Java applications.
Code-128 Drawer In Java
Using Barcode maker for Java Control to generate, create Code 128B image in Java applications.
Severity Level 1 2 3
Painting 1D In Java
Using Barcode printer for Java Control to generate, create Linear image in Java applications.
UPC-A Supplement 2 Printer In Java
Using Barcode drawer for Java Control to generate, create GTIN - 12 image in Java applications.
Selected Pink Yellow White
Generating USPS PLANET Barcode In Java
Using Barcode encoder for Java Control to generate, create Planet image in Java applications.
Create European Article Number 13 In None
Using Barcode encoder for Online Control to generate, create EAN 13 image in Online applications.
Nonselected Red Green Blue
EAN13 Generation In .NET Framework
Using Barcode creation for Reporting Service Control to generate, create European Article Number 13 image in Reporting Service applications.
Generating EAN13 In Java
Using Barcode generation for Android Control to generate, create EAN13 image in Android applications.
The other two panes in the main Log Analyzer window are the record pane and the analysis pane The record pane shows a detailed description of the selected record, providing all information recorded The analysis window shows additional information in case you invoke the Analyze function (under the Record menu) and there exists some additional information to display Such additional information can be symptoms identified by the Log Analyzer from a database of common WebSphere errors Note that after the Analyze function is applied, each analyzed record entry on the tree has a small indicator icon attached to it The meaning of each icon follows:
Recognize UPC Symbol In Java
Using Barcode recognizer for Java Control to read, scan read, scan image in Java applications.
Code 128 Encoder In VB.NET
Using Barcode encoder for .NET framework Control to generate, create Code 128A image in .NET framework applications.
Icon
Generating UPC-A Supplement 2 In None
Using Barcode generator for Excel Control to generate, create UCC - 12 image in Office Excel applications.
Code 128 Code Set C Maker In Objective-C
Using Barcode encoder for iPhone Control to generate, create Code-128 image in iPhone applications.
Meaning Some analysis information is available in the Analysis window Some analysis information is available in the Analysis window, but 366
Icon
Meaning this entry is related to a problem that has occurred previously You might want to consult previous log files to diagnose the problem The entry is of severity 1 or 2, but it has no analysis information The entry is of severity 3, but it has no analysis information
Summary This chapter, which described the logging and tracing capabilities available in WebSphere and the JRas toolkit, concludes Part IV of this book We now move on from discussing the core services that are available as part of the WebSphere Application Server to examining the constructs with which applications are developed for deployment on WebSphere Part V addresses servlets and JavaServer Pages (JSPs) in WebSphere, and Part VI addresses Enterprise JavaBeans (EJB) Both of these sections focus on the application frameworks and the support available to you as a developer
Part V: Developing Servlets and JavaServer Pages List 22: HTTP Servlets 23: Servlet Sessions 24: WebSphere-Specific Servlet Issues 25: JSP Elements 26: JSP Examples 27: Custom Tag Libraries 28: Debugging Servlets and JSPs Using VisualAge
22: HTTP Servlets Overview Now that you are familiar with servlets and how they work (having gone over servlet lifecycle and seen a simple "Hello World" example), you are ready to tackle the next stage This chapter presents three examples of the most common servlets, Hypertext Transfer Protocol servlets, which are accessed through an HTTP connection The purpose of this chapter is twofold: to show you some real-world examples of how servlets are usually used and to give you experience using WebSphere servlets Each example illustrates an end-to-end process, including the generation of some form of user interface and access to data stored in a mail server or relational database management system (RDBMS)
The Mail Reading Servlet The first example in this chapter is an implementation of a real-world Web-based service that allows users to read e-mail over the Web, using a Web browser (as opposed to using an e-mail program such as Microsoft Outlook) Such services are available for free on the Web for example, a t wwwmail2webcom To allow our sample mail reading service to be available from any Web browser, we build an HTTP servlet to service mail requests Our HTTP servlet will receive the e-mail request, access a Post Office Protocol 3 (POP3) mail server to check for mail, and return some user interface for viewing the mail This servlet makes use of the JavaMail application programming interface (API), which is part of the Java 2 Platform Enterprise Edition (J2EE) and was introduced in 15 Our servlet uses four different parameters for the e-mail user name, POP3 server, POP3 password, and operation (which is used by the servlet to identify the requested operation) The operation parameter can either be absent or take the value detail for retrieving the message body Servlet parameters appear in the servlet uniform resource locator (URL), and can be accessed through the HttpServletRequest object Here is the servlet code: package bookwebspherechapter22; import javaxmail*; import javaxservlet*; import javaxservlethttp*; import javautil*; import javaio*; public class MailReader extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { performTask(request, response); }
public void doGetMail(HttpServletRequest req, HttpServletResponse resp) { PrintWriter pw = null; try { pw = respgetWriter(); } catch (Exception ex) { return; } try { String userName = reqgetParameter("username"); String pop3 = reqgetParameter("pop3"); String password = reqgetParameter("password"); session = SessiongetInstance (SystemgetProperties(),null); store = sessiongetStore("pop3"); storeconnect(pop3, userName, password); folder = storegetFolder("INBOX"); folderopen(FolderREAD_ONLY); messages = foldergetMessages(); respsetContentType("text/html"); pwprintln("<HTML><HEAD><TITLE>Your" + "Mail</TITLE></HEAD><BODY><TABLE>" + "BORDER=\"1\"><TR>");
pwprintln("<TH>From</TH><TH>Date</TH><TH>Subject</TH>"); for (int i = 0; i < messageslength; i++) { pwprintln("<TR><TD>" + messages[i]getFrom()[0] "</TD>"); pwprintln("<TD>" messages[i]getSentDate() + "</TD>"); pwprintln("<TD><A HREF='" + reqgetRequestURI() + " operation=detail&msgnum=" + i + "'>" + messages[i]getSubject() + 370 + +
"</A></TD></TR>"); } pwprintln("</TABLE><P><A HREF='" + HttpUtilsgetRequestURL(req) + " operation=logoff'>" + "Log-Off</A></P></BODY></HTML>"); pwclose(); } catch (Exception ex) { exprintStackTrace(pw); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { performTask(request, response); } public void performTask(HttpServletRequest request, HttpServletResponse response) { try { String operation = requestgetParameter("operation"); String userName = requestgetParameter("username"); if (operation == null) { if (userName == null) sendOutPage(responsegetWriter()); else doGetMail(request, response); } else if (operationequals("detail")) { doGetDetail(request, response); } else if (operationequals("logoff")) { doLogoff(request, response); } } catch(Exception ex) { 371
exprintStackTrace(); } } public void sendOutPage(PrintWriter pw) { pwprintln("<HTML><HEAD><TITLE>Mail Reading " + "Servlet</TITLE></HEAD>"); pwprintln("<BODY><H1>Welcome to the Mail"+ " Reading Servlet</H1>"); pwprintln("<FORM ACTION=" + "'http://yourhost/ch22/MailReader'"+ "METHOD='GET'>"); pwprintln("<B>Username: </B><INPUT TYPE='TEXT'" + "NAME='username'><BR>"); pwprintln("<B>POP3 Server: </B> " + "<INPUT TYPE='TEXT' NAME='pop3'><BR>"); pwprintln("<B>Password: </B><INPUT TYPE='TEXT'" + "NAME='password'><BR>"); pwprintln("<INPUT TYPE='SUBMIT'><INPUT" + "TYPE='RESET'></FORM></BODY></HTML>"); } private Folder folder; private Message[] messages; private Session session; private Store store; public void doGetDetail(HttpServletRequest req, HttpServletResponse resp) { PrintWriter pw = null; try { pw = respgetWriter(); } catch (Exception ex) { return; } try { int num = IntegerparseInt( 372
reqgetParameter("msgnum")); String s; Message msg = messages[num]; respsetContentType("text/html"); pwprintln("<HTML><HEAD><TITLE>Reading Message:" + msggetSubject() + "</TITLE>"); pwprintln("</HEAD><BODY><B>From:</B>" + msggetFrom()[0]); pwprintln("<B>To:</B>" + msggetRecipients(MessageRecipientTypeTO)[0]); pwprintln("<B>Date:</B>" + msggetSentDate()); pwprintln("<P>"); BufferedReader rd = new BufferedReader(new InputStreamReader(msggetInputStream())); while ((s = rdreadLine()) != null) pwprintln(s); pwprintln("</P></BODY></HTML>"); pwclose(); } catch (Exception ex) { exprintStackTrace(pw); } } public void doLogoff(HttpServletRequest req, HttpServletResponse resp) { try { folderclose(false); storeclose(); } catch (Exception ex) { } } } When no operation parameter and no user name are provided, the program assumes this is the first access to the servlet and sends out an initial login page The login page, shown here, is a simple Hypertext Markup Language (HTML) form into which the parameters can be keyed in 373
Once the Submit Query button is clicked, the same servlet is invoked again On this second invocation, the servlet already has a user name (provided as a request parameter) Using the JavaMail API, the servlet connects to the POP3 server and downloads the user's e -mail Using the Session Object The Session object is accessed using the SessiongetInstance method Note that it is possible to provide this method with a Properties parameter This parameter can be used for specifying the protocols or implementations you are interested in This example opts for the default properties, which are fine as long as no special settings exist on your system; the files in which such settings reside are javamailproviders, javamaildefaultproviders, javamailaddressmap, and javamaildefaultaddressmap Note that the getInstance method has another parameter not used in this example an authenticator This parameter can be used for advanced authentication schemes intended to improve e-mail security The Session interface also provides the method getDefaultInstance, which provides access to a default (and shared) session instance With the Session object at hand, the program retrieves a Store object for the POP3 protocol Invoking the connect method of the store with the appropriate parameters (the server, user name, and password) allows the servlet to retrieve the INBOX folder from the store After the Folder object has been opened, the e-mail messages are retrieved using the getMessages method The incoming e-mail is shown in a table, where each incoming message takes one row The information for each row is based on a single Message object The message accessor methods are used to retrieve the e-mail sender, date, and subject An HTML link is provided from the message subject to the message body This link is used to obtain the details of the e-mail message and requires another round-trip to the server To construct the original URL of the request (including all the parameters), the method getRequestURL, taken from the class javaxservlethttpHttpUtils, is used This class provides some static utility methods that come in handy for writing HTTP servlet code The following illustration shows a table of incoming e-mail, provided as output by the server after the form data has been posted Notice that this is just an example; in a real mail reader, no one would display the user's password on a URL
The Configuration Servlet The second example is taken from the world of hierarchical parts configurations This example displays a configuration of a complex piece of machinery This machinery is composed according to a hierarchical structure, in which each part may be broken down into a set of smaller parts, which themselves may be broken down into yet smaller parts Since most people can see only so many details at a time, almost all objects in the real world are broken down into such hierarchical structures Each level is manageable in its own right, and the observer can decide at which level the part(s) should be viewed For example, computer hardware is composed of the motherboard, the network card, the disk, and so on The motherboard is further broken down into the CPU, the memory chips, the controller, and so on Just like computer hardware, software is also composed of parts: modules, procedures, and functions Such a hierarchical view is not limited to information technology (IT)-related issues Everything from projects, to power plants, to aircraft, to cities practically everything is maintained in some hierarchical structure Such a breakdown is usually maintained in a database of some sort, and we, as programmers, are asked to provide a view of this configuration Obviously, we want to display this information as a hierarchy and the best way to do this is to use a tree widget Given some data model representing a hierarchical structure, we are asked to build a Web-enabled interface that will display the hierarchies as trees in a browser This will allow anyone having access to our Web site (and authorized to do so) to view the configurations in a convenient manner Since we need to provide this service from any browser, we will build an HTTP servlet to service these requests The HTTP servlet will receive the request, access the data in the database, and return some user interface to display the hierarchical information Before we begin, a couple of decisions need to be made What will the server model be This part is quite simple (especially after we've seen the title of this chapter) The best fit is an HTTP servlet (surprise, surprise) In this example, we will build a servlet that will accept GET requests Upon receiving such a request (along with a set of parameters required to identify the root of the configuration), the servlet will access the database and get the information regarding the entire tree It will then write this information to the output stream Next question: How should we write the information Should we write it as straight HTML That would be pretty ugly Maybe we can put it in an HTML table and indent the lines based on the depth in the tree That would be slightly better but not by much 375
Actually, since we were asked to provide a dynamic user interface, we need some code to be passed to the browser so that the tree can be displayed and manipulated (that is, its nodes collapsed, opened, and so on) Our selection is therefore much narrower: we can either go with a combination of JavaScript and Dynamic HTML (DHTML) or with a Java applet Since the subject of this book is tightly coupled with Java technology, we'll opt for the latter Then comes the fun part Being lazy in nature, whenever we need to write some code, we always spend a little time on the Web looking for examples we can borrow from or even for code to buy After spending half an hour (isn't the Web great ), we come up with a list of 10 applets that perform precisely the tasks we need After spending a little more time comparing the available packages, we zoom in on a package called Advanced Tree Explorer, available at http://wwwjpoweredcom/tree This is a superb applet that is small, fast, pleasant to look at, and easy to use So we download it (or a 30-day evaluation version) and read the instructions, which takes less than 15 minutes, and we are ready to go Initializing the Servlet First, we build the servlet class and the init method of the servlet, as shown here: package bookwebspherechapter22; import javaxservlet*; import javaxservlethttp*; import javaio*; import javautil*; import javasql*; import javatext*; public class ConfigServlet extends HttpServlet { static ResourceBundle aBundle = null; static String serialFormat; static String nonSerialRootFormat; static String serialRootFormat; static String nonSerialFormat; static String bgImage = ""; static String codebase; static String fontString; public void init(ServletConfig config) throws ServletException { superinit(config); aBundle = ResourceBundlegetBundle("ConfigServlet"); serialFormat = aBundlegetString("serialFormat"); nonSerialFormat = aBundlegetString("nonSerialFormat"); serialRootFormat = aBundlegetString("serialRootFormat"); nonSerialRootFormat = 376
aBundlegetString("nonSerialRootFormat"); codebase = aBundlegetString("codebase"); fontString = aBundlegetString("font"); bgImage = aBundlegetString("bgImage"); DBConnectioninit( aBundlegetString("dburl"), aBundlegetString("dbuser"), aBundlegetString("dbpass")); try { Connection conn = DBConnectiongetConnection(); CallableStatement stmt = connprepareCall( "alter YYYY'" ); stmtexecute(); stmtclose(); } catch (Throwable ex) { exprintStackTrace(); } } session set NLS_DATE_FORMAT = 'DD MON
The init method will be called whenever the servlet is loaded that is, when the application server is started Because our servlet accesses the database, we need to create a connection to the database Given the fact that creating a connection takes time (it is actually one of the operations that consumes the longest amount of time to perform), it makes sense that we open the connection during servlet startup (when no users are waiting on this operation) We also do other things that need to happen only once, such as reading the property files and setting all constants to be used later in the actual processing Note that the database connection is performed through a simplistic connection class, which is shown next Normally, when using WebSphere, you use a connection retrieved from a connection pool, as opposed to having the servlet manage the connections This functionality is covered at length in 18
package bookwebspherechapter22; import javasql*; public class DBConnection { static Connection conn = null; static String aURL; static String aUserName; static String aPassword; 377
public static void init(String url, String userName, String password) { // Load the JDBC driver if (conn == null) { try { DriverManagerregisterDriver(new oraclejdbcdriverOracleDriver()); } catch (Exception e) { Systemerrprintln("Could not load driver "); eprintStackTrace(); } aURL = url; aUserName = userName; aPassword = password; } } public static Connection createConnection() { try { // Establish the connection to the database conn = DriverManagergetConnection(aURL, aUserName, aPassword); } catch (Exception e) { Systemerrprintln("Could not create connection " + egetMessage()); eprintStackTrace(); conn = null; } return conn; } public static Connection getConnection() { Connection toRet = null; if (conn == null) toRet = createConnection(); else toRet = conn; return toRet; } 378
} This example uses the Java Database Connectivity (JDBC) thin driver from Oracle; make sure your WebSphere server has access to this class either by having the JDBC driver registered as a JDBC Resource in the Administrator console or by updating the classpath of the Web module you are using for deploying this servlet If you don't perform either of these actions, you will get an exception while trying to register the servlet with the application server Of course, if you're using a different database, the respective JDBC driver should be used Servicing the Request The next step is to build the method that will do all the work Since we want the service to be available in the most flexible way, we implement the doGet method of the servlet This method accepts a number of arguments from the request object and proceeds to build the configuration tree The code for the method is shown here: public void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { responsesetContentType("text/html"); PrintWriter out (responsegetOutputStream()); = new PrintWriter
String nodeKey = requestgetParameter("nodeKey"); String rootSerialId = requestgetParameter("serialsT"); String rootPartId = requestgetParameter("partId"); String rootPartDesc = requestgetParameter("partDesc"); String rootRevision = requestgetParameter("rev"); String quantity = requestgetParameter("qty"); outprintln("<html>"); outprintln("<head><title>Configuration View</title></head>"); outprintln("<body>"); outprintln("<applet code=\"TreeApplet\" width=\"250\" height=\"300\"" + "archive=\"Treemenujar\">" outprintln("<param name=\"nodeOffset\" value=\"25\">"); outprintln("<param name=\"image1\"" + "value=\"closed|/IconImages/closedfoldergif\">"); outprintln("<param name=\"image2\" + "value=\"open|/IconImages/openfoldergif\">"); outprintln("<param name=\"image3\" + "value=\"document|/IconImages/documentgif\">"); 379
Stack displayStringStack = new Stack(); Stack levelStack = new Stack(); String rootName = formatRootBySerial( rootPartId,rootPartDesc, rootRevision, rootSerialId); outprintln("<param name=\"node1\" value=\"conf|root|" + rootName + "|Helvetica|N|10|0|0|0|true|closed |open"); displayStringStackpush(rootName); levelStackpush(new Integer(1)); // Build the tree in the database and read it in // rs is the result set object returned from the // database query holding the nodes that need to // go into the tree structure while (rsnext()) { // read in the data per row and place it in variables // to be used in the following code // then, based on the level and the values on the stack // decide where in the tree the node belongs if (configLevel == atTop) { String itemString = "item" + IntegertoString(itemNum++); String dispString ((String)displayStringStackpeek()) + "/" + dString; outprintln("<param name=\"" + itemString + "\" value=\"" + dispString); } else if (configLevel < atTop) { while (configLevel < ((Integer)levelStackpeek())intValue()) { displayStringStackpop(); levelStackpop(); } String itemString = "item" + IntegertoString(itemNum++); String dispString ((String)displayStringStackpeek()) + "/" + dString; 380 = =
outprintln("<param name=\"" + itemString + "\" value=\"" + } else { dispString); // configLevel > atop
String itemString = "item" + IntegertoString(itemNum++); String dispString ((String)displayStringStackpeek()) + "/" + dString; outprintln("<param name=\"" + itemString + "\" value=\"" + dispString); displayStringStackpush(dispString); levelStackpush(new Integer(configLevel)); } } stmtclose(); } catch (Throwable ex) { exprintStackTrace(); } outprintln("</applet>"); outprintln("</body></html>"); outclose(); } Note Some of the database access code is omitted because it is not of much interest here; it is sufficient that you understand that the arguments passed in through the request object are used to invoke a database operation that builds the tree The tree is then read from the database and used to produce the arguments to the applet =
The method starts by reading in the arguments sent to the servlet to determine what node forms the root of the configuration tree The servlet then proceeds to set the output stream's content type (an HTML page) and write out the applet tag The Advanced Tree Explorer applet receives the parameters affecting its display through a set of PARAM tags It also receives the data forming the tree using PARAM tags The servlet therefore needs to write to the output stream both the general display parameters (accomplished in the first part of the method) and the parameters encapsulating the data (the rest of the method) After the general parameters have been written, the database is accessed to get the nodes The database call returns the nodes in the order in which they should be displayed, as opposed to a tree ordering (such as a depth-first search or a breadth-first search) A stack object is used to build the tree structure, based on a config-level value marked in each of the rows returning from the database Then, a PARAM tag is added to the applet with a 381
name of nodeX, where X is incremented by 1 in each row The tree structure is attained by concatenating the complete path to each node name (The prefix is managed by the stack) The resulting HTML source for the example is as follows:
<html> <head> <title>Install Base Configuration</title> </head> <body> <applet code="TreeApplet" width="250" height="300" archive="Treemenujar"> <param name="nodeOffset" value="25"> <param name="image1" value="closed|/IconImages/closedfoldergif"> <param name="image2" value="open|/IconImages/openfoldergif"> <param name="image3" value="document|/IconImages/documentgif"> <param name="node1" Configuration|Helvetica| value="conf|root|Root
N|10|0|0|0|true|closed|open"> <param name="node2" value="serialeee|conf|Serial #EEE|Helvetica| <param name="node3" 2000|Helvetica| N|10|0|0|0|true|closed|open"> value="pentium|serialeee|Pentium IV
N|10|0|0|0|true|closed|document"> <param name="node4" value="modem|pentium|ADSL Modem|Helvetica| <param name="node5" Systems| <param supply| </applet> </body> </html> The corresponding Web page is shown here: name="node6" N|10|0|0|0|true|closed|document"> value="printer|serialeee|Printer for MF
Copyright © OnBarcode.com . All rights reserved.