In this section, you will create a Request class, which is a utility class for holding information about an incoming CGI request. You will modify the main function by replacing its current contents with a declaration of a Request object, and an output statement that prints a simple response to the request back to standard output.
In later sections, the Request object will determine the class of user accessing the tool (for example, Reviewer or Author), and will create an object of the appropriate user class, so that the object can perform actions based on the authorities assigned to that class.
This section should take you approximately 90 minutes to complete. In it you will learn to perform the following IDE tasks:
You can cut sections of code from the online tutorial and paste them into the appropriate source views; this will let you concentrate on the concepts, and will save you time and potential typing errors.
| Implementation Details At the heart of the Request class is its constructor. The Request constructor does the following:
|
Prerequisites If You Are Starting Here
You should have the following source files in a directory on your system. If you did not complete Part 1 of the tutorial, click the links below to see each file's contents, create these files, then load review.icc in the VisualAge C++ IDE. Any changes you may need to make for your environment are indicated in the files.
Once you have created these files, start the VisualAge C++ IDE. Open the project identified by review.icc, then build the project when prompted.
You need to add the declaration for the Request class to the project. Follow these steps:
#include <istring.hpp> //Required for use of IString class
// Class Definition
class Request {
IString ReqString, //Request string from cgi call
lReqString, //Lowercase version for searches
ReqMethod, //How request was obtained
Op, //Operation requested
Filename, //File requested
Filepath, //File, with slashes corrected
Key; //User's key value
int ReqLen; //Length of request string
public:
//Constructor and get methods
Request();
IString GetReqString() {return ReqString; }
IString GetOp() {return Op;}
IString GetFilename() {return Filename;}
IString GetFilepath() {return Filepath;}
IString GetKey() {return Key;}
int GetReqLen() {return ReqLen;};
//Get the value of an attribute=value pair from request string
IString GetValue(IString Attribute);
};
To see the result of the build, select the Classes page in the Project section. The Request class should appear in the upper left pane (a Classes view of the Project object), with its members in the right pane (a Members view of the selected Class object). Class members are grouped by access method and sorted alphabetically by name. As you select different class members in the right pane, the Source view underneath shows a yellow arrow beside the declaration of the member you select. For example, select the Request class constructor; its declaration appears in the Source view. Later, when you add definitions for some of the undefined functions, the Source view will change to show these definitions.
Add the Constructor for the Request Class
Because the Request class constructor does more than simply initialize its data members with default values, it is not defined inline in the class declaration. Instead, it is defined in a function definitions file, request.cpp.
To create request.cpp, follow the steps in the previous section (Add the Request Class Declaration to the Project) to add request.cpp to the Source directive and create the file, just as you created and added request.hpp. Then, in the Source view that opens for request.cpp, enter the following code:
Request::Request() {
ReqString=""; //Initialize string
ReqMethod=getenv("REQUEST_METHOD"); //Determine how input provided
if (ReqMethod=="GET") { //GET means it comes from
ReqString=getenv("QUERY_STRING"); //QUERY_STRING variable
ReqLen=ReqString.length();
}
else if (ReqMethod=="POST") { //POST means read the right number
ReqLen=atoi(getenv("CONTENT_LENGTH")); //of characters from standard input.
for (int c=1;c<=ReqLen;c++)
ReqString+=char(cin.get());
ReqString.change("&"," "); //In POST calls, an "&" separates fields
}
ReqString.change("+"," "); //In both types, a "+" replaces a space
//Special characters are escaped with % and two hex digits.
//Convert these to their actual character values
int p=ReqString.indexOf("%");
while (p>0) {
if (ReqString.subString(p+1,2).isHexDigits()) // If it's a hex pair after %
ReqString.change(
ReqString.subString(p,3), // Change % and hex pair
ReqString.subString(p+1,2).x2c(),p,1); // to char value using IString::x2c
p=ReqString.indexOf("%",p+1); // Search for next %
}
lReqString=IString::lowerCase(ReqString); // Create lowercase version for searches
//Get the file attribute's value, then set Filepath to the value of
//the WebRoot macro plus a slash plus the file name. WebRoot and slash will be
//defined shortly.
Filename=GetValue("file");
Filepath=Filename;
Filepath.change(slash,"/");
if (Filepath.subString(1,1)!=slash)
Filepath=slash+Filepath;
Filepath=WebRoot+Filepath;
Key=GetValue("key"); //Get user's key
}
Build the project again. There should be two errors, stating that declarations for WebRoot and slash could not be found. You will define these next.
Add the source file macros.hpp to the Source directive in the same way you added request.cpp and request.hpp above, then add the following macros to that file. Change the string literal in the WebRoot macro to point to the path where HTML documents will be stored for review.
If you are doing the tutorial on AIX, change the definition of slash to a forward slash (/). Be sure not to add trailing semicolons (;) to these macro definitions.
#define WebRoot IString("f:\\vatutor\\htmldocs")
// Note - change above path to the correct path on your system
#define slash IString("\\")
If you were to rebuild the project now, the same errors would occur, because VisualAge C++ does not grant macros global scope by default. This differs from class, member, variable, and function definitions, which are C++ constructs and are accessible to any part of a VisualAge C++ program as long as the source files containing their declarations are part of a project's configuration.
Give Macros Global Scope
The option shows a hatched check box, which indicates that the option's default value is being used. In this case the default value is off. When you click the check box it changes to unchecked with no hatching, which sets the option to be off explicitly. This will cause the option to appear in the configuration file. Clicking the checkbox again will select it, which enables the option.
Click the Set Global Scope for Macros option by clicking the checkbox until it is checked.
Build the application again. You will encounter a different error this time, stating that one item is referenced but not defined (expand the error and you will see that the item is the GetValue function). The project has compiled successfully, but has not linked because of the undefined item. You will define GetValue in the next section of this tutorial. First, however, go back to the Classes page in the Project section, and try selecting the Request class constructor from the Members view of the class. Notice that as you do so, the source view underneath changes to show the constructor's definition, rather than its declaration within the class declaration. Even though you have not yet completed a build successfully, VisualAge C++ now knows enough about the code in your project to display the constructor definition, rather than the declaration that it showed the first time you selected the constructor from the Class Details view.
| Implementation Details: The GetValue function searches through the request string for the specified name followed by an equals sign (=), and, if the name is found, returns the value that immediately follows the equals sign, up to but excluding the first whitespace character or the end of the string. |
You do not need to add a new source file to your project to define this function; instead, you can add it to request.cpp. There are two ways you can access the source file:
Paste or type in the source code for the GetValue function at the bottom of request.cpp:
IString Request::GetValue(IString Search) {
Search.lowerCase();
Search+="=*";
for (int i=1; i<=ReqString.numWords();i++)
if (lReqString.word(i).isLike(Search))
return ReqString.word(i).subString(Search.length());
return "";
}
This function folds the search string to lowercase, appends "=*" to the search string, and uses the IString::isLike member function, which allows wildcard comparisons to a string, to compare the search string to each whitespace-delimited word in the lowercase version of the request. If a match is found, the value of the attribute is returned; otherwise the function returns a blank string.
Build your application again. If you have typed everything correctly, the project should build successfully. If a Help Tips window appears, click OK to close it. Your main function still has not changed, so the Request class is not actually used in your program. You will now modify the main function to declare an object of the Request class, which will cause the Request constructor to read in the CGI request information and set certain class variables (such as Filename and Filepath); main will then do some simple processing of the request to determine the output to write back to the user's browser.
You can open a Source view for the main function in any of the following ways. Try them all so you will better understand how the VisualAge C++ IDE gives you flexibility in how you view your program. In the first two methods, the Source view takes up the entire workbook section; in the others, the Source view is displayed below the other views.
If the Source view you are using is one of several views on the current page, you can enlarge it, by doing one of the following:
Change the source code for the main function to the following:
#include <fstream.h>
int main(int argc, char* argv[]) {
// Declare a Request object; this reads the request into fields of object
Request Req;
// Output is plain text unless later shown otherwise
IBoolean HtmlOut=false;
// Initialize the Result string to contain output
IString Result="";
// For now, require that key value be "secret"
if (Req.GetKey()!="secret")
Result="Sorry, you aren't authorized";
else {
// Handle request for file. Display if found.
if (Req.GetFilename()=="")
Result="Sorry, you didn't specify a file";
else {
ifstream InFile(Req.GetFilepath());
if (!InFile) Result="Sorry, file not found";
else {
// IString::lineFrom(ifstream,EOF) reads entire file
Result=IString::lineFrom(InFile,EOF);
// If the file contains "<html>" or "<HTML>" set HtmlOut to true
if (Result.indexOf("<html>")>0 || Result.indexOf("<HTML>")>0)
HtmlOut=true;
else if (Result=="") Result="Sorry, file was empty";
}
}
}
// Write the Content-Type header of the appropriate type (html/plain)
cout << "Content-Type: text/";
if (HtmlOut) cout << "html";
else cout << "plain";
// Write the result. The two \n's are a required part of the header.
cout << "\n\n" << Result << flush;
return 0;
}
Rebuild the project. If there are typing errors, go to the Messages page and correct them, then rebuild.
Run and Test the Program
You can now test this version of the CGI in your browser. Make sure the VisualAge Help Server is running:
Click the following links to see how the CGI behaves. In both cases the CGI returns an error message; the first message states that the requested file was not found, because you have not yet created the index.html file; the second states that you are not authorized, because the key "unauthorized" is not a recognized key.
Copy any existing HTML file to the directory you specified as WebRoot in macros.hpp, name it index.html, then try the two links again. The second link's result is the same as before; the first link should display the file you requested, as an HTML file. If it does not, check the following:
Now that you have defined the Request class and modified main to use it, you can proceed to the next part:
