oracle.otnsamples.orajaxb.RecordHolder (Java2HTML)
/*
* @Author : Abhijeet Kulkarni
* @Version 1.0
* Copyright (C) 2003 Oracle Corporation
*
* Development Environment : Oracle9i JDeveloper
* Creation / Modification History
* Abhijeet Kulkarni 1-July-2003 Created
*
*/


//Package definition
package oracle.otnsamples.orajaxb;


//Importing the required classes generated by the JAXB Class Generator
import jaxbderived.profile.Address;
import jaxbderived.profile.Claims;
import jaxbderived.profile.Profile;
import jaxbderived.profile.Customer;
import jaxbderived.profile.Record;
import jaxbderived.profile.ObjectFactory;

//Importing the required IO classes
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.PrintWriter;
import java.io.StringWriter;

import java.net.URL;

//Importing the required utility classes
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;

//Importing the required Swing classes
import javax.swing.JTextArea;

//Importing the required XML classes
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;


/**
* This is the base class that implements IProfileManager interface. This class
* is extended by DBRecordHolder class to offer functionality specific to
* database storage handling. This class has methods that allow users to
* navigate and manage list of Record objects. It also has support methods
* that is used to load sample Record objects from the local directory.
*/

public class RecordHolder implements IProfileManager {
public Record currentRecord;
protected JTextArea textArea;
protected List list = Collections.synchronizedList(new ArrayList());
protected ListIterator listiterator = null;
protected MainFrame mainFrame;
protected String dirPath = null;
protected boolean valid = false;

/**
* Creates a new RecordHolder object.
*
* @param frame Reference to the MainFrame object
* @param area Reference to the text area where message logs are displayed
*/

public RecordHolder(MainFrame frame, JTextArea area) {
mainFrame = frame;
textArea = area;
}

/**
* Returns the previous record in the list
*
* @param rec Reference to the current record object
*
* @return Reference to the previous object
*/

public Record getPreviousRecord(Record rec) {
try {
int i = list.indexOf(currentRecord);

list.set(i, rec);

if (i >= 0) {
currentRecord = (Record) list.get(i - 1);
} else {
currentRecord = (Record) list.get(i);
}
} catch (Exception e) {
} finally {
return currentRecord;
}
}

/**
* Returns reference of the next record
*
* @param rec Reference to the current record object
*
* @return Reference to the next object
*/

public Record getNextRecord(Record rec) {
try {
int i = list.indexOf(currentRecord);

list.set(i, rec);

if (i < (list.size() - 1)) {
currentRecord = (Record) list.get(++i);
} else {
currentRecord = (Record) list.get(i);
}
} catch (Exception e) {
} finally {
return currentRecord;
}
}

/**
* Saves the current record
*
* @param rec Saves the current record in the active database repository
*/

public void saveRecord(Record rec) {
try {
//Create a JAXBContext instance
JAXBContext jc = JAXBContext.newInstance(
"jaxbderived.profile"
);
String filename = null;
if ( !dirPath.endsWith(".xml"))
filename = dirPath + "/" + currentRecord.getCustomerID() +".xml";
else filename = dirPath;

textArea.append(" Saving file " + filename + "\n");

File f = new File(filename);

f.delete();

//Create a marshaler object
Marshaller m = jc.createMarshaller();
StringWriter swriter = new StringWriter();

//Marshal the record object
m.marshal(rec, swriter);

//Store the marshaled object in the String
String s = swriter.toString();

//Output this String to a file
FileOutputStream fout = new FileOutputStream(filename);
PrintWriter pw = new PrintWriter(fout);

pw.write(s);

//Flush and close file and printWriter
pw.flush();

if (pw != null) {
pw.close();
}

if (fout != null) {
fout.close();
}

textArea.append("Record saved... \n");
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* Creates a new record
*
* @return Creates an empty new record with the help of getEmptyRecord()
*/

public Record createNewRecord() {
//Create an empty record object
Record r = this.getEmptyRecord();

//Point currentRecord to newly created object
currentRecord = r;

//Add newly created object to list
list.add(list.size(), r);

//Update the listiterator object
listiterator = list.listIterator(list.size() - 1);

return currentRecord;
}

/**
* Removes newly created record
*
* @return Returns reference to previous Record
*/

public Record removeNewRecord() {
list.remove(currentRecord);
currentRecord = (Record) list.get(list.size() - 1);

return currentRecord;
}

/**
* Loads the profile data from the directory specified by the user
*/

public void loadData() {
//Create a FileFilter class
class ProfileFilter implements FilenameFilter {
/**
* Filter class
*
* @param dir File / Directory reference
* @param name Name of the file / directory
*
* @return boolean value
*/

public boolean accept(File dir, String name) {
//Select only those files that match the filter prof*.xml
if ((name.startsWith("prof") && (name.endsWith("xml")))) {
return true;
} else {
return false;
}
}
}

//Create ProfileFilter instance
ProfileFilter pf = new ProfileFilter();
File f = new File(dirPath);

//Get listing of the files present in the current directory
String [] farr = f.list(pf);

textArea.append("Number of files that match filter prof*.xml " +
farr.length + "\n"
);
textArea.append("Reading files and creating Record objects \n");
textArea.append("This may take some time. Please wait... \n\n");

for (int i = 0; i < farr.length; i++) {
try {
//Create a JAXBContext instance
JAXBContext jc = JAXBContext.newInstance(
"jaxbderived.profile"
);

//Create an unmarshaller instance
Unmarshaller u = jc.createUnmarshaller();

u.setValidating(true);

textArea.append("Reading file " + farr[i] + "\n");
//Unmarshal the Record object from FileInputStream
Record rec = (Record) u.unmarshal(fileToURL(dirPath+"/"+farr[i]));

//Store the object in the list
list.add(rec);
} catch (Exception ex) {
textArea.append("There was an error while parsing \n" + farr[i]+
"\nThis file will be ignored. \n"
);
textArea.append(
"Please note that this error is thrown when the source XML does not "
);
textArea.append(
"confirm to the Profile Record \nSchema definition. The error is given below \n"
);
textArea.append(ex.toString() +"\n\n");
} finally {
}
}

textArea.append(list.size() + " records have been loaded \n ");

//Get the listiterator reference
listiterator = list.listIterator(0);

//Advance the listiterator by 1
try {
listiterator.next();
} catch (Exception ex) {
}
}

/**
* Sets the directory where sample Records are stored
*
* @param s The directory where sample profile data is present
*/

public void setDirPath(String s) {
dirPath = s;
}

/**
* Checks if the current record is the last record
*
* @return Returns true if the current record is the last record in the
* list
*/

public boolean isLastRecord() {
int i = list.indexOf(currentRecord);

if (i == (list.size() - 1)) {
return true;
} else {
return false;
}
}

/**
* Checks if the current record is the first record
*
* @return Returns true if the current record is the first record in the
* list
*/

public boolean isFirstRecord() {
int i = list.indexOf(currentRecord);

if (i == 0) {
return true;
} else {
return false;
}
}

/**
* Returns the number of Record objects present in the list
*
* @return Returns the number of Record objects present in the list
*/

public int getSize() {
return list.size();
}

/**
* Returns reference of the first record in the list
*
* @return Returns the reference to the first record in the list
*/

public Record getFirstRecord() {
currentRecord = (Record) list.get(0);

return currentRecord;
}

/**
* Gets an empty Record object
*
* @return Returns a reference to an empty Record object
*/

public Record getEmptyRecord() {
Record rec = null;

try {
//Create new ObjectFactory instance
ObjectFactory ofact = new ObjectFactory();

rec = ofact.createRecord();

Calendar c = Calendar.getInstance();
String str = "prof";

str = str + c.get(Calendar.YEAR) + (c.get(Calendar.MONTH) + 1) +
c.get(Calendar.DATE) + c.get(Calendar.HOUR_OF_DAY) +
c.get(Calendar.MINUTE) + c.get(Calendar.SECOND);
rec.setCustomerID(str);

//Create Customer object
Customer cust = ofact.createCustomer();

cust.setFirstName("");
cust.setLastName("");
cust.setGender("");
cust.setBirthDate("");
rec.setCustomerRec(cust);

//Create Address object
Address addr = ofact.createAddress();

addr.setLine1("");
addr.setLine2("");
addr.setCity("");
addr.setCountry("");
addr.setZip(0);
rec.setAddressRec(addr);

//Create Profile Object
Profile pf = ofact.createProfile();

pf.setCustomerType("Bronze");
pf.setPremiumAmount((float) 0);
pf.setPremiumMode("Monthly");
pf.setRating("Average");
rec.setProfileRec(pf);

//Create Claims object
Claims claims = ofact.createClaims();
List list = claims.getClaim();

rec.setClaimsRec(claims);
} catch (Exception e) {
}

return rec;
}

/**
* Returns unique claim id
*
* @return Returns a unique string that will be used as claim ID.
*/

public String getClaimID() {
Calendar c = Calendar.getInstance();
String str = "c" + c.get(Calendar.DATE) + c.get(Calendar.HOUR_OF_DAY) +
c.get(Calendar.MINUTE) + c.get(Calendar.SECOND);

return str;
}

/**
* This method loads a single Profile Record Object in the list.
*/

public void loadSingleRecord() {
textArea.append("This may take some time. Please wait... \n");

try {
//Create a JAXBContext instance
JAXBContext jc = JAXBContext.newInstance(
"jaxbderived.profile"
);

//Create an unmarshaller instance
Unmarshaller u = jc.createUnmarshaller();
u.setValidating(true);
textArea.append("\nReading file " + dirPath + "\n");

//Unmarshal the Record object from FileInputStream
Record rec = (Record) u.unmarshal(fileToURL(dirPath));

//Store the object in the list
list.add(rec);
textArea.append("One record loaded.\n Size of the list is " +
list.size() + " \n"
);
} catch (Exception ex) {
textArea.append("There was an error while parsing \n" + dirPath +
"\nThis file will be ignored. \n"
);
textArea.append(
"Please note that this error is thrown when the source XML does not "
);
textArea.append(
"confirm to the Profile Record \nSchema definition. The error is given below \n"
);
textArea.append(ex.toString() +"\n\n");
} finally {
}
}

/**
* Returns Record present in "i"th location
*
* @param i index
*
* @return Returns reference to a Record object
*/

public Record getRecord(int i ) {
return (Record ) list.get(i);
}

/**
* Sets the current record reference
*
* @param r Reference to record object
*/

public void setCurrentRecord(Record r) {
this.currentRecord = r;
}

/**
* Updates the Record list with respect to the data present in the UI controls
*
* @param r Reference to record object
*/

public void updateCurrentRecord(Record r) {
try {
int i = list.indexOf(currentRecord);
list.set(i, r);
currentRecord = r;
} catch (Exception e) {
}
}

/**
* This method changes the file path to URL path
*
* @param sfile A String containing the location of the file or directory
* @return URL URL representation of the file or directory location
*/

private static URL fileToURL(String sfile)
{
File file = new File(sfile);
String path = file.getAbsolutePath();
String fSep = System.getProperty("file.separator");
if (fSep != null && fSep.length() == 1)
path = path.replace(fSep.charAt(0), '/');
if (path.length() > 0 && path.charAt(0) != '/')
path = '/' + path;
try
{
return new URL("file" , null, path);
}
catch (java.net.MalformedURLException e)
{
throw new Error("Error: Unexpected MalformedURLException");
}
}
}

E-mail this page
Printer View Printer View
Oracle Is The Information Company About Oracle | Oracle RSS Feeds | Careers | Contact Us | Site Maps | Legal Notices | Terms of Use | Privacy