📄 creditcardissuer.java
字号:
/**
* Copyright (c) 1996-2004 Borland Software Corporation. All Rights Reserved.
*
* This SOURCE CODE FILE, which has been provided by Borland Software as part
* of a Borland Software product for use ONLY by licensed users of the product,
* includes CONFIDENTIAL and PROPRIETARY information of Borland Software.
*
* USE OF THIS SOFTWARE IS GOVERNED BY THE TERMS AND CONDITIONS
* OF THE LICENSE STATEMENT AND LIMITED WARRANTY FURNISHED WITH
* THE PRODUCT.
*
* IN PARTICULAR, YOU WILL INDEMNIFY AND HOLD BORLAND SOFTWARE, ITS
* RELATED COMPANIES AND ITS SUPPLIERS, HARMLESS FROM AND AGAINST ANY
* CLAIMS OR LIABILITIES ARISING OUT OF THE USE, REPRODUCTION, OR
* DISTRIBUTION OF YOUR PROGRAMS, INCLUDING ANY CLAIMS OR LIABILITIES
* ARISING OUT OF OR RESULTING FROM THE USE, MODIFICATION, OR
* DISTRIBUTION OF PROGRAMS OR FILES CREATED FROM, BASED ON, AND/OR
* DERIVED FROM THIS SOURCE CODE FILE.
*/
//------------------------------------------------------------------------------
// Copyright (c) 1996-2004 Borland Software Corporation. All Rights Reserved.
//------------------------------------------------------------------------------
package com.borland.samples.creditapproval.server;
import java.io.*;
import java.util.*;
import java.net.*;
import com.borland.dx.dataset.*;
import com.borland.dx.sql.dataset.*;
import com.borland.samples.creditapproval.CORBAInterface.*;
/**
* CreditCardIssuer issues a credit card to a specified applicant.
*
* Credit Cards are issues using the following business logic:
*
* 1) Calculate Credit Card Number: Increment a database
* counter and add a constant
* New Number = (Credit Card Counter + 1) + 9000000000000000
* 2) Calculate Expiration Date: Add 2 years to the current Month/Year
* Expiration Date = Current Month / (Current Year + 2)
*/
public class CreditCardIssuer implements DataModule{
private static CreditCardIssuer myDM;
Database cliffhangerDb = new Database();
// Dataset used to create new customer ID
QueryDataSet nextCustomerIDDataSet = new QueryDataSet();
ResourceBundle res = Res.getBundle("com.borland.samples.creditapproval.server.Res");
public CreditCardIssuer() throws Exception {
try {
jbInit();
}
catch (Exception e) {
e.printStackTrace();
throw e;
}
}
/**
* Initialize Objects
* @throws Exception exception
*/
private void jbInit() throws Exception{
// Initialize database connection
cliffhangerDb.setConnection(new com.borland.dx.sql.dataset.ConnectionDescriptor(CreditCardIssuer.getInterBaseURL("OnlineStore", "cliffhanger.gdb"), "SYSDBA", "masterkey", false, "interbase.interclient.Driver"));
cliffhangerDb.setSQLDialect(com.borland.dx.sql.dataset.SQLDialect.INTERBASE);
nextCustomerIDDataSet.setQuery(new com.borland.dx.sql.dataset.QueryDescriptor(cliffhangerDb, "SELECT NEXTID FROM spNextCustomerID", null, true, Load.ALL));
}
/**
* Connect/Disconnect to/from the database based on 'connect' parameter.
* @param open boolean
* @throws DataSetException datasetexception
*/
void connect(boolean open) throws DataSetException {
if (open) {
if (!cliffhangerDb.isOpen()) new TimedConnect(cliffhangerDb, 2, 8 );
}
else {
if (cliffhangerDb.isOpen()) {
try {
cliffhangerDb.closeConnection();
} catch (Exception e) {
System.out.println( e );
}
}
}
}
static public CreditCardIssuer getDataModule() throws Exception {
if (myDM == null)
myDM = new CreditCardIssuer();
return myDM;
}
/**
* Create an Expiration date and return it as a string in
* JDBC date escape format.
* @throws Exception exception
* @return String
*/
String generateExpirationDate() throws Exception {
java.util.GregorianCalendar calendar = new java.util.GregorianCalendar();
String expirationDate;
expirationDate = Integer.toString( calendar.get(java.util.Calendar.YEAR) + 2 ) +
"-" + Integer.toString( calendar.get(java.util.Calendar.MONTH) + 1 ) + "-01";
return expirationDate;
}
/**
* Increment the database credit card counter and add a constant
* to produce a new credit card number.
* @throws Exception exception
* @return String
*/
String generateCardNumber() throws Exception {
int nextCount = 0;
// Issue an SQL statement to increment the Credit Card Number
java.sql.Statement statement = cliffhangerDb.createStatement() ;
statement.executeUpdate("UPDATE CARDNUMBER SET CARDNUMBER = CARDNUMBER + 1");
java.sql.ResultSet results = statement.executeQuery("SELECT CARDNUMBER FROM CARDNUMBER");
// Move to first row in the result set! If a row does not
// exist, throw an exception.
if (results.next()) nextCount = results.getInt("CARDNUMBER");
else throw new Exception( res.getString("Database_error") );
results.close();
// Add the constant to generate a new, properly formed, Credit Card Number
String count = Integer.toString( nextCount );
String number = "9000000000000000";
number = number.substring( 0, (number.length() - count.length())) + count;
return number;
}
/**
* Method to format a customer name given the first name, middle initial,
* and last name.
*
* @param firstName String
* @param mi String
* @param lastName String
* @return String
*/
private String formatCustomerName(String firstName, String mi, String lastName) {
// Format the customer name
if (mi.compareTo("") == 0)
return (firstName + " " + lastName);
else
return (firstName + " " + mi + ". " + lastName);
}
/**
* Create an account record in the Cliffhanger Database for the new
* credit card holder.
*
* @param appInfo applicantInfoStruct
* @param creditCardInfo creditApprovalStruct
* @throws Exception exception
*/
public void generateAccountRecord(applicantInfoStruct appInfo,
creditApprovalStruct creditCardInfo )
throws Exception {
// Call the stored procedure to get a new Customer ID
int customerID = getNextCustomerID();
// Insert a new account record
String accountQuery = "INSERT INTO ACCOUNT (ID, CREDITCARDNUMBER, " +
"EXPIRATIONDATE, LIMIT, " +
"IDENTIFICATION, DOB, STATUS, BALANCE) " +
"VALUES( ?, ?, ?, ?, ?, ?, 'OPEN', 0)";
java.sql.PreparedStatement newAccountStatement =
cliffhangerDb.createPreparedStatement( accountQuery );
// Populate the ? in the prepared statements with actual values.
// This relies on the JDBC driver to format data-types correctly,
// such as dates, for the back-end RDBMS.
newAccountStatement.setInt( 1, customerID);
newAccountStatement.setString( 2, creditCardInfo.creditCardNumber );
newAccountStatement.setDate( 3, java.sql.Date.valueOf( creditCardInfo.expirationDate ));
newAccountStatement.setDouble( 4, creditCardInfo.limit );
newAccountStatement.setString( 5, appInfo.PID );
newAccountStatement.setDate( 6, java.sql.Date.valueOf( appInfo.DOB ));
newAccountStatement.execute();
newAccountStatement.close();
// Insert a new Customer Record
String customerQuery = "INSERT INTO CUSTOMER (ID, FIRSTNAME, MI, " +
"LASTNAME, PHONE, ADDR1, ADDR2, CITY, " +
"STATE, POSTALCODE, COUNTRY, SHIPNAME, SHIPADDR1, " +
"SHIPADDR2, SHIPCITY, SHIPSTATE, SHIPPOSTALCODE, " +
"SHIPCOUNTRY, FAX, EMAIL ) " +
"VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, '', '' )";
java.sql.PreparedStatement newCustomerStatement =
cliffhangerDb.createPreparedStatement( customerQuery );
newCustomerStatement.setInt( 1, customerID);
newCustomerStatement.setString( 2, appInfo.firstName);
newCustomerStatement.setString( 3, appInfo.MI );
newCustomerStatement.setString( 4, appInfo.lastName );
newCustomerStatement.setString( 5, appInfo.phone );
newCustomerStatement.setString( 6, appInfo.address1 );
newCustomerStatement.setString( 7, appInfo.address2 );
newCustomerStatement.setString( 8, appInfo.city );
newCustomerStatement.setString( 9, appInfo.state );
newCustomerStatement.setString( 10, appInfo.postalCode );
newCustomerStatement.setString( 11, appInfo.country );
newCustomerStatement.setString( 12, formatCustomerName( appInfo.firstName,
appInfo.MI,
appInfo.lastName ));
newCustomerStatement.setString( 13, appInfo.address1 );
newCustomerStatement.setString( 14, appInfo.address2 );
newCustomerStatement.setString( 15, appInfo.city );
newCustomerStatement.setString( 16, appInfo.state );
newCustomerStatement.setString( 17, appInfo.postalCode );
newCustomerStatement.setString( 18, appInfo.country );
newCustomerStatement.execute();
newCustomerStatement.close();
}
/**
* Issue a credit credit card to the specified applicant.
* @param appInfo applicantInfoStruct
* @param creditCardInfo creditApprovalStruct
* @throws Exception exception
*/
public void issueCreditCard(applicantInfoStruct appInfo,
creditApprovalStruct creditCardInfo )
throws Exception {
try{
// Turn off autoCommit so that all of the SQL statements
// in the folllowing method invocations are part of the
// same transaction.
cliffhangerDb.setAutoCommit( false );
// Generate credit card information
creditCardInfo.creditCardNumber = generateCardNumber();
creditCardInfo.expirationDate = generateExpirationDate();
generateAccountRecord( appInfo, creditCardInfo );
// Commit the transaction
cliffhangerDb.commit();
} catch( Exception e) {
System.err.println(e);
// The transaction needs to be rolled-back
// to ensure all DB changes are discarded.
try{
cliffhangerDb.rollback();
} catch( Exception rollbackException ) {
System.out.println(rollbackException);
}
// Throw a new exception so that the caller is aware
// that an error occurred.
throw new Exception(res.getString("An_error_occurred") + "\n" +
res.getString("Please_try_again_"));
}
}
/**
* Method to get the next customer ID.
* This calls a stored procedure on the database server spNextCustomerID
* that returns a single row with the next Customer ID generated by the server.
* @throws Exception exception
* @return int
*/
private int getNextCustomerID() throws Exception {
int result = 0;
try {
nextCustomerIDDataSet.open();
nextCustomerIDDataSet.refresh();
result = nextCustomerIDDataSet.getInt("NEXTID");
nextCustomerIDDataSet.close();
}
catch (Exception ex) {
ex.printStackTrace();
throw ex;
}
return result;
}
/**
* The following method (not described in the tutorial) is used to dynamically
* locate the database used by this sample, since the absolute location of the
* database varies depending upon where the sample is installed. A database
* for a non-sample application would normally be in a static location, and
* this would not be necessary.
*
* @param sampleDirRoot String
* @param fileName String
* @return String
*/
public static String getInterBaseURL(String sampleDirRoot, String fileName) {
String url = null;
try {
File file = new File(CreditCardIssuer.class.getResource("CreditCardIssuer.class").
getFile());
File parentDir = file.getParentFile();
do {
parentDir = parentDir.getParentFile();
} while (!parentDir.getName().equals(sampleDirRoot));
String path = parentDir.getParent();
url = "jdbc:interbase://localhost/" + URLDecoder.decode(path, "UTF-8") +
"/OnlineStore/database/" + fileName;
System.out.println(
"CreditCardIssuer.getInterBaseURL() using this URL to connect to " + fileName +
": " + url);
} catch (UnsupportedEncodingException uex) {
uex.printStackTrace();
}
return url;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -