Building Peachmail: Registration and Login
Joe's first action when he arrives at Peachmail is to register for an account. He is presented with a screen to enter his username, password, email address, POPServer, and SMTPServer. Once he enters this information, Peachmail processes the information by sending this data to the server. After Peachmail confirms his account, Joe proceeds to log in. Let's first look at how Flash MX will generate the data to send to Java, and then explore how Flash handles the responses from Java.
The Front-End: Flash MX
Peachmail's first screen (Figure 7.10) contains two buttons: Login and New User.
Joe clicks on the New User button and is presented with the Create New User screen. He fills out his details and clicks Create, which triggers Flash to generate the following XML transaction data:
<Request> <TransactionType> CreateUser </TransactionType> <Data> <Username> myjoe </Username> <Password> myjoepassword </Password> <EmailAddress> joe@joes_email.com </EmailAddress> <POPServer> mail.joes_email.com </POPServer> <SMTPServer> smtp.joes_email.com </SMTPServer> </Data> </Request>
Figure 7.10 Peachmail's Login screen.
This is all the information that Peachmail needs to process the registration. Next, Joe is told that his registration is successful and he returns to the main screen and clicks Login. This triggers Flash to generate the login XML transaction data:
<Request> <TransactionType> Login </TransactionType> <Data> <Username> myjoe </Username> <Password> myjoepassword </Password> </Data> </Request>
In the Peachmail application are functions named createHandler and loginHandler for the Create button and Login button, respectively. These button handlers help to generate the preceding XML documents, and pass them to Java for processing.
createHandler does the following:
Creates the XML new user request from the input fields on the screen.
Passes the request to Java.
Creates a callback function to test whether the creation was successful.
Here is the ActionScript code for createHandler:
createHandler = function () { message.text = "Creating..."; // check the two passwords if (password.text === passwordRepeat.text) { // make the xml var createUserXml = buildCreateUserRequest (username.text, password.text, email.text, popServer.text, smtpServer.text); // callback createUserCallback = function () { if (wasSuccessful(this.getDocIn())) { // goto the created interface gotoAndStop("created"); } else { // show message message.text = getError(this.getDocIn()); } } // send create user xml sendToServer(createUserXml, createUserCallback); } else { // make message message.text = "Passwords do not match"; } }
loginHandler does the following:
Creates the XML login request from the username and password.
Sends the data to Java for processing.
Sets up a callback function to check whether the login was successful Here is the ActionScript code for loginHandler:
loginHandler = function () { // make the xml var loginXML = buildLoginRequest(username.text, password.text); // give a message message.text = "Logging In..."; // check received xml loginCallback = function () { if (wasSuccessful(this.getDocIn())) { // goto email interface gotoAndStop("email"); }else { // show error message.text = getError(this.getDocIn()); } } // send login request sendToServer(loginXML, loginCallback); }
Notice how the loginHandler and the createHandler act similarlyboth create a XML request, pass the request to Java, and create a callback function for the Java response, to see whether the request was successful. This create-send-callback action is used in other handlers throughout the Peachmail application.
buildBaseRequest: Creating the XML Request
loginHandler calls a function buildLoginRequest and createHandler calls a function buildCreateUserRequest. Let's take a quick look at the code:
buildLoginRequest = function (username, password) { // build the request var createLoginRequest = new buildBaserequest("Login"); // add the username createLoginRequest.addData("Username", username); // add the password createLoginRequest.addData("Password", password); // return the finished xml doc return createLoginRequest.getDoc(); } buildCreateUserRequest = function (username, password, emailAddress, POPServer, SMTPServer) { // Build a basic create user transaction var createCreateUserRequest = new buildBaseRequest( "CreateUser" ); // add the username data to the xml doc createCreateUserRequest.addData("Username", username); // add the password data to the xml doc createCreateUserRequest.addData("Password", password); // add the email address createCreateUserRequest.addData("EmailAddress", emailAddress); // add the servers createCreateUserRequest.addData("POPServer", POPServer); createCreateUserRequest.addData("SMTPServer", SMTPServer); // return the finished XML document return createCreateUserRequest.getDoc(); }
As you can see, both buildLoginRequest and buildCreateUserRequest create a buildBaseRequest object to form the proper XML document for the respective handler. Along with the addData() method, it creates the XML document mirroring the syntax of the two XML documents Joe created previously, and it returns the XML document to the respective handler.
Here is the constructor for buildBaseRequest and the addData method, along with some helper methods:
// buildBaseRequest constructor function buildBaseRequest(transactionType) { // Create the XML Object this.doc = new XML(); // Create the request node var requestNode = this.doc.createElement("Request"); // Create the transaction node var transactionNode = this.doc.createElement ("TransactionType"); // Create the transaction value var transactionNodeValue = this.doc.createTextNode (transactionType); // Populate the value of the transaction node transactionNode.appendChild(transactionNodeValue); // Create the data node var dataNode = this.doc.createElement("Data"); // Append the transaction node to the request node requestNode.appendChild(transactionNode); // Append the data node to the request node requestNode.appendChild(dataNode); // Append the request node to the parent doc this.doc.appendChild(requestNode); // Return the completed document return this.doc; } // end buildBaseRequest function // addData function buildBaseRequest.prototype.addData = function (newData, value, attributes) { // find the data node var dataNode = findDataNode(this.doc); // create the newData node var newDataNode = this.doc.createElement(newData); // check to see if a value was specified if (value != null) // create the value text node var valueTextNode = this.doc.createTextNode(value); // check to see if attributes were specified if (attributes != undefined) // loop through the attributes and set them for (var i in attributes) // add the attribute newDataNode.attributes[i] = attributes[i]; // append valueTextNode to newDataNode newDataNode.appendChild(valueTextNode); // append newDataNode to dataNode dataNode.appendChild(newDataNode); } // end adddata // findDataNode function // This helper function finds and returns the data node in a transaction xml doc function findDataNode(xmlDoc) { // Get the children nodes var children = xmlDoc.firstChild.childNodes; // Get the second child node (the data node) var dataNode = children[1]; // return the node return dataNode; } // end findDataNode function // getDoc function // returns the xml doc buildBaseRequest.prototype.getDoc = function () { // return the xml document return this.doc; } // wasSuccessful function // This helper is used to determine if a transaction executed properly or not. function wasSuccessful(xmlDoc) { // Create an XML object to be sure var xmlDoc = new XML(xmlDoc); // Parse through and find the status var mainNodes = xmlDoc.firstChild.childNodes; var statusNode = mainNodes[0]; var status = statusNode.firstChild.nodeValue; // If its an error, find the message if(status == 'Error') { var dataNode = mainNodes[1]; var messageNode = dataNode.firstChild; errorMessage = messageNode.firstChild.nodeValue; return false; } // return true if there was no error return true; } // end wasSuccessful function // getError function // This helper is used to get the error of an unsuccesful xml doc function getError(xmlDoc) { // Create an XML object to be sure var xmlDoc = new XML(xmlDoc); // Parse through and find the error var mainNodes = xmlDoc.firstChild.childNodes; var dataNode = mainNodes[1]; var messageNode = dataNode.firstChild; errorMessage = messageNode.firstChild.nodeValue; // return error return errorMessage; } // end getError function
sendToServer: Sending XML to Java
Both loginHandler and createHandler use sendToServer() to send XML data to Java, like this:
sendToServer(loginXML, loginCallback);
Here's a closer look at the sendToServer() function:
global.sendToServer = function (theXML, callBack) { // set the document to send to server server.setDocOut(theXML); // set the xml to recieve a reply from server server.setDocIn(new XML()); // get the callback arguments from the arguments server.callBackArgs = arguments.slice(2); // store the callback function server.callBack = callBack; // set the callback function server.onLoad = function (success) { // check to see if there is an incoming doc if (success) { // call the callback function with the arguments this.callBack.apply(this, this.callBackArgs); } else { // call the server error function onServerDisconnect(); } } // send the document server.execute(); }
To quickly summarize, the sendToServer() function takes an object named server and passes it the XML data and the callback function, and then tells server to send the data by calling server.execute(). server is an object of a custom-made class named Serverdata()its purpose to handle the passing of the data to Java in one neat little package. The following code shows how server is created and its defaults set.
global.server = new ServerData(); // set the methods server.setMethod(server.SEND_AND_LOAD); // set the language server.setLanguage(server.JAVA); // this is the url of server server.setURL(myurl);
Without going into all the detail regarding ServerData(), we'll look at what ServerData.execute() uses to send the XML data to Java: the Flash XML.sendAndLoad() method. The specific line of code inside ServerData() looks like this:
docOut.sendAndLoad(url, docIn);
where docOut is the XML data being sent to the Java server located at url, and docIn is the variable that contains the result passed back from Java once docOut is sent and processed.
Once a response is returned from Java and Flash receives the data result, Flash automatically runs docIn.onLoad(), which is set up in ServerData() to process the callback function originally set by the handler.
Callbacks: Verifying Data Requests
Let's revisit the code for loginHandler, specifically the declaration of its call-back function and the passing of this function to the ServerData() object:
loginCallback = function () { if (wasSuccessful(this.getDocIn())) { // goto email interface gotoAndStop("email"); } else { // show error message.text = getError(this.getDocIn()); } } // send login request sendToServer(loginXML, loginCallback);
The loginCallback() function is sent as the second parameter of sendTo Server, so the ServerData object can call loginCallback() automat-ically, upon receiving a response after Java processes the XML. Also notice that loginCallback's action resulting from a successful transaction is to take Joe into the main part of the application (the email screen); it displays an error message for unsuccessful transactions.
Now that we've discussed the create-send-callback method, let's move on to the server and look at how the back-end detects, processes, and responds to the Flash code.
The Back-End: Java
Recall how Flash sends the XML data to Javait uses the ServerData() object and the standard XML.sendAndLoad() method, sending the XML data stored in docOut to the server:
docOut.sendAndLoad(url, docIn);
Also recall that docIn is the variable that will contain the result passed back from the server. How does this work? Flash automatically knows that by using the sendAndLoad() method, it will wait to receive data into docIn. Once the data is in docIn, Flash automatically executes the docIn.onLoad() method.
Running the docIn.onLoad() triggers the execution of the callback function. This is because we preset the docIn.onLoad() method to run the callback when sendToServer() is executed in the handler code:
sendToServer(loginXML, loginCallback);
Processing the New User Request
Earlier you saw how Flash created the New User request when Joe clicked the Create button for the registration screen. When the Java server receives and processes the data, it returns to Flash a result indicating whether the process is successful, and as discussed earlier, this result is stored in the Flash variable docIn.
Java returns the following code to Flash when Java processes the data unsuccessfully:
<Response> <Status> Error </Status> <Data> <Message> Some message on why the new user request failed </Message> </Data> </Response>
and successfully:
<Response> <Status> Success </Status> <Data> <Message> The transaction completed successfully </Message> </Data> </Response>
Processing the Login Request
Much in the same way that new user requests are handled by Java, the login requests tell Java to generate the following code to send to Flash for an unsuccessful process:
<Response> <Status> Error </Status> <Data> <Message> Some message on why the login failed </Message> </Data> </Response>
and for a successful process:
<Response> <Status> Success </Status> <Data> <Message> The transaction completed successfully </Message> </Data> </Response>
The Database
On the create new user request, Joe's data updates the Users table of the database, as Java sends the information to the database to be written.
The login request triggers the Java server to allocate a thread for Joe, for handling Joe's connection throughout the life of the time he is logged into the application. The database is unaffected by Joe's login request.