Installing MySQL

after mysql is installed.

Configure MySQL databases

I’m going to simulate two different business entities (which is explained in detail at the beginning of part, Java EE Basics – Persistence, Query, and Presentation), so I need to create two separate databases and users on MySQL by running the following commands from MySQL

from MySQL Monitor:

create database store_db;

create database theater_db;

grant all on store_db.* to store_user@localhost identified by’store’;

grant all on theater_db.* to theater_user@localhost identified by’theater’;

flush privileges;



In case you are planning to connect from a machine or host other than localhost, change the command to:

grant all on store_db.* to store_user@’%’ identified by’store’;

grant all on theater_db.* to theater_user@’%’ identifiedby ‘theater’;

We’ve just created the users, the databases, and granted the corresponding access.

Now, to create and populate the data structures, we’re going to use the same command, but pass a script as the parameter for each database. From the command prompt run:

mysql -D store_db -u store_user -p < store_db.sql

mysql -D theater_db -u theater_user -p < theater_db.sql


Scripts store_db.sql and theater_db.sql can be saved for latter operations,

You should not see any error messages while the script is running. When the scripts end, the databases are configured and loaded with data.

Installing Oracle Enterprise Pack for Eclipse (OEPE)

The installation package we got doesn’t come bundled with a development environment (Oracle JDeveloper, NetBeans, or Eclipse/OEPE). To create the book’s applications, we decided to use Eclipse along with Oracle’s application server plugin, OEPE, which is a great tool for Java EE development, integrating the IDE with WebLogic Server and other Java EE application servers. Perform the following steps to install it:

Navigate to
Click on the option button for Accept License Agreement, choose the Eclipse version that runs on your system, and click on it to start the download.
After the download completes, unzip the installer in the directory $MW_HOME/oepe(C:\Oracle\Middleware\Oracle_Home\oepe) and it’s done.

OEPE’s newest version,, is based on Eclipse 4.3 Kepler, the most up-to-date version of Eclipse.

Installing Oracle WebLogic Server

Oracle WebLogic Server’s installation is pretty straightforward; you just need to pay attention to the Java SDK selection in order to use the one we just installed.

After the installation following variables are set up:

ORACLE_HOME = C:\Oracle\Middleware\Oracle_Home

Oracle Home, where the WebLogic Server binaries will be installed.

DOMAIN_HOME = C:\Oracle\Middleware\Oracle_Home\user_projects\domains\tickets

MW_HOME = C:\Oracle\Middleware\Oracle_Home

 If you are familiar with the previous versions of WebLogic, this is what was called Middleware Home, and earlier still, it used to be the BEA Home.

1. Open download page at
2.  Accept License Agreement by clicking the option button.
3. Right below the option box, there’s a drop-down list with five entries. Select the entry Generic WebLogic Server and Coherence installer (880MB) and click on the Download File button.
    Another option is to download the zip distribution; with barely one fifth the size of the generic installer, it includes all core artifacts, leaving out samples, the Derby database, and web server plugins, among other features. Also, there’s no way to apply patches to this installation.

    If bandwidth is a concern, go ahead and get this file instead of the generic one. Check the README.txt file inside the package for instructions on how to install and configure a domain—the steps described in this chapter don’t apply.
4. You will be redirected to a login page where you must enter your Oracle credentials (if you don’t have one yet, sign up for an account now; you just need to fill up a short form).
5. When the download is completed, execute the installer using the Java binary installed in the previous section:
/oracle/jdk1.7.0_21/bin/java/java -jar wls_121200.jar

The first step of the installation asks you to set up an inventory, which is the engine used by Oracle (along with OPatch) to apply upgrades and patches to its software. Enter /opt/packt/inventory as Inventory Directory, select a system group, and click on OK.

You may proceed and run the inventory script created in the folder you entered, or just go ahead and continue the installation process—we’re not going to apply any patches to the installation, so this step is optional.
Click on Next on the Welcome screen. Enter the installation directory for the software, /opt/packt/install, and click on Next. Note

The path you just entered is called Oracle Home, where the WebLogic Server binaries will be installed. If you are familiar with the previous versions of WebLogic, this is what was called Middleware Home, and earlier still, it used to be the BEA Home. In a nutshell, this folder is the root point where other Oracle products, such as SOA Suite, can be installed later, using the software that is already present as its starting point.

If you’re using Windows, remember to choose a folder name with no spaces in it. This is critical to run things smoothly.
On the Installation Type screen, you can choose between the default WebLogic Server Installation and Complete Installation; the difference between them is that the latter installs everything from the former plus the samples for both WebLogic and Coherence. Now click on Next.
The Prerequisite Checks screen does a basic validation of the environment, showing warning messages for those that don’t pass; for instance, if you’re using Ubuntu, which is not a certified platform, a warning is shown, and can be safely ignored. If no other warnings or errors are present, go ahead and click on Next.
You may want to register with Oracle Support in order to receive security updates. If you don’t want to, just uncheck the I wish to receive security updates via My Oracle Support option and click on Next.
A summary is presented. Go ahead and click on Install to start the installation process.

If this sequence is going to be repeated frequently, you can create a response file by clicking on the Save Response File button at the bottom of the summary tree, and execute a silent install later. Get a link to the official documentation in the Web resources section at the end of the chapter.
After it finishes, uncheck the Automatically Launch the Configuration Wizard checkbox and click on Finish to close the installer.

It is recommended to export an environment variable pointing to your WebLogic’s installation folder. Inside Oracle’s documentation and usually in real environments, this is referred to as MW_HOME (the middleware home). For example: export MW_HOME=/opt/packt/install. This is how we will refer to this folder from now on.

Installing JDK 1.7

Since Oracle WebLogic Server 12c offers support to both Java SE 6 and 7,
I’m going to use the newest version, so I can code using a few developer-friendly features,
such as the diamond operator and multicatch statements, as outlined in the The Project Coin section in Chapter 1, Overview of WebLogic Server 12c and Related Technologies.

This is the location of JDK

JAVA_HOME = C:\Program Files\Java\jdk1.7.0_65

Setting Up the Environment

Software required to implement and execute the code that we will be writing along the sample application. More specifically, I’m going to:

  • Install JDK Version 1.7, which will be used by the application server and the development environment
  • Install Oracle WebLogic Server and Eclipse OEPE binaries
  • Install a MySQL RDBMS server and configure a database
  • Create and configure a WebLogic domain
  • Configure the Eclipse IDE to recognize the WebLogic Server
  • Install and configure an OpenLDAP server


As I’ve dipped a toe into Java EE development and would now like to dive right in, then I need a guide.

This blog introduces the key components of WebLogic Server and all that’s great about Java EE 6.

  • Create a complete Java EE 6 application leveraging WebLogic features like JMS, SOAP and RESTful Web Services
  • Learn how to use Oracle WebLogic Server’s key components and features
  • Step-by-step instructions with screenshots and code samples to help understand and apply concepts
In Detail

Oracle WebLogic server has long been the most important, and most innovative, application server on the market. The updates in the 12c release have seen changes to the Java EE runtime and JDK version, providing developers and administrators more powerful and feature-packed functionalities.


Provides a practical, hands-on, introduction to the application server, helping alike get up to speed with Java EE development, using the Oracle application server.

Starting with an overview of the new features of JDK 7 and Java EE 6, this guide quickly moves on to showing you how to set up a WebLogic development environment, by creating a domain and setting it up to deploy the application.

Once set up, we then explain how to use the key components of WebLogic Server, showing me how to apply them using a sample application that is continually developed throughout the chapters. On the way, we’ll also be exploring Java EE 6 features such as context injection, persistence layer and transactions.

After the application has been built, I will then learn how to tune its performance with some expert WebLogic Server tips.

Ternary operator

In addition to the if and switch statements there is the ternary operator (?:). This operator can replace a single if/else clause that assigns a value to a specific variable. The operator takes three expressions. If the first one is evaluated to true then the second expression is returned, and if it is false, the third one is returned.

// Value between 0.0 and 1.0
double x = new System.Random().NextDouble();
x = (x < 0.5) ? 0 : 1; // ternary operator (?:)

switch Multiple-Selection Statement

We discussed the if single-selection statement and the ifelse double-selection statement in Chapter 5. C# provides the switch multiple-selection statement to perform different actions based on the possible values of an expression. Each action is associated with the value of a constant integral expression or a constant string expression that the variable or expression on which the switch is based may assume. A constant integral expression is any expression involving character and integer constants that evaluates to an integer value—i.e., values of type sbyte, byte, short, ushort, int, uint, long, ulong and char, or a constant from an enum type (enum is discussed in Section 7.10). A constant string expression is any expression composed of string literals that always results in the same string.

Figure 6.9 contains an enhanced version of the GradeBook class introduced in Chapter 4 and further developed in Chapter 5. The version of the class we now present not only calculates the average of a set of numeric grades entered by the user, but uses a switch statement to determine whether each grade is the equivalent of an A, B, C, D or F, then increments the appropriate grade counter. The class also displays a summary of the number of students who received each grade. Figure 6.10 shows sample input and output of the GradeBookTest application that uses class GradeBook to process a set of grades.

Fig. 6.9. GradeBook class that uses a switch statement to count A, B, C, D and F grades.
 1   // Fig. 6.9: GradeBook.cs
 2   // GradeBook class uses switch statement to count letter grades.
 3   using System;
 5   public class GradeBook
 6   {
 7      private int total; // sum of grades                  
 8      private int gradeCounter; // number of grades entered
 9      private int aCount; // count of A grades             
10      private int bCount; // count of B grades             
11      private int cCount; // count of C grades             
12      private int dCount; // count of D grades             
13      private int fCount; // count of F grades             
15      // automatic property CourseName
16      public string CourseName { get; set; }
18      // constructor initializes automatic property CourseName;
19      // int instance variables are initialized to 0 by default
20      public GradeBook( string name )
21      {
22         CourseName = name; // set CourseName to name
23      } // end constructor
25      // display a welcome message to the GradeBook user
26      public void DisplayMessage()
27      {
28         // CourseName gets the name of the course
29         Console.WriteLine( "Welcome to the grade book for\n{0}!\n",
30            CourseName );
31      } // end method DisplayMessage
33      // input arbitrary number of grades from user
34      public void InputGrades()
35      {
36         int grade; // grade entered by user
37         string input; // text entered by the user
39         Console.WriteLine( "{0}\n{1}",
40            "Enter the integer grades in the range 0-100.",
41            "Type <Ctrl> z and press Enter to terminate input:" );
43         input = Console.ReadLine(); // read user input
45         // loop until user enters the end-of-file indicator (<Ctrl> z)
46         while ( input != null )
47         {
48            grade = Convert.ToInt32( input ); // read grade off user input
49            total += grade; // add grade to total
50            ++gradeCounter; // increment number of grades
52            // call method to increment appropriate counter
53            IncrementLetterGradeCounter( grade );
55            input = Console.ReadLine(); // read user input
56         } // end while
57      } // end method InputGrades
59      // add 1 to appropriate counter for specified grade
60      private void IncrementLetterGradeCounter( int grade )
61      {
62         // determine which grade was entered     
63         switch ( grade / 10 )                    
64         {                                        
65            case 9: // grade was in the 90s       
66            case 10: // grade was 100             
67               ++aCount; // increment aCount      
68               break; // necessary to exit switch 
69            case 8: // grade was between 80 and 89
70               ++bCount; // increment bCount      
71               break; // exit switch              
72            case 7: // grade was between 70 and 79
73               ++cCount; // increment cCount      
74               break; // exit switch              
75            case 6: // grade was between 60 and 69
76               ++dCount; // increment dCount      
77               break; // exit switch              
78            default: // grade was less than 60    
79               ++fCount; // increment fCount      
80               break; // exit switch              
81         } // end switch                          
82      } // end method IncrementLetterGradeCounter
84      // display a report based on the grades entered by the user
85      public void DisplayGradeReport()
86      {
87         Console.WriteLine( "\nGrade Report:" );
89         // if user entered at least one grade...
90         if ( gradeCounter != 0 )
91         {
92            // calculate average of all grades entered
93            double average = ( double ) total / gradeCounter;
95            // output summary of results
96            Console.WriteLine( "Total of the {0} grades entered is {1}",
97               gradeCounter, total );
98            Console.WriteLine( "Class average is {0:F}", average );
99            Console.WriteLine( "{0}A: {1}\nB: {2}\nC: {3}\nD: {4}\nF: {5}",
100              "Number of students who received each grade:\n",
101              aCount, // display number of A grades
102              bCount, // display number of B grades
103              cCount, // display number of C grades
104              dCount, // display number of D grades
105              fCount ); // display number of F grades
106        } // end if
107        else // no grades were entered, so output appropriate message
108           Console.WriteLine( "No grades were entered" );
109     } // end method DisplayGradeReport
110  } // end class GradeBook


Fig. 6.10. Create GradeBook object, input grades and display grade report.
 1   // Fig. 6.10: GradeBookTest.cs
 2   // Create GradeBook object, input grades and display grade report.
 4   public class GradeBookTest
 5   {
 6      public static void Main( string[] args )
 7      {
 8         // create GradeBook object myGradeBook and
 9         // pass course name to constructor
10         GradeBook myGradeBook = new GradeBook(
11            "CS101 Introduction to C# Programming" );
13         myGradeBook.DisplayMessage(); // display welcome message
14         myGradeBook.InputGrades(); // read grades from user                
15         myGradeBook.DisplayGradeReport(); // display report based on grades
16      } // end Main
17   } // end class GradeBookTest


Welcome to the grade book for
CS101 Introduction to C# Programming!

Enter the integer grades in the range 0-100.
Type <Ctrl> z and press Enter to terminate input:

Grade Report:
Total of the 9 grades entered is 638
Class average is 70.89
Number of students who received each grade:
A: 4
B: 0
C: 1
D: 1
F: 3


Instance Variables

Class GradeBook (Fig. 6.9) declares instance variables total (line 7) and gradeCounter (line 8), which keep track of the sum of the grades entered by the user and the number of grades entered, respectively. Lines 9–13 declare counter variables for each grade category. Class GradeBook maintains total, gradeCounter and the five letter-grade counters as instance variables so that they can be used or modified in any of the class’s methods.

Property CourseName, Method DisplayMessage and the Constructor

Like earlier versions of the class, class GradeBook declares automatic property CourseName (line 16) and method DisplayMessage (lines 26–31) to display a welcome message to the user. The class also contains a constructor (lines 20–23) that initializes the course name. The constructor sets only the course name—the remaining seven instance variables are ints and are initialized to 0 by default.

Methods InputGrades and DisplayGradeReport

Class GradeBook contains three additional methods—InputGrades, IncrementLetterGradeCounter and DisplayGradeReport. Method InputGrades (lines 34–57) reads an arbitrary number of integer grades from the user using sentinel-controlled repetition and updates instance variables total and gradeCounter. Method InputGrades calls method IncrementLetterGradeCounter (lines 60–82) to update the appropriate letter-grade counter for each grade entered. Class GradeBook also contains method DisplayGradeRe-port (lines 85–109), which outputs a report containing the total of all grades entered, the average of the grades and the number of students who received each letter grade. Let’s examine these methods in more detail.

Lines 36–37 in method InputGrades declare variables grade and input, which will first store the user’s input as a string (in the variable input), then convert it to an int to store in the variable grade. Lines 39–41 prompt the user to enter integer grades and to type Ctrl + z, then press Enter to terminate the input. The notation Ctrl + z means to simultaneously press both the Ctrl key and the z key when typing in a Command Prompt. Ctrl + z is the Windows key sequence for typing the end-of-file indicator. This is one way to inform an application that there’s no more data to input. If Ctrl + z is entered while the application is awaiting input with a ReadLine method, null is returned. (The end-of-file indicator is a system-dependent keystroke combination. On many non-Windows systems, end-of-file is entered by typing Ctrl + d.) In Chapter 17, Files and Streams, we’ll see how the end-of-file indicator is used when an application reads its input from a file. [Note: Windows typically displays the characters ^Z in a Command Prompt when the end-of-file indicator is typed, as shown in the output of Fig. 6.10.]

Line 43 uses the ReadLine method to get the first line that the user entered and store it in variable input. The while statement (lines 46–56) processes this user input. The condition at line 46 checks whether the value of input is a null reference. The Console class’s ReadLine method will return null only if the user typed an end-of-file indicator. As long as the end-of-file indicator has not been typed, input will not contain a null reference, and the condition will pass.

Line 48 converts the string in input to an int type. Line 49 adds grade to total. Line 50 increments gradeCounter. The class’s DisplayGradeReport method uses these variables to compute the average of the grades. Line 53 calls the class’s IncrementLetterGradeCounter method (declared in lines 60–82) to increment the appropriate letter-grade counter, based on the numeric grade entered.

Method IncrementLetterGradeCounter and the Constructor

Method IncrementLetterGradeCounter contains a switch statement (lines 63–81) that determines which counter to increment. In this example, we assume that the user enters a valid grade in the range 0–100. A grade in the range 90–100 represents A, 80–89 represents B, 70–79 represents C, 60–69 represents D and 0–59 represents F. The switch statement consists of a block that contains a sequence of case labels and an optional default label. These are used in this example to determine which counter to increment based on the grade.

When the flow of control reaches the switch statement, the application evaluates the expression in the parentheses (grade / 10) following keyword switch—this is called the switch expression. The application attempts to match the value of the switch expression with one of the case labels. The switch expression in line 63 performs integer division, which truncates the fractional part of the result. Thus, when we divide any value in the range 0–100 by 10, the result is always a value from 0 to 10. We use several of these values in our case labels. For example, if the user enters the integer 85, the switch expression evaluates to int value 8. If a match occurs between the switch expression and a case (case 8: at line 69), the application executes the statements for that case. For the integer 8, line 70 increments bCount, because a grade in the 80s is a B. The break statement (line 71) causes program control to proceed with the first statement after the switch—in this application, we reach the end of method IncrementLetterGradeCounter’s body, so control returns to line 55 in method InputGrades (the first line after the call to IncrementLetterGradeCounter). This line uses the ReadLine method to read the next line entered by the user and assign it to the variable input. Line 56 marks the end of the body of the while statement that inputs grades (lines 46–56), so control flows to the while’s condition (line 46) to determine whether the loop should continue executing based on the value just assigned to the variable input.

The cases in our switch explicitly test for the values 10, 9, 8, 7 and 6. Note the case labels at lines 65–66 that test for the values 9 and 10 (both of which represent the grade A). Listing case labels consecutively in this manner with no statements between them enables the cases to perform the same set of statements—when the switch expression evaluates to 9 or 10, the statements in lines 67–68 execute. The switch statement does not provide a mechanism for testing ranges of values, so every value to be tested must be listed in a separate case label. Each case can have multiple statements. The switch statement differs from other control statements in that it does not require braces around multiple statements in each case.

In C, C++, and many other programming languages that use the switch statement, the break statement is not required at the end of a case. Without break statements, each time a match occurs in the switch, the statements for that case and subsequent cases execute until a break statement or the end of the switch is encountered. This is often referred to as “falling through” to the statements in subsequent cases. This frequently leads to logic errors when you forget the break statement. For this reason, C# has a “no fall through” rule for cases in a switch—after the statements in a case, you are required to include a statement that terminates the case, such as a break, a return or a throw. (We discuss the throw statement in Chapter 13, Exception Handling.)

If no match occurs between the switch expression’s value and a case label, the statements after the default label (lines 79–80) execute. We use the default label in this example to process all switch-expression values that are less than 6—that is, all failing grades. If no match occurs and the switch does not contain a default label, program control simply continues with the first statement (if there is one) after the switch statement.

GradeBookTest Class That Demonstrates Class GradeBook

Class GradeBookTest (Fig. 6.10) creates a GradeBook object (lines 10–11). Line 13 invokes the object’s DisplayMessage method to output a welcome message to the user. Line 14 invokes the object’s InputGrades method to read a set of grades from the user and keep track of the sum of all the grades entered and the number of grades. Recall that method InputGrades also calls method IncrementLetterGradeCounter to keep track of the number of students who received each letter grade. Line 15 invokes method DisplayGradeRe-port of class GradeBook, which outputs a report based on the grades entered. Line 90 of class GradeBook (Fig. 6.9) determines whether the user entered at least one grade—this avoids dividing by zero. If so, line 93 calculates the average of the grades. Lines 96–105 then output the total of all the grades, the class average and the number of students who received each letter grade. If no grades were entered, line 108 outputs an appropriate message. The output in Fig. 6.10 shows a sample grade report based on 9 grades.

Class GradeBookTest (Fig. 6.10) does not directly call GradeBook method IncrementLetterGradeCounter (lines 60–82 of Fig. 6.9). This method is used exclusively by method InputGrades of class GradeBook to update the appropriate letter-grade counter as each new grade is entered by the user. Method IncrementLetterGradeCounter exists solely to support the operations of class GradeBook’s other methods and thus is declared private. Members of a class declared with access modifier private can be accessed only by members of the class in which the private members are declared. When a private member is a method, it’s commonly referred to as a utility method or helper method, because it can be called only by other members of that class and is used to support the operation of those other members.

switch Statement UML Activity Diagram

Figure 6.11 shows the UML activity diagram for the general switch statement. Every set of statements after a case label normally ends its execution with a break or return statement to terminate the switch statement after processing the case. Typically, you’ll use break statements. Figure 6.11 emphasizes this by including break statements in the activity diagram. The diagram makes it clear that the break statement at the end of a case causes control to exit the switch statement immediately.

Fig. 6.11. switch multiple-selection statement UML activity diagram with break statements.

Good Programming Practice 6.5

Although each case and the default label in a switch can occur in any order, place the default label last for clarity.

When using the switch statement, remember that the expression after each case can be only a constant integral expression or a constant string expression—that is, any combination of constants that evaluates to a constant value of an integral or string type. An integer constant is simply an integer value (e.g., –7, 0 or 221). In addition, you can use character constants—specific characters in single quotes, such as 'A', '7' or '$'—which represent the integer values of characters. (Appendix C shows the integer values of the characters in the ASCII character set, which is a subset of the Unicode character set used by C#.) A string constant (or string literal) is a sequence of characters in double quotes, such as "Welcome to C# Programming!".

The expression in each case also can be a constant—a value which does not change for the entire application. Constants are declared with the keyword const (discussed in Chapter 7). C# also has a feature called enumerations, which we also present in Chapter 7. Enumeration constants can also be used in case labels. In Chapter 12, we present a more elegant way to implement switch logic—we use a technique called polymorphism to create applications that are often clearer, easier to maintain and easier to extend than applications using switch logic.

Enhanced combobox with readonly and working value member

As I had several problems with the standard combo box of the .Net 2.0 Framework such as the missing read only property or the not working value member property (if not using a datasource), I decided to write my own improved combo box. To change the default combobox to my needs I overwrote the OnPaint() mehtod and provided some additional methods.With the enhanced combo box you can finally specify a value member without having to use a datasource as you can see in the code below: Continue reading