From: pinene Date: Sat, 7 Mar 2015 13:48:38 +0000 (+0100) Subject: unification with the actual initial project. Some things are new now, but there has... X-Git-Url: https://xp-dev.com/git/RRRRHHHH_Code/commitdiff_plain/06a849f3febf443d051a11bf7e4eea56c4ec6740 unification with the actual initial project. Some things are new now, but there has been a feature that has been deleted.\n The feature of opening and closing the database per each query/store has been deleted by now --- diff --git a/ruralHouses/.DS_Store b/ruralHouses/.DS_Store new file mode 100644 index 0000000..4eec472 Binary files /dev/null and b/ruralHouses/.DS_Store differ diff --git a/ruralHouses/.classpath b/ruralHouses/.classpath index 70ef287..3caf01b 100644 --- a/ruralHouses/.classpath +++ b/ruralHouses/.classpath @@ -1,17 +1,8 @@ - - - - - - - - - - - - + + + diff --git a/ruralHouses/.gitignore b/ruralHouses/.gitignore index aeb337b..2a22d9f 100644 --- a/ruralHouses/.gitignore +++ b/ruralHouses/.gitignore @@ -1,3 +1,4 @@ /bin /lib /db +/src/*/*.class \ No newline at end of file diff --git a/ruralHouses/config.xml b/ruralHouses/config.xml new file mode 100644 index 0000000..e431b73 --- /dev/null +++ b/ruralHouses/config.xml @@ -0,0 +1,19 @@ + + + + localhost + 1099 + RuralHouses + + + localhost + db/casas.db4o + initialize + 5 + 5 + 8100 + softEng + i4softwEngin2matx + +java.policy + \ No newline at end of file diff --git a/ruralHouses/db/DBjcampos004.yap b/ruralHouses/db/DBjcampos004.yap deleted file mode 100644 index 212f8cd..0000000 Binary files a/ruralHouses/db/DBjcampos004.yap and /dev/null differ diff --git a/ruralHouses/java.policy b/ruralHouses/java.policy new file mode 100644 index 0000000..a38bc88 --- /dev/null +++ b/ruralHouses/java.policy @@ -0,0 +1,9 @@ +grant { +permission java.security.AllPermission; +}; +// If there problems with permissions: +// permission java.security.AllPermission; +//permission java.net.SocketPermission "localhost:1099", "connect,resolve"; +//permission java.net.SocketPermission "*", "accept,resolve"; +//permission java.io.FilePermission "casas.db4o", "delete,read,write"; +//permission java.util.PropertyPermission "*", "read"; \ No newline at end of file diff --git a/ruralHouses/src/businessLogic/.DS_Store b/ruralHouses/src/businessLogic/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/ruralHouses/src/businessLogic/.DS_Store differ diff --git a/ruralHouses/src/businessLogic/ApplicationFacadeInterface.java b/ruralHouses/src/businessLogic/ApplicationFacadeInterface.java index ef3cad2..5cf74f5 100644 --- a/ruralHouses/src/businessLogic/ApplicationFacadeInterface.java +++ b/ruralHouses/src/businessLogic/ApplicationFacadeInterface.java @@ -2,25 +2,29 @@ package businessLogic; import java.rmi.*; import java.util.Vector; -import java.util.Date; +import java.sql.Date; import domain.Booking; import domain.Offer; import domain.Owner; import domain.RuralHouse; -import exceptions.OfferCanNotBeBooked; + + +import exceptions.OfferCanNotBeBooked; + public interface ApplicationFacadeInterface extends Remote { + /** - * This method creates an offer with a house number, first day, last day and - * price + * This method creates an offer with a house number, first day, last day and price * * @param House * number, start day, last day and price * @return None */ + Offer createOffer(RuralHouse ruralHouse, Date firstDay, Date lastDay, float price) throws RemoteException, Exception; @@ -32,41 +36,28 @@ public interface ApplicationFacadeInterface extends Remote { * @return a book */ Booking createBooking(RuralHouse ruralHouse, Date firstDay, Date lastDay, - String telephoneNumber) throws RemoteException, OfferCanNotBeBooked; - - /** - * This method obtains available offers for a concrete house in a certain - * period - * - * @param houseNumber - * , the house number where the offers must be obtained - * @param firstDay - * , first day in a period range - * @param lastDay - * , last day in a period range - * @return a vector of offers(Offer class) available in this period - */ - Vector getOffers(RuralHouse houseNumber, Date firstDay, Date lastDay) - throws RemoteException, Exception; + String telephoneNumber) throws RemoteException, + OfferCanNotBeBooked; + /** - * This method finds existing owners + * This method retrieves the existing owners * + * @return a Set of owners */ - public Vector getOwners() throws RemoteException, Exception; - + public Vector getOwners() throws RemoteException, + Exception; + /** - * This method obtains an owner's rural houses - * - * @param owner - * object + * This method retrieves the existing rural houses * - * @return a vector of Rural Houses + * @return a Set of rural houses */ - public Vector getRuralHouses(Owner owner) - throws RemoteException; + public Vector getAllRuralHouses()throws RemoteException, + Exception; + + public void close() throws RemoteException; - public Vector getAllRuralHouses() throws RemoteException, - Exception; + } \ No newline at end of file diff --git a/ruralHouses/src/businessLogic/BusinessLogicServer.java b/ruralHouses/src/businessLogic/BusinessLogicServer.java new file mode 100644 index 0000000..4050bbb --- /dev/null +++ b/ruralHouses/src/businessLogic/BusinessLogicServer.java @@ -0,0 +1,129 @@ +package businessLogic; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.rmi.Naming; +import java.rmi.RMISecurityManager; +import java.rmi.RemoteException; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.border.EmptyBorder; + +import configuration.ConfigXML; + +import javax.swing.JTextArea; + +import dataAccess.DB4oManager; + +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; + +public class BusinessLogicServer extends JDialog { + + private final JPanel contentPanel = new JPanel(); + JTextArea textArea; + ApplicationFacadeInterface server; + + /** + * Launch the application. + */ + public static void main(String[] args) { + try { + BusinessLogicServer dialog = new BusinessLogicServer(); + dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + dialog.setVisible(true); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Create the dialog. + */ + public BusinessLogicServer() { + setTitle("BusinessLogicServer: running the business logic"); + setBounds(100, 100, 486, 209); + getContentPane().setLayout(new BorderLayout()); + contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); + getContentPane().add(contentPanel, BorderLayout.CENTER); + contentPanel.setLayout(new BorderLayout(0, 0)); + { + textArea = new JTextArea(); + contentPanel.add(textArea); + } + { + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); + getContentPane().add(buttonPane, BorderLayout.SOUTH); + { + JButton okButton = new JButton("OK"); + okButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + textArea.append("\n\n\nClosing the server... "); + try { + server.close(); + } catch (RemoteException e1) { + } + System.exit(1); + } + }); + okButton.setActionCommand("OK"); + buttonPane.add(okButton); + getRootPane().setDefaultButton(okButton); + } + { + JButton cancelButton = new JButton("Cancel"); + cancelButton.setActionCommand("Cancel"); + buttonPane.add(cancelButton); + } + } + + ConfigXML c=ConfigXML.getInstance(); + + + System.setProperty("java.security.policy", c.getJavaPolicyPath()); + + + System.setSecurityManager(new RMISecurityManager()); + + try { + java.rmi.registry.LocateRegistry.createRegistry(Integer.parseInt(c.getPortRMI())); + // Create RMIREGISTRY + } catch (Exception e) { + textArea.append(e.toString() + "Rmiregistry already running."); + } + + try { + + try{ + server = new FacadeImplementation(); + } + catch (com.db4o.ext.DatabaseFileLockedException e) { + System.out.println("Error in BusinessLogicServer: "+e.toString()); + textArea.append("\nYou should have not launched DB4oManagerServer...\n"); + textArea.append("\n\nOr maybe there is a BusinessLogicServer already launched...\n"); + throw e; + } + + + String service= "//"+c.getBusinessLogicNode() +":"+ c.getPortRMI()+"/"+c.getServiceRMI(); + + // Register the remote server + Naming.rebind(service, server); + textArea.append("Running service at:\n\t" + service); + //This operation removes the actual database and initialize with predefined values + + textArea.append("\n\n\nPress button to exit this server... "); + + } catch (Exception e) { + textArea.append(e.toString()); + } + + } + +} + diff --git a/ruralHouses/src/businessLogic/FacadeImplementation.java b/ruralHouses/src/businessLogic/FacadeImplementation.java index 0caab61..b97613d 100644 --- a/ruralHouses/src/businessLogic/FacadeImplementation.java +++ b/ruralHouses/src/businessLogic/FacadeImplementation.java @@ -2,94 +2,112 @@ package businessLogic; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; -import java.util.Date; -import java.util.Vector; +import java.sql.Date; import java.sql.SQLException; +import java.util.Vector; import com.db4o.ObjectContainer; import com.db4o.ObjectSet; -import configuration.Config; +import configuration.ConfigXML; import dataAccess.DB4oManager; import domain.Booking; import domain.Offer; import domain.Owner; import domain.RuralHouse; +import exceptions.BadDates; +import exceptions.DB4oManagerCreationException; import exceptions.OfferCanNotBeBooked; +import exceptions.OverlappingOfferExists; + public class FacadeImplementation extends UnicastRemoteObject implements ApplicationFacadeInterface { + /** + * + */ private static final long serialVersionUID = 1L; - DB4oManager dbMngr; - public FacadeImplementation() throws RemoteException, InstantiationException, - IllegalAccessException, ClassNotFoundException, SQLException { - dbMngr = DB4oManager.getInstance(); - } + Vector owners; + Vector ruralHouses; + DB4oManager dB4oManager; + - - public Offer createOffer(RuralHouse ruralHouse, Date firstDay, Date lastDay, - float price) throws RemoteException, Exception { - return dbMngr.createOffer(ruralHouse, firstDay, lastDay, price); + public FacadeImplementation() throws RemoteException, InstantiationException, + IllegalAccessException, ClassNotFoundException, SQLException, DB4oManagerCreationException { + owners=null; + ruralHouses=null; + try{ + dB4oManager=DB4oManager.getInstance(); + } + catch (com.db4o.ext.DatabaseFileLockedException e) { + System.out.println("Error in FacadeImplementation: "+e.toString()); + throw e; + } + catch (Exception e) { + System.out.println("Error in FacadeImplementation: "+e.toString()); + throw new DB4oManagerCreationException(); + } } + /** - * This method obtains available offers for a concrete house in a certain period + * This method creates an offer with a house number, first day, last day and price * - * @param houseNumber, the house number where the offers must be obtained - * @param firstDay, first day in a period range - * @param lastDay, last day in a period range - * @return a vector of offers(Offer class) available in this period + * @param House + * number, start day, last day and price + * @return the created offer, or null, or an exception */ - public Vector getOffers(RuralHouse house,Date firstDay, Date lastDay) throws RemoteException, - Exception { - return house.getOffers(firstDay, lastDay); - + public Offer createOffer(RuralHouse ruralHouse, Date firstDay, Date lastDay, + float price) throws OverlappingOfferExists, BadDates, RemoteException, Exception { + if (firstDay.compareTo(lastDay)>=0) throw new BadDates(); + ruralHouses=null; + owners=null; + boolean b = dB4oManager.existsOverlappingOffer(ruralHouse,firstDay,lastDay); // The ruralHouse object in the client may not be updated + if (!b) return dB4oManager.createOffer(ruralHouse,firstDay,lastDay,price); + return null; } + /** - * This method finds all existing owners + * This method creates a book with a corresponding parameters * + * @param First + * day, last day, house number and telephone + * @return a book */ - public Vector getOwners() throws RemoteException, - Exception { - return dbMngr.getOwners(); - } + public Booking createBooking(RuralHouse ruralHouse, Date firstDate, Date lastDate, String bookTelephoneNumber) + throws OfferCanNotBeBooked { + ruralHouses=null; + owners=null; + return dB4oManager.createBooking(ruralHouse,firstDate,lastDate,bookTelephoneNumber); + } + /** - * This method obtains an owner's rural houses + * This method existing owners * - * @param owner object - * - * @return a vector of Rural Houses */ - public Vector getRuralHouses(Owner owner) - throws RemoteException { - return owner.getRuralHouses(); + public Vector getOwners() throws RemoteException, + Exception { + + if (owners!=null) { System.out.println("Owners obtained directly from business logic layer"); + return owners; } + else return owners=dB4oManager.getOwners(); } - - + public Vector getAllRuralHouses() throws RemoteException, - Exception { - return dbMngr.getAllRuralHouses(); - } + Exception { + + if (ruralHouses!=null) { System.out.println("RuralHouses obtained directly from business logic layer"); + return ruralHouses; } + else return ruralHouses=dB4oManager.getAllRuralHouses(); + } + public void close() throws RemoteException{ + dB4oManager.close(); - public Booking createBooking(RuralHouse ruralHouse, Date firstDate, Date lastDate, String bookTelephoneNumber) - throws OfferCanNotBeBooked { - try { - RuralHouse rh=dbMngr.getRuralHouse(ruralHouse); - Offer offer = rh.findOffer(firstDate, lastDate); - Booking b=dbMngr.createBooking(offer,bookTelephoneNumber); - return b; - } catch (Exception exc) { - exc.printStackTrace(); - return null; - } - } - - -} + } diff --git a/ruralHouses/src/configuration/.DS_Store b/ruralHouses/src/configuration/.DS_Store new file mode 100644 index 0000000..02896dc Binary files /dev/null and b/ruralHouses/src/configuration/.DS_Store differ diff --git a/ruralHouses/src/configuration/ConfigXML.java b/ruralHouses/src/configuration/ConfigXML.java new file mode 100644 index 0000000..ca4a156 --- /dev/null +++ b/ruralHouses/src/configuration/ConfigXML.java @@ -0,0 +1,175 @@ +package configuration; + +import java.io.File; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class ConfigXML { + private String businessLogicNode; + + private String portRMI; + + private String serviceRMI; + + private String javaPolicyPath; + + private static String db4oFilename; + + //Two possible values: "open" or "initialize" + private String dataBaseOpenMode; + + //Two possible values: true (no instance of RemoteServer needs to be launched) or false (RemoteServer needs to be run first) + private boolean businessLogicLocal; + + //Two possible values: true (if the database is in same node as business logic ) or false (in other case) + private boolean databaseLocal; + + private String databaseNode; + + private int activationDepth; + + private int updateDepth; + + private int databasePort; + + private String user; + + private String password; + + public int getDatabasePort() { + return databasePort; + } + + public String getUser() { + return user; + } + + public String getPassword() { + return password; + } + + public int getActivationDepth() { + return activationDepth; + } + + public int getUpdateDepth() { + return updateDepth; + } + + public boolean isDatabaseLocal() { + return databaseLocal; + } + + public boolean isBusinessLogicLocal() { + return businessLogicLocal; + } + private static ConfigXML theInstance = new ConfigXML(); + + private ConfigXML(){ + + try { + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); + Document doc = dBuilder.parse(new File("config.xml")); + doc.getDocumentElement().normalize(); + + NodeList list = doc.getElementsByTagName("config"); + Element config = (Element) list.item(0); // list.item(0) is a Node that is an Element + + + //Two possible values: true (no instance of RemoteServer needs to be launched) or false (RemoteServer needs to be run first) + String value= ((Element)config.getElementsByTagName("businessLogic").item(0)).getAttribute("local"); + businessLogicLocal=value.equals("true"); + + businessLogicNode = getTagValue("businessLogicNode", config); + + portRMI = getTagValue("portRMI", config); + + serviceRMI = getTagValue("serviceRMI", config); + + javaPolicyPath= getTagValue("javaPolicyPath", config); + + db4oFilename = getTagValue("db4oFilename", config); + + //Two possible values: true (no instance of RemoteServer needs to be launched) or false (RemoteServer needs to be run first) + value= ((Element)config.getElementsByTagName("database").item(0)).getAttribute("local"); + databaseLocal=value.equals("true"); + + + //Two possible values: "open" or "initialize" + dataBaseOpenMode= getTagValue("dataBaseOpenMode", config); + + + databaseNode = getTagValue("databaseNode", config); + + activationDepth=Integer.parseInt(getTagValue("activationDepth", config)); + + updateDepth=Integer.parseInt(getTagValue("updateDepth", config)); + + + databasePort=Integer.parseInt(getTagValue("databasePort", config)); + + user=getTagValue("user", config); + + password=getTagValue("password", config); + + System.out.print("Read from config.xml: "); + System.out.print("\t businessLogicLocal="+businessLogicLocal); + System.out.print("\t databaseLocal="+databaseLocal); + System.out.println("\t dataBaseOpenMode="+dataBaseOpenMode); + + } catch (Exception e) { + System.out.println("Error in ConfigXML.java: problems with config.xml"); + e.printStackTrace(); + } + + + + + } + + private static String getTagValue(String sTag, Element eElement) + { + NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes(); + Node nValue = (Node) nlList.item(0); + + return nValue.getNodeValue(); + + } + + public static ConfigXML getInstance() { + return theInstance; + } + + public String getBusinessLogicNode() { + return businessLogicNode; + } + + public String getPortRMI() { + return portRMI; + } + + public String getServiceRMI() { + return serviceRMI; + } + public String getDb4oFilename(){ + return db4oFilename; + } + public String getJavaPolicyPath(){ + return javaPolicyPath; + } + public String getDataBaseOpenMode(){ + return dataBaseOpenMode; + } + + public String getDatabaseNode() { + return databaseNode; + } + +} diff --git a/ruralHouses/src/dataAccess/.DS_Store b/ruralHouses/src/dataAccess/.DS_Store new file mode 100644 index 0000000..de29268 Binary files /dev/null and b/ruralHouses/src/dataAccess/.DS_Store differ diff --git a/ruralHouses/src/dataAccess/DB4oManager.java b/ruralHouses/src/dataAccess/DB4oManager.java index b0e4005..45f847c 100644 --- a/ruralHouses/src/dataAccess/DB4oManager.java +++ b/ruralHouses/src/dataAccess/DB4oManager.java @@ -1,126 +1,282 @@ package dataAccess; import java.io.File; -import java.rmi.RemoteException; -import java.util.Date; -import java.util.Vector; //import java.util.Enumeration; //import java.util.Vector; -import businessLogic.BookingManager; -import com.db4o.*; +import java.rmi.RemoteException; +import java.sql.Date; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Vector; -import configuration.Config; -import domain.*; +import com.db4o.*; +import com.db4o.config.EmbeddedConfiguration; +import com.db4o.cs.Db4oClientServer; +import com.db4o.cs.config.ClientConfiguration; + +import configuration.ConfigXML; +import domain.Account; +import domain.Booking; +import domain.Offer; +//import dataModel.Offer; +import domain.Owner; +import domain.RuralHouse; import exceptions.OfferCanNotBeBooked; +import exceptions.OverlappingOfferExists; +public class DB4oManager { + + private static ObjectContainer db; + private static EmbeddedConfiguration configuration; + private static ClientConfiguration configurationCS; + private int bookingNumber=0; // if it is "static" then it is not serialized + private int offerNumber=0; // if it is "static" then it is not serialized + private static DB4oManager theDB4oManager=null; + + private static DB4oManagerAux theDB4oManagerAux; + static ConfigXML c; + + private DB4oManager() throws Exception { + theDB4oManagerAux=new DB4oManagerAux(0,0); + c=ConfigXML.getInstance(); + System.out.println("Creating DB4oManager instance => isDatabaseLocal: "+c.isDatabaseLocal()+" getDatabBaseOpenMode: "+c.getDataBaseOpenMode()); + + + if ((c.getDataBaseOpenMode().equals("initialize")) && (c.isDatabaseLocal())) + new File(c.getDb4oFilename()).delete(); + + if (c.isDatabaseLocal()) + { + configuration = Db4oEmbedded.newConfiguration(); + configuration.common().activationDepth(c.getActivationDepth()); + configuration.common().updateDepth(c.getUpdateDepth()); + db=Db4oEmbedded.openFile(configuration, c.getDb4oFilename()); + System.out.println("DataBase opened"); + } + else // c.isDatabaseLocal==false + { + openObjectContainer(); + } + if (c.getDataBaseOpenMode().equals("initialize")) + { initializeDB(); + System.out.println("DataBase initialized"); + } + else // c.getDataBaseOpenMode().equals("open") + + { + ObjectSet res =db.queryByExample(DB4oManagerAux.class); + ListIterator listIter = res.listIterator(); + if (listIter.hasNext()) theDB4oManagerAux = (DB4oManagerAux) res.next(); + } + } -public class DB4oManager { + private static void openDB(){ + configuration = Db4oEmbedded.newConfiguration(); + configuration.common().activationDepth(c.getActivationDepth()); + configuration.common().updateDepth(c.getUpdateDepth()); + db=Db4oEmbedded.openFile(configuration, c.getDb4oFilename()); + } + + private void openObjectContainer(){ + + configurationCS = Db4oClientServer.newClientConfiguration(); + configurationCS.common().activationDepth(c.getActivationDepth()); + configurationCS.common().updateDepth(c.getUpdateDepth()); + configurationCS.common().objectClass(Owner.class).cascadeOnDelete(true); + db = Db4oClientServer.openClient(configurationCS,c.getDatabaseNode(), + c.getDatabasePort(),c.getUser(),c.getPassword()); - private static ObjectContainer db; - private static DB4oManager theDB4oManager = new DB4oManager(); + } + + class DB4oManagerAux { + int bookingNumber; + int offerNumber; + DB4oManagerAux(int bookingNumber,int offerNumber){ + this.bookingNumber=bookingNumber; + this.offerNumber=offerNumber; + } + } - /** - * - */ - private DB4oManager() { - Config c = Config.getInstance(); - String dataBaseOpenMode = c.getDataBaseOpenMode(); - DB4oManager.openDatabase(dataBaseOpenMode); + public static DB4oManager getInstance() throws Exception{ + if (theDB4oManager==null) + theDB4oManager=new DB4oManager(); + return theDB4oManager; + } + + + public void initializeDB(){ + + try { + Owner jon = new Owner("Jon"); + Owner alfredo = new Owner("Alfredo"); + jon.addRuralHouse(1, "Ezkioko etxea", "Ezkio", 3, 3, 3, 3, 3); + jon.addRuralHouse(2, "Eskiatzeko etxea", "Jaca", 4, 4, 4, 4, 4); + jon.setBankAccount("1349 5677 21 2133567777"); + alfredo.addRuralHouse(3, "Casa del abuelo", "Pitillas", 5, 5, + 5, 5, 5); + alfredo.addRuralHouse(4,"", "Murgia", 6, 6, 6, 6, 6); + alfredo.setBankAccount("4144 0087 23 9700002133"); + Account jonAcc = new Account("userJon", "passJon", jon); + Account alfredoAcc = new Account("userAlfredo", "passAlfredo", + alfredo); + db.store(jon); + db.store(alfredo); + db.store(jonAcc); + db.store(alfredoAcc); + db.commit(); + } + finally { + //db.close(); + } + } + + @SuppressWarnings("finally") + public Offer createOffer(RuralHouse ruralHouse, Date firstDay, Date lastDay, + float price) throws RemoteException, Exception { + Offer o = null; + try { + + if (c.isDatabaseLocal()==false) openObjectContainer(); + + + RuralHouse proto = new RuralHouse(ruralHouse.getHouseNumber(),null,null,null,null); + ObjectSet result = db.queryByExample(proto); + RuralHouse rh=(RuralHouse)result.next(); + o=rh.createOffer(theDB4oManagerAux.offerNumber++,firstDay, lastDay, price); + db.store(theDB4oManagerAux); // To store the new value for offerNumber + db.store(o); + db.commit(); + + } + catch (com.db4o.ext.ObjectNotStorableException e){ + System.out.println("Error: com.db4o.ext.ObjectNotStorableException in createOffer"); + } + finally { + return o; + } + } + + public void deleteDB() { + + try { + Owner proto = new Owner(null,null); + ObjectSet result = db.queryByExample(proto); + Vector owners=new Vector(); + while(result.hasNext()) + { Owner o = (Owner)result.next(); + System.out.println("Deleted owner: "+o.toString()); + db.delete(o); + } + db.commit(); + } finally { + // db.close(); + } } /** - * @param mode + * This method creates a book with a corresponding parameters + * + * @param First + * day, last day, house number and telephone + * @return a book */ - public static void openDatabase(String mode) { - Config c = Config.getInstance(); - String db4oFileName = c.getDb4oFilename(); - if (mode.compareTo("open") == 0) { - db = Db4o.openFile(Db4o.newConfiguration(), db4oFileName); - db.ext().configure().updateDepth(5); + public Booking createBooking(RuralHouse ruralHouse, Date firstDate, Date lastDate, String bookTelephoneNumber) + throws OfferCanNotBeBooked { + + try { + + if (c.isDatabaseLocal()==false) openObjectContainer(); + + RuralHouse proto = new RuralHouse(ruralHouse.getHouseNumber(),null,ruralHouse.getDescription(),ruralHouse.getTown(), null); + ObjectSet result = db.queryByExample(proto); + RuralHouse rh=(RuralHouse)result.next(); + Offer offer; + offer = rh.findOffer(firstDate, lastDate); - } else if (mode.compareTo("initialize") == 0) { - try { - new File(db4oFileName).delete(); - db = Db4o.openFile(Db4o.newConfiguration(), db4oFileName); - db.ext().configure().updateDepth(5); - Owner jon = new Owner("Jon"); - Owner alfredo = new Owner("Alfredo"); - jon.addRuralHouse(1, "Ezkioko etxea", "Ezkio", 3, 3, 3, 3, 3); - jon.addRuralHouse(2, "Eskiatzeko etxea", "Jaca", 4, 4, 4, 4, 4); - jon.setBankAccount("1349 5677 21 2133567777"); - alfredo.addRuralHouse(3, "Casa del abuelo", "Pitillas", 5, 5, - 5, 5, 5); - alfredo.addRuralHouse(4,"", "Murgia", 6, 6, 6, 6, 6); - alfredo.setBankAccount("4144 0087 23 9700002133"); - Account jonAcc = new Account("userJon", "passJon", jon); - Account alfredoAcc = new Account("userAlfredo", "passAlfredo", - alfredo); - db.store(jon); - db.store(alfredo); - db.store(jonAcc); - db.store(alfredoAcc); + if (offer!=null) { + offer.createBooking(theDB4oManagerAux.bookingNumber++, bookTelephoneNumber); + db.store(theDB4oManagerAux); // To store the new value for bookingNumber + db.store(offer); db.commit(); - System.out.println("DataBase Initialized"); - } finally { - db.close(); + return offer.getBooking(); } + return null; + } catch (com.db4o.ext.ObjectNotStorableException e){ + System.out.println("Error: com.db4o.ext.ObjectNotStorableException in createBooking"); + return null; + } + catch (Exception exc) { + exc.printStackTrace(); + return null; } } + /** - * @return + * This method existing owners + * */ - public static ObjectContainer getContainer() { - return db; + public Vector getOwners() throws RemoteException, + Exception { + + if (c.isDatabaseLocal()==false) openObjectContainer(); + + try { + Owner proto = new Owner(null,null); + ObjectSet result = db.queryByExample(proto); + Vector owners=new Vector(); + while(result.hasNext()) + owners.add((Owner)result.next()); + return owners; + } finally { + //db.close(); + } + } + public Vector getAllRuralHouses() throws RemoteException, + Exception { + if (c.isDatabaseLocal()==false) openObjectContainer(); + + try { + RuralHouse proto = new RuralHouse(0,null,null,null,null); + ObjectSet result = db.queryByExample(proto); + Vector ruralHouses=new Vector(); + while(result.hasNext()) + ruralHouses.add((RuralHouse)result.next()); + return ruralHouses; + } finally { + // db.close(); + } + } + + public boolean existsOverlappingOffer(RuralHouse rh,Date firstDay, Date lastDay) throws RemoteException, OverlappingOfferExists{ + try { + if (c.isDatabaseLocal()==false) openObjectContainer(); + + RuralHouse rhn = (RuralHouse) db.queryByExample(new RuralHouse(rh.getHouseNumber(),null,null,null,null)).next(); + if (rhn.overlapsWith(firstDay, lastDay)!=null) throw new OverlappingOfferExists(); + else return false; + } finally { + //db.close(); + } } - - /** - * @param rh - */ - public boolean storeRuralHouses(RuralHouse rh) { - DB4oManager.openDatabase("open"); - boolean stored = false; - ObjectContainer db = DB4oManager.getContainer(); - RuralHouse house = new RuralHouse(rh.getHouseNumber(), null, null, - null, null); - try { - ObjectSet result = db.queryByExample(house); - if (result.isEmpty()) { - db.store(rh); - db.commit(); - stored = true; - } - } finally { - db.close(); - } - return stored; + public static ObjectContainer getContainer(){ + return db; + } + + public void close(){ + db.close(); + System.out.println("DataBase closed"); + } + + public String toString() { + return "bookingNumber="+bookingNumber+" offerNumber="+offerNumber; } - /** - * This method finds all existing owners - * - */ - public Vector getOwners() throws RemoteException, Exception { - DB4oManager.openDatabase("open"); - ObjectContainer db = DB4oManager.getContainer(); - - try { - Owner proto = new Owner(null, null); - ObjectSet result = db.queryByExample(proto); - Vector owners = new Vector(); - while (result.hasNext()) - owners.add((Owner) result.next()); - return owners; - } finally { - db.close(); - } - - } /** * @param usr @@ -131,8 +287,6 @@ public class DB4oManager { */ public Vector getAccount(String usr, String pwd) throws RemoteException, Exception { - DB4oManager.openDatabase("open"); - ObjectContainer db = DB4oManager.getContainer(); try { Account proto = new Account(usr, pwd, new Owner(null, null)); @@ -142,114 +296,34 @@ public class DB4oManager { accounts.add((Account) result.next()); return accounts; } finally { - db.close(); + //db.close(); } } - /** - * @return - * @throws RemoteException - * @throws Exception - */ - public Vector getAllRuralHouses() throws RemoteException, - - Exception { - DB4oManager.openDatabase("open"); - ObjectContainer db = DB4oManager.getContainer(); - try { - RuralHouse proto = new RuralHouse(0, null, null, null, null); - ObjectSet result = db.queryByExample(proto); - Vector ruralHouses = new Vector(); - while (result.hasNext()) - ruralHouses.add((RuralHouse) result.next()); - return ruralHouses; - } finally { - db.close(); - } - } - - /** - * This method creates an offer with a house number, first day, last day and - * price precondition: There are no overlapping offers - * - * @param House - * number, start day, last day and price - * @return None - */ - - public Offer createOffer(RuralHouse ruralHouse, Date firstDay, - Date lastDay, float price) throws RemoteException, Exception { - DB4oManager.openDatabase("open"); - ObjectContainer db = DB4oManager.getContainer(); - Offer o; - try { - RuralHouse proto = new RuralHouse(ruralHouse.getHouseNumber(), - null, ruralHouse.getDescription(), ruralHouse.getTown(), - ruralHouse.getFeatures()); - ObjectSet result = db.queryByExample(proto); - RuralHouse rh = (RuralHouse) result.next(); - o = rh.createOffer(firstDay, lastDay, price); - db.store(o); - db.commit(); - } finally { - db.close(); - } - return o; - } - - /** * @param rh - * @return */ - public RuralHouse getRuralHouse(RuralHouse rh) { - - DB4oManager.openDatabase("open"); - try { - ObjectContainer db = DB4oManager.getContainer(); - RuralHouse proto = new RuralHouse(rh.getHouseNumber(), null, - - rh.getDescription(), rh.getTown(), rh.getFeatures()); - ObjectSet result = db.queryByExample(proto); - return rh = (RuralHouse) result.next(); - } catch (Exception exc) { - exc.printStackTrace(); - return null; - } finally { - db.close(); - } - - } - - /** - * @param offer - * @param clientTelephoneNumber - * @return - * @throws OfferCanNotBeBooked - */ - public Booking createBooking(Offer offer, String clientTelephoneNumber) - throws OfferCanNotBeBooked { - DB4oManager.openDatabase("open"); + public boolean storeRuralHouses(RuralHouse rh) { + DB4oManager.openDB(); + boolean stored = false; + ObjectContainer db = DB4oManager.getContainer(); + RuralHouse house = new RuralHouse(rh.getHouseNumber(), null, null, + null, null); try { - Booking b = null; - if (offer != null) { - b = offer.createBook(clientTelephoneNumber); - db.store(b); - db.store(offer); + ObjectSet result = db.queryByExample(house); + if (result.isEmpty()) { + db.store(rh); db.commit(); + stored = true; } - return b; - } catch (Exception exc) { - exc.printStackTrace(); - return null; } finally { db.close(); } - + return stored; } public void removeHouse(int houseNumber) { - ObjectContainer db = DB4oManager.getContainer(); + DB4oManager.openDB(); RuralHouse house = new RuralHouse(houseNumber, null, null, null, null); try { ObjectSet result = db.queryByExample(house); @@ -265,14 +339,5 @@ public class DB4oManager { } } - - /** - * This method returns the instance of the DB4oManager class - * - * @return the db4o manager - */ - public static DB4oManager getInstance() { - return theDB4oManager; - } - } + diff --git a/ruralHouses/src/dataAccess/DB4oManagerServer.java b/ruralHouses/src/dataAccess/DB4oManagerServer.java new file mode 100644 index 0000000..06ca88a --- /dev/null +++ b/ruralHouses/src/dataAccess/DB4oManagerServer.java @@ -0,0 +1,123 @@ +package dataAccess; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.rmi.Naming; +import java.rmi.RMISecurityManager; +import java.rmi.RemoteException; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.border.EmptyBorder; + +import configuration.ConfigXML; + +import javax.swing.JTextArea; + +import com.db4o.ObjectServer; +import com.db4o.cs.Db4oClientServer; +import com.db4o.cs.config.ServerConfiguration; + +import domain.Offer; +import domain.Owner; + +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; + +public class DB4oManagerServer extends JDialog { + + private final JPanel contentPanel = new JPanel(); + JTextArea textArea; + ObjectServer server; + private ServerConfiguration configurationCS; + + /** + * Launch the application. + */ + public static void main(String[] args) { + try { + DB4oManagerServer dialog = new DB4oManagerServer(); + dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + dialog.setVisible(true); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Create the dialog. + */ + public DB4oManagerServer() { + setTitle("DB4oManagerServer: running the database server"); + setBounds(100, 100, 486, 180); + getContentPane().setLayout(new BorderLayout()); + contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); + getContentPane().add(contentPanel, BorderLayout.CENTER); + contentPanel.setLayout(new BorderLayout(0, 0)); + { + textArea = new JTextArea(); + contentPanel.add(textArea); + } + { + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); + getContentPane().add(buttonPane, BorderLayout.SOUTH); + { + JButton okButton = new JButton("OK"); + okButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + textArea.append("\n\n\nClosing the database... "); + try { + server.close(); + } catch (Exception e1) { + } + System.exit(1); + } + }); + okButton.setActionCommand("OK"); + buttonPane.add(okButton); + getRootPane().setDefaultButton(okButton); + } + { + JButton cancelButton = new JButton("Cancel"); + cancelButton.setActionCommand("Cancel"); + buttonPane.add(cancelButton); + } + } + + ConfigXML c=ConfigXML.getInstance(); + + + try{ + + if (c.getDataBaseOpenMode().equals("initialize")) new File(c.getDb4oFilename()).delete(); + + configurationCS = Db4oClientServer.newServerConfiguration(); + configurationCS.common().activationDepth(c.getActivationDepth()); + configurationCS.common().updateDepth(c.getUpdateDepth()); + configurationCS.common().objectClass(Owner.class).cascadeOnDelete(true); + + server = Db4oClientServer.openServer(configurationCS, + c.getDb4oFilename(),c.getDatabasePort()); + + textArea.append("\nConnection to the database '"+c.getDb4oFilename()+"' opened in port "+c.getDatabasePort()); + + server.grantAccess(c.getUser(),c.getPassword()); + + textArea.append("\nAccess granted to: "+c.getUser()); + + + + textArea.append("\nPress button to exit this database server... "); + + } catch (Exception e) { + textArea.append("Something has happened in DB4oManagerServer: "+e.toString()); + + } + } +} + diff --git a/ruralHouses/src/domain/Booking.java b/ruralHouses/src/domain/Booking.java index 64a3152..20d110e 100644 --- a/ruralHouses/src/domain/Booking.java +++ b/ruralHouses/src/domain/Booking.java @@ -13,12 +13,13 @@ public class Booking implements Serializable { private String telephone; private Offer offer; + public Booking() { } - public Booking(String telephone, Offer offer) { + public Booking(int bN ,String telephone, Offer offer) { - this.bookingNumber = BookingManager.getNumber(); + this.bookingNumber = bN; this.telephone=telephone; this.offer = offer; //this.price = price; diff --git a/ruralHouses/src/domain/Offer.java b/ruralHouses/src/domain/Offer.java index 36b7037..c0dfade 100644 --- a/ruralHouses/src/domain/Offer.java +++ b/ruralHouses/src/domain/Offer.java @@ -1,77 +1,146 @@ package domain; import java.io.*; -//import java.util.Vector; -import java.util.Date; -import businessLogic.OfferManager; -import com.db4o.ObjectContainer; -import dataAccess.DB4oManager; +import java.util.Date; + @SuppressWarnings("serial") public class Offer implements Serializable { + private int offerNumber; - private Date firstDay; - private Date lastDay; - private float price; - private Booking booking; + private Date firstDay; // Dates are stored as java.util.Date objects instead of java.sql.Date objects + private Date lastDay; // because, they are not well stored in db4o as java.util.Date objects + private float price; // This is coherent because objects of java.sql.Date are objects of java.util.Date + private Booking booking; // That is: java.sql.Date is a subclass (or extends) java.util.Date private RuralHouse ruralHouse; + - public Offer(RuralHouse ruralHouse, Date firstDay, Date lastDay, float price) { + public Offer(int offerNumber,RuralHouse ruralHouse, Date firstDay, Date lastDay, float price){ this.firstDay=firstDay; this.lastDay=lastDay; this.price=price; this.ruralHouse=ruralHouse; - this.offerNumber=OfferManager.getNumber(); + this.offerNumber=offerNumber; } - + /** + * Get the house number of the offer + * + * @return the house number + */ public RuralHouse getRuralHouse() { return this.ruralHouse; } + /** + * Set the house number to a offer + * + * @param house number + */ public void setRuralHouse(RuralHouse ruralHouse) { this.ruralHouse = ruralHouse; } + + /** + * Get the offer number + * + * @return offer number + */ public int getOfferNumber() { return this.offerNumber; } + + + /** + * Get the first day of the offer + * + * @return the first day + */ public Date getFirstDay() { return this.firstDay; } + /** + * Set the first day of the offer + * + * @param firstDay + * The first day + */ public void setFirstDay(Date firstDay) { this.firstDay = firstDay; } + /** + * Get the last day of the offer + * + * @return the last day + */ public Date getLastDay() { return this.lastDay; } + /** + * Set the last day of the offer + * + * @param lastDay + * The last day + */ public void setLastDay(Date lastDay) { this.lastDay = lastDay; } + /** + * Get the price + * + * @return price + */ public float getPrice() { return this.price; } + /** + * Set the price + * + * @param price + */ public void setPrice(float price) { this.price = price; } + /** + * Get the book number + * + * @return book object + */ public Booking getBooking() { return this.booking; } + /** + * Set the book object + * + * @param book + * Book object + * @return None + */ public void setBooking(Booking booking) { this.booking = booking; } - public Booking createBook(String bookTelephoneNumber) { - Booking b=new Booking(bookTelephoneNumber, this); - booking=b; - return booking; + /** + * This method creates a book with a corresponding parameters + * + * @param First day, last day, house number and telephone + * @return a book + */ + public Booking createBooking(int numBooking,String bookTelephoneNumber) { + return booking=new Booking(numBooking,bookTelephoneNumber,this); + + } + + public String toString(){ + return offerNumber+";"+firstDay.toString()+";"+lastDay.toString()+";"+price+";"+ruralHouse; } } \ No newline at end of file diff --git a/ruralHouses/src/domain/RuralHouse.java b/ruralHouses/src/domain/RuralHouse.java index 7087a66..2ab7ac9 100644 --- a/ruralHouses/src/domain/RuralHouse.java +++ b/ruralHouses/src/domain/RuralHouse.java @@ -73,12 +73,13 @@ public class RuralHouse implements Serializable { return this.houseNumber + ": " + this.town; } - public Offer createOffer(Date firstDay, Date lastDay, float price) { - Offer off=new Offer(this, firstDay, lastDay, price); + public Offer createOffer(int offerNumber,Date firstDay, Date lastDay, float price) { + Offer off=new Offer(offerNumber,this,firstDay,lastDay,price); offers.add(off); return off; } + @Override public int hashCode() { final int prime = 31; @@ -152,6 +153,17 @@ public class RuralHouse implements Serializable { return null; } - +public Offer overlapsWith( Date firstDay, Date lastDay) { + + Iterator e=offers.iterator(); + Offer offer=null; + while (e.hasNext()){ + offer=e.next(); + if ( (offer.getFirstDay().compareTo(lastDay)<0) && (offer.getLastDay().compareTo(firstDay)>0)) + return offer; + } + return null; + + } } diff --git a/ruralHouses/src/exceptions/.DS_Store b/ruralHouses/src/exceptions/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/ruralHouses/src/exceptions/.DS_Store differ diff --git a/ruralHouses/src/exceptions/BadDates.java b/ruralHouses/src/exceptions/BadDates.java new file mode 100644 index 0000000..9cf6915 --- /dev/null +++ b/ruralHouses/src/exceptions/BadDates.java @@ -0,0 +1,17 @@ +package exceptions; +public class BadDates extends Exception { + private static final long serialVersionUID = 1L; + + public BadDates() + { + super(); + } + /**This exception is triggered if first date is greater than last date in offers + *@param String + *@return None + */ + public BadDates(String s) + { + super(s); + } +} \ No newline at end of file diff --git a/ruralHouses/src/exceptions/DB4oManagerCreationException.java b/ruralHouses/src/exceptions/DB4oManagerCreationException.java new file mode 100644 index 0000000..4b49471 --- /dev/null +++ b/ruralHouses/src/exceptions/DB4oManagerCreationException.java @@ -0,0 +1,17 @@ +package exceptions; +public class DB4oManagerCreationException extends Exception { + private static final long serialVersionUID = 1L; + + public DB4oManagerCreationException() + { + super(); + } + /**This exception is triggered if there is a problem when constructor of DB4oManager is executed + *@param String + *@return None + */ + public DB4oManagerCreationException(String s) + { + super(s); + } +} \ No newline at end of file diff --git a/ruralHouses/src/exceptions/OverlappingOfferExists.java b/ruralHouses/src/exceptions/OverlappingOfferExists.java new file mode 100644 index 0000000..c776a3b --- /dev/null +++ b/ruralHouses/src/exceptions/OverlappingOfferExists.java @@ -0,0 +1,17 @@ +package exceptions; +public class OverlappingOfferExists extends Exception { + private static final long serialVersionUID = 1L; + + public OverlappingOfferExists() + { + super(); + } + /**This exception is triggered if there exists an overlapping offer + *@param String + *@return None + */ + public OverlappingOfferExists(String s) + { + super(s); + } +} \ No newline at end of file diff --git a/ruralHouses/src/gui/.DS_Store b/ruralHouses/src/gui/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/ruralHouses/src/gui/.DS_Store differ diff --git a/ruralHouses/src/gui/BookRuralHouseConfirmationWindow.java b/ruralHouses/src/gui/BookRuralHouseConfirmationWindow.java index a80006f..70dd714 100644 --- a/ruralHouses/src/gui/BookRuralHouseConfirmationWindow.java +++ b/ruralHouses/src/gui/BookRuralHouseConfirmationWindow.java @@ -1,87 +1,103 @@ package gui; -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; +import javax.swing.JFrame; +import java.awt.Dimension; +import javax.swing.JLabel; +import java.awt.Rectangle; +import javax.swing.JTextField; +import javax.swing.JButton; + import domain.Booking; -public class BookRuralHouseConfirmationWindow extends JFrame { +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; - private static final long serialVersionUID = 1L; - private JLabel jLabel1 = new JLabel(); - private JTextField jTextField1 = new JTextField(); - private JLabel jLabel2 = new JLabel(); - private JTextField jTextField2 = new JTextField(); - private JLabel jLabel3 = new JLabel(); - private JButton jButton1 = new JButton(); - private JLabel jLabel4 = new JLabel(); - private JLabel jLabel5 = new JLabel(); - private JTextField jTextField3 = new JTextField(); - private JTextField jTextField4 = new JTextField(); +public class BookRuralHouseConfirmationWindow extends JFrame { + private static final long serialVersionUID = 1L; + + private JLabel jLabel1 = new JLabel(); + private JTextField jTextField1 = new JTextField(); + private JLabel jLabel2 = new JLabel(); + private JTextField jTextField2 = new JTextField(); + private JLabel jLabel3 = new JLabel(); + private JButton jButton1 = new JButton(); + private JLabel jLabel4 = new JLabel(); + private JLabel jLabel5 = new JLabel(); + private JTextField jTextField3 = new JTextField(); + private JTextField jTextField4 = new JTextField(); - public BookRuralHouseConfirmationWindow(Booking booking) { - try { - jbInit(booking); - } - catch(Exception e) { - e.printStackTrace(); - } - } + public BookRuralHouseConfirmationWindow(Booking book) + { + try + { + jbInit(book); + } + catch(Exception e) + { + e.printStackTrace(); + } - private void jbInit(Booking booking) throws Exception { + } - this.getContentPane().setLayout(null); - this.setSize(new Dimension(416, 316)); - this.setTitle("Confirm Booking"); - this.setResizable(false); - jLabel1.setText("Owner Bank account number:"); - jLabel1.setBounds(new Rectangle(20, 20, 200, 25)); - jTextField1.setBounds(new Rectangle(225, 20, 165, 25)); - jTextField1.setEditable(false); - jTextField1.setText(booking.getOffer().getRuralHouse().getOwner().getBankAccount()); + private void jbInit(Booking book) throws Exception + { + - jLabel2.setText("Booking number:"); - jLabel2.setBounds(new Rectangle(20, 60, 130, 25)); - jTextField2.setBounds(new Rectangle(225, 60, 165, 25)); - jTextField2.setEditable(false); + this.getContentPane().setLayout(null); + this.setSize(new Dimension(416, 316)); + this.setTitle("See Booking Details"); + this.setResizable(false); + jLabel1.setText("Owner Bank account number:"); + jLabel1.setBounds(new Rectangle(20, 20, 200, 25)); + jTextField1.setBounds(new Rectangle(225, 20, 165, 25)); + jTextField1.setEditable(false); - jTextField2.setText(Integer.toString(booking.getBookNumber())); + jTextField1.setText(book.getOffer().getRuralHouse().getOwner().getBankAccount()); + + jLabel2.setText("Booking number:"); + jLabel2.setBounds(new Rectangle(20, 60, 130, 25)); + jTextField2.setBounds(new Rectangle(225, 60, 165, 25)); + jTextField2.setEditable(false); - jLabel3.setText("You ought to transfer 20% of the total price of the booking in the next three days."); - jLabel3.setBounds(new Rectangle(20, 105, 370, 25)); - jButton1.setText("Accept"); - jButton1.setBounds(new Rectangle(135, 235, 130, 30)); - jButton1.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - jButton1_actionPerformed(e); - } - }); - jLabel4.setText("Total:"); - jLabel4.setBounds(new Rectangle(70, 140, 85, 25)); - jLabel5.setText("Deposit amount:"); - jLabel5.setBounds(new Rectangle(70, 175, 100, 25)); - jTextField3.setBounds(new Rectangle(180, 140, 115, 25)); - jTextField3.setEditable(false); + jTextField2.setText(Integer.toString(book.getBookNumber())); + + jLabel3.setText("You must deposit 20% of the total ammount of a book in the next three days."); + jLabel3.setBounds(new Rectangle(20, 105, 370, 25)); + jButton1.setText("Close"); + jButton1.setBounds(new Rectangle(135, 235, 130, 30)); + jButton1.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + jButton1_actionPerformed(e); + } + }); + jLabel4.setText("Total:"); + jLabel4.setBounds(new Rectangle(70, 140, 85, 25)); + jLabel5.setText("Deposit ammount:"); + jLabel5.setBounds(new Rectangle(70, 175, 100, 25)); + jTextField3.setBounds(new Rectangle(180, 140, 115, 25)); + jTextField3.setEditable(false); - jTextField3.setText(Float.toString(booking.getPrice()) + " €"); - jTextField4.setBounds(new Rectangle(180, 175, 115, 25)); - jTextField4.setEditable(false); - jTextField4.setText(Float.toString(booking.getPrice()*(float)0.2) + " €"); - this.getContentPane().add(jTextField4, null); - this.getContentPane().add(jTextField3, null); - this.getContentPane().add(jLabel5, null); - this.getContentPane().add(jLabel4, null); - this.getContentPane().add(jButton1, null); - this.getContentPane().add(jLabel3, null); - this.getContentPane().add(jTextField2, null); - this.getContentPane().add(jLabel2, null); - this.getContentPane().add(jTextField1, null); - this.getContentPane().add(jLabel1, null); - } + jTextField3.setText(Float.toString(book.getPrice()) + " €"); + jTextField4.setBounds(new Rectangle(180, 175, 115, 25)); + jTextField4.setEditable(false); + jTextField4.setText(Float.toString(book.getPrice()*(float)0.2) + " €"); + this.getContentPane().add(jTextField4, null); + this.getContentPane().add(jTextField3, null); + this.getContentPane().add(jLabel5, null); + this.getContentPane().add(jLabel4, null); + this.getContentPane().add(jButton1, null); + this.getContentPane().add(jLabel3, null); + this.getContentPane().add(jTextField2, null); + this.getContentPane().add(jLabel2, null); + this.getContentPane().add(jTextField1, null); + this.getContentPane().add(jLabel1, null); + } - private void jButton1_actionPerformed(ActionEvent e) { - this.setVisible(false); - } - + private void jButton1_actionPerformed(ActionEvent e) + { + this.setVisible(false); + } } \ No newline at end of file diff --git a/ruralHouses/src/gui/BookRuralHouseGUI.java b/ruralHouses/src/gui/BookRuralHouseGUI.java index eadd8b0..705b351 100644 --- a/ruralHouses/src/gui/BookRuralHouseGUI.java +++ b/ruralHouses/src/gui/BookRuralHouseGUI.java @@ -6,216 +6,261 @@ import com.toedter.calendar.*; import domain.Booking; import domain.RuralHouse; - import exceptions.OfferCanNotBeBooked; import java.beans.*; - import java.sql.Date; import java.text.*; import java.util.*; import javax.swing.*; + import java.awt.*; import java.awt.event.*; + + public class BookRuralHouseGUI extends JFrame { - private static final long serialVersionUID = 1L; - - private JLabel jLabel1 = new JLabel(); - private JComboBox jComboBox1; - private JLabel jLabel2 = new JLabel(); - private JLabel jLabel3 = new JLabel(); - private JLabel jLabel4 = new JLabel(); - private JTextField jTextField2 = new JTextField(); - private JTextField jTextField3 = new JTextField(); - private JTextField jTextField4 = new JTextField(); - private JButton jButton2 = new JButton(); - private JButton jButton3 = new JButton(); - - // Code for JCalendar - private JCalendar jCalendar1 = new JCalendar(); - private Calendar myCalendar = null; - private JLabel jLabel5 = new JLabel(); - - public BookRuralHouseGUI() { - try { - jbInit(); - } - catch(Exception e) { - e.printStackTrace(); - } - } - - public BookRuralHouseGUI(int houseNumber, Date firstDay, Date lastDay) { - try { - jbInit(); - - /*jTextField1.setText(Integer.toString(houseNumber)); - long nights=(lastDay.getTime()-firstDay.getTime())/(1000*60*60*24); - jTextField3.setText(Long.toString(nights)); - DateFormat dateformat1 = DateFormat.getDateInstance(1); - - Date first= new Date((long)(firstDay.getTime())); - jTextField2.setText(dateformat1.format(first)); - GregorianCalendar cal=new GregorianCalendar(); - cal.setTime(first); - int year=cal.get(Calendar.YEAR); - int month=cal.get(Calendar.MONTH); - int day=cal.get(Calendar.DAY_OF_MONTH); - - JYearChooser yc=jCalendar1.getYearChooser(); - JMonthChooser mc= jCalendar1.getMonthChooser(); - JDayChooser dc= jCalendar1.getDayChooser(); - - yc.setYear(year); - mc.setMonth(month); - dc.setDay(day); */ - - } - catch(Exception e) { - e.printStackTrace(); - } - } - - private void jbInit() throws Exception { - this.getContentPane().setLayout(null); - this.setSize(new Dimension(430, 440)); - this.setTitle("Book Rural House"); - jLabel1.setText("Rural house:"); - ApplicationFacadeInterface facade=StartWindow.getBusinessLogic(); - Vector ruralHouses=facade.getAllRuralHouses(); - - jComboBox1 = new JComboBox(ruralHouses); - - jLabel1.setBounds(new Rectangle(15, 10, 115, 20)); - jComboBox1.setBounds(new Rectangle(120, 10, 175, 20)); - - jTextField3.addFocusListener(new FocusListener() { - public void focusGained(FocusEvent e) {} - public void focusLost(FocusEvent e) { - jTextField3_focusLost(); - } - }); - jTextField4.addFocusListener(new FocusListener() { - public void focusGained(FocusEvent e) { } - public void focusLost(FocusEvent e) { - jTextField4_focusLost(); - } - }); - jLabel2.setText("Arrival day:"); - jLabel2.setBounds(new Rectangle(15, 40, 115, 20)); - jLabel3.setText("Number of nights:"); - jLabel3.setBounds(new Rectangle(15, 240, 115, 20)); - jLabel4.setText("Telephone contact number:"); - jLabel4.setBounds(new Rectangle(15, 270, 140, 20)); - jTextField2.setBounds(new Rectangle(155, 205, 140, 20)); - jTextField2.setEditable(false); - jTextField3.setBounds(new Rectangle(155, 240, 140, 20)); - jTextField3.setText("0"); - jTextField4.setBounds(new Rectangle(155, 270, 140, 20)); - jTextField4.setText("0"); - jButton2.setText("Accept"); - jButton2.setBounds(new Rectangle(50, 345, 130, 30)); - jButton2.setSize(new Dimension(130, 30)); - jButton2.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - // House code - RuralHouse house=(RuralHouse)jComboBox1.getSelectedItem(); - // Arrival date - Date firstDay= new Date(jCalendar1.getCalendar().getTime().getTime()); - firstDay=Date.valueOf(firstDay.toString()); - // Last day - // Number of days expressed in milliseconds - long nights=1000*60*60*24* Integer.parseInt(jTextField3.getText()); - Date lastDay= new Date((long)(firstDay.getTime()+nights)); - // Contact telephone - String telephone=jTextField4.getText(); - try { - //Obtain the business logic from a StartWindow class (local or remote) - ApplicationFacadeInterface facade=StartWindow.getBusinessLogic(); - - Booking book=facade.createBooking(house, firstDay, lastDay, telephone); - if (book!=null) { - System.out.println(book.getPrice()); - BookRuralHouseConfirmationWindow confirmWindow=new BookRuralHouseConfirmationWindow(book); - confirmWindow.setVisible(true); - } - } - catch (OfferCanNotBeBooked e1) { - jLabel5.setText("Error: Booking is not possible"); - JFrame a = new SearchOffersGUI(); - a.setVisible(true); - } - catch (Exception e1) { - e1.printStackTrace(); - } - } - }); - jButton3.setText("Cancel"); - jButton3.setBounds(new Rectangle(220, 345, 130, 30)); - jButton3.setSize(new Dimension(130, 30)); - jButton3.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - jButton3_actionPerformed(e); - } - }); - jLabel5.setBounds(new Rectangle(50, 310, 300, 20)); - jLabel5.setForeground(Color.red); - jCalendar1.setBounds(new Rectangle(155, 50, 235, 145)); - this.getContentPane().add(jCalendar1, null); - this.getContentPane().add(jLabel5, null); - this.getContentPane().add(jButton3, null); - this.getContentPane().add(jButton2, null); - this.getContentPane().add(jTextField4, null); - this.getContentPane().add(jTextField3, null); - this.getContentPane().add(jTextField2, null); - this.getContentPane().add(jLabel4, null); - this.getContentPane().add(jLabel3, null); - this.getContentPane().add(jLabel2, null); - this.getContentPane().add(jComboBox1, null); - this.getContentPane().add(jLabel1, null); - - // Code for JCalendar - this.jCalendar1.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent propertychangeevent) { - if (propertychangeevent.getPropertyName().equals("locale")) { - jCalendar1.setLocale((Locale) propertychangeevent.getNewValue()); - DateFormat dateformat = DateFormat.getDateInstance(1, jCalendar1.getLocale()); - jTextField2.setText(dateformat.format(myCalendar.getTime())); - } - else if (propertychangeevent.getPropertyName().equals("calendar")) { - myCalendar = (Calendar) propertychangeevent.getNewValue(); - DateFormat dateformat1 = DateFormat.getDateInstance(1, jCalendar1.getLocale()); - jTextField2.setText(dateformat1.format(myCalendar.getTime())); - jCalendar1.setCalendar(myCalendar); +private static final long serialVersionUID = 1L; +public static final long MILLSECS_PER_DAY= 24 * 60 * 60 * 1000; + + private JLabel jLabel1 = new JLabel(); + private JComboBox jComboBox1; + Vector ruralHouses; + private JLabel jLabel2 = new JLabel(); + private JLabel jLabel3 = new JLabel(); + private JLabel jLabel4 = new JLabel(); + private JTextField jTextField2 = new JTextField(); + private JTextField jTextField3 = new JTextField(); + private JTextField jTextField4 = new JTextField(); + private JButton jButton2 = new JButton(); + private JButton jButton3 = new JButton(); + + // Code for JCalendar + private JCalendar jCalendar1 = new JCalendar(); + private Calendar calendarMio = null; + private JLabel jLabel5 = new JLabel(); + + + +public BookRuralHouseGUI() + { + try + { + jbInit(); + + + } + catch(Exception e) + { + e.printStackTrace(); + } + } + public BookRuralHouseGUI(int houseNumber,Date firstDay,Date lastDay) + { + try + { + jbInit(); + + + // Put the "houseNumber", "firstDay" and "lastDay" in the graphical components of the user interface + for (int i=0; i rhs=facade.getAllRuralHouses(); + + comboBox = new JComboBox(rhs); + //comboBox.setModel(new DefaultComboBoxModel(rhs)); + + + this.getContentPane().setLayout(null); + this.setSize(new Dimension(433, 548)); + this.setTitle("Query availability"); + jLabel1.setText("Rural house code:"); + jLabel1.setBounds(new Rectangle(40, 20, 105, 25)); + jLabel2.setText("First day:"); + jLabel2.setBounds(new Rectangle(40, 55, 75, 25)); + jTextField2.setBounds(new Rectangle(190, 210, 155, 25)); + jTextField2.setEditable(false); + jLabel3.setText("Number of nights:"); + jLabel3.setBounds(new Rectangle(40, 250, 115, 25)); + jTextField3.setBounds(new Rectangle(190, 250, 155, 25)); + jTextField3.setText("0"); + jButton1.setText("Accept"); + jButton1.setBounds(new Rectangle(55, 455, 130, 30)); + jButton1.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + jButton1_actionPerformed(e); + } + }); + jButton2.setText("Close"); + jButton2.setBounds(new Rectangle(230, 455, 130, 30)); + + + jTextField3.addFocusListener(new FocusListener() + { + public void focusGained(FocusEvent e) + { + } + + public void focusLost(FocusEvent e) + { + jTextField3_focusLost(); + } + }); + jButton2.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + jButton2_actionPerformed(e); + } + }); + jLabel4.setBounds(new Rectangle(55, 300, 305, 30)); + jLabel4.setForeground(Color.red); + jCalendar1.setBounds(new Rectangle(190, 60, 225, 150)); + scrollPane.setBounds(new Rectangle(45, 305, 320, 116)); + + this.getContentPane().add(scrollPane, null); + + table = new JTable(); + table.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + int i=table.getSelectedRow(); + int houseNumber = (int) tableModel.getValueAt(i,1); + Date firstDate=new Date(((java.util.Date)tableModel.getValueAt(i,2)).getTime()); + Date lastDate=new Date(((java.util.Date)tableModel.getValueAt(i,3)).getTime()); + + BookRuralHouseGUI b=new BookRuralHouseGUI(houseNumber,firstDate,lastDate); + b.setVisible(true);} + }); + + scrollPane.setViewportView(table); + tableModel = new DefaultTableModel( + null, + columnNames); + + table.setModel(tableModel); + this.getContentPane().add(jCalendar1, null); + this.getContentPane().add(jLabel4, null); + this.getContentPane().add(jButton2, null); + this.getContentPane().add(jButton1, null); + this.getContentPane().add(jTextField3, null); + this.getContentPane().add(jLabel3, null); + this.getContentPane().add(jTextField2, null); + this.getContentPane().add(jLabel2, null); + this.getContentPane().add(jLabel1, null); + comboBox.setBounds(new Rectangle(245, 22, 115, 20)); + comboBox.setBounds(189, 22, 115, 20); + + getContentPane().add(comboBox); + labelNoOffers.setBounds(73, 432, 265, 14); + + getContentPane().add(labelNoOffers); + + // Codigo para el JCalendar + this.jCalendar1.addPropertyChangeListener(new PropertyChangeListener() + { + public void propertyChange(PropertyChangeEvent propertychangeevent) + { + if (propertychangeevent.getPropertyName().equals("locale")) + { + jCalendar1.setLocale((Locale) propertychangeevent.getNewValue()); + DateFormat dateformat = DateFormat.getDateInstance(1, jCalendar1.getLocale()); + jTextField2.setText(dateformat.format(calendarMio.getTime())); + } + else if (propertychangeevent.getPropertyName().equals("calendar")) + { + calendarMio = (Calendar) propertychangeevent.getNewValue(); + DateFormat dateformat1 = DateFormat.getDateInstance(1, jCalendar1.getLocale()); + jTextField2.setText(dateformat1.format(calendarMio.getTime())); + jCalendar1.setCalendar(calendarMio); + } + } + }); + + + } + + private void jButton2_actionPerformed(ActionEvent e) + { + this.setVisible(false); + } + + + private void jTextField3_focusLost() + { + try + { + new Integer (jTextField3.getText()); + jLabel4.setText(""); + } + catch (NumberFormatException ex) + { + jLabel4.setText("Error: Introduce a number"); + } + } + + private void jButton1_actionPerformed(ActionEvent e) + { + // House object + RuralHouse rh=(RuralHouse)comboBox.getSelectedItem(); + // First day + Date firstDay=new Date(jCalendar1.getCalendar().getTime().getTime()); + //Remove the hour:minute:second:ms from the date + firstDay=Date.valueOf(firstDay.toString()); + final long diams=1000*60*60*24; + long nights= diams * Integer.parseInt(jTextField3.getText()); + // Last day + Date lastDay= new Date((long)(firstDay.getTime()+nights)); + + try { + + ApplicationFacadeInterface facade=StartWindow.getBusinessLogic(); + + Vector v=rh.getOffers(firstDay, lastDay); + + Enumeration en=v.elements(); + Offer of; + tableModel.setDataVector(null, columnNames); + if (!en.hasMoreElements()) + labelNoOffers.setText("There are no offers at these dates"); + else { + labelNoOffers.setText("Select an offer if you want to book"); + + while (en.hasMoreElements()) { + of=en.nextElement(); + System.out.println("Offer retrieved: "+of.toString()); + Vector row = new Vector(); + row.add(of.getOfferNumber()); + row.add(of.getRuralHouse().getHouseNumber()); + + // Dates are stored in db4o as java.util.Date objects instead of java.sql.Date objects + // They have to be converted into java.sql.Date objects before + Date firstDaySqlDate = new Date(of.getFirstDay().getTime()); + Date lastDaySqlDate = new Date(of.getLastDay().getTime()); + row.add(firstDaySqlDate); + row.add(lastDaySqlDate); + row.add(of.getPrice()); + + + tableModel.addRow(row); + } + } + + + } catch (Exception e1) { + + labelNoOffers.setText(e1.getMessage()); + }} +} \ No newline at end of file diff --git a/ruralHouses/src/gui/SearchOffersGUI.java b/ruralHouses/src/gui/SearchOffersGUI.java deleted file mode 100644 index 02472f3..0000000 --- a/ruralHouses/src/gui/SearchOffersGUI.java +++ /dev/null @@ -1,178 +0,0 @@ -package gui; - -import businessLogic.ApplicationFacadeInterface; - -import com.toedter.calendar.JCalendar; - -import domain.Offer; -import domain.RuralHouse; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; - -import java.beans.*; - -import java.sql.Date; -import java.text.DateFormat; -import java.util.*; - -public class SearchOffersGUI extends JFrame { - - private static final long serialVersionUID = 1L; - - private JLabel jLabel1 = new JLabel(); - private JComboBox jComboBox1; - private JLabel jLabel2 = new JLabel(); - private JTextField jTextField2 = new JTextField(); - private JLabel jLabel3 = new JLabel(); - private JTextField jTextField3 = new JTextField(); - private JButton jButton1 = new JButton(); - private JButton jButton2 = new JButton(); - // Code for JCalendar - private JCalendar jCalendar1 = new JCalendar(); - private Calendar myCalendar = null; - private JLabel jLabel4 = new JLabel(); - private JTextArea jTextArea1 = new JTextArea(); - private JScrollPane scrollPane = new JScrollPane(); - - public SearchOffersGUI() { - try { - jbInit(); - } - catch (Exception e) { - e.printStackTrace(); - } - } - - private void jbInit() throws Exception { - ApplicationFacadeInterface facade=StartWindow.getBusinessLogic(); - - Vector rhs=facade.getAllRuralHouses(); - jComboBox1 = new JComboBox(rhs); - - this.getContentPane().setLayout(null); - this.setSize(new Dimension(440, 548)); - this.setTitle("Search available rural houses"); - jLabel1.setText("Rural house:"); - jComboBox1.setBounds(new Rectangle(10, 10, 115, 25)); - jLabel1.setBounds(new Rectangle(40, 20, 105, 25)); - jComboBox1.setBounds(new Rectangle(115, 30, 115, 20)); - jLabel2.setText("First day:"); - jLabel2.setBounds(new Rectangle(40, 55, 75, 25)); - jTextField2.setBounds(new Rectangle(190, 210, 155, 25)); - jTextField2.setEditable(false); - jLabel3.setText("Number of nights:"); - jLabel3.setBounds(new Rectangle(40, 250, 115, 25)); - jTextField3.setBounds(new Rectangle(190, 250, 155, 25)); - jTextField3.setText("0"); - jButton1.setText("Accept"); - jButton1.setBounds(new Rectangle(55, 455, 130, 30)); - jButton1.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - jButton1_actionPerformed(e); - } - }); - jButton2.setText("Close"); - jButton2.setBounds(new Rectangle(230, 455, 130, 30)); - - jTextField3.addFocusListener(new FocusListener() { - public void focusGained(FocusEvent e) { } - public void focusLost(FocusEvent e) { - jTextField3_focusLost(); - } - }); - jButton2.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - jButton2_actionPerformed(e); - } - }); - jLabel4.setBounds(new Rectangle(55, 300, 305, 30)); - jLabel4.setForeground(Color.red); - jTextArea1.setEditable(false); - jCalendar1.setBounds(new Rectangle(190, 60, 225, 150)); - scrollPane.setBounds(new Rectangle(45, 305, 320, 135)); - jTextArea1.setText(""); - scrollPane.getViewport().add(jTextArea1, null); - - this.getContentPane().add(scrollPane, null); - this.getContentPane().add(jCalendar1, null); - this.getContentPane().add(jLabel4, null); - this.getContentPane().add(jButton2, null); - this.getContentPane().add(jButton1, null); - this.getContentPane().add(jTextField3, null); - this.getContentPane().add(jLabel3, null); - this.getContentPane().add(jTextField2, null); - this.getContentPane().add(jLabel2, null); - this.getContentPane().add(jComboBox1, null); - this.getContentPane().add(jLabel1, null); - - // Code for JCalendar - this.jCalendar1.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent propertychangeevent) { - if (propertychangeevent.getPropertyName().equals("locale")) { - jCalendar1.setLocale((Locale) propertychangeevent.getNewValue()); - DateFormat dateformat = DateFormat.getDateInstance(1, jCalendar1.getLocale()); - jTextField2.setText(dateformat.format(myCalendar.getTime())); - } - else if (propertychangeevent.getPropertyName().equals("calendar")) { - myCalendar = (Calendar) propertychangeevent.getNewValue(); - DateFormat dateformat1 = DateFormat.getDateInstance(1, jCalendar1.getLocale()); - jTextField2.setText(dateformat1.format(myCalendar.getTime())); - jCalendar1.setCalendar(myCalendar); - } - } - }); - - } - - private void jButton2_actionPerformed(ActionEvent e) { - this.setVisible(false); - } - - private void jTextField3_focusLost() { - try { - new Integer (jTextField3.getText()); - jLabel4.setText(""); - } - catch (NumberFormatException ex) { - jLabel4.setText("Error: Please introduce a number"); - } - } - - private void jButton1_actionPerformed(ActionEvent e) { - // House object - RuralHouse rh=(RuralHouse)jComboBox1.getSelectedItem(); - // First day - Date firstDay=new Date(jCalendar1.getCalendar().getTime().getTime()); - //Remove the hour:minute:second:ms from the date - firstDay=Date.valueOf(firstDay.toString()); - final long diams=1000*60*60*24; - long nights= diams * Integer.parseInt(jTextField3.getText()); - // Last day - Date lastDay= new Date((long)(firstDay.getTime()+nights)); - jTextArea1.setText(""); - try { - ApplicationFacadeInterface facade=StartWindow.getBusinessLogic(); - Vector v=facade.getOffers(rh, firstDay, lastDay); - - Enumeration en=v.elements(); - Offer of; - while (en.hasMoreElements()) { - of=en.nextElement(); - firstDay= new Date(of.getFirstDay().getTime()); - firstDay=Date.valueOf(firstDay.toString()); - lastDay= new Date(of.getLastDay().getTime()); - lastDay=Date.valueOf(lastDay.toString()); - jTextArea1.append("Offer "+Integer.toString(of.getOfferNumber())+":from:"+firstDay+" to:"+lastDay+"\n"); - } - - //} catch (RemoteException e1) { - // e1.printStackTrace(); - - } - catch (Exception e1) { - e1.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/ruralHouses/src/gui/SetAvailability2GUI.java b/ruralHouses/src/gui/SetAvailability2GUI.java new file mode 100644 index 0000000..86a1d29 --- /dev/null +++ b/ruralHouses/src/gui/SetAvailability2GUI.java @@ -0,0 +1,236 @@ +package gui; +import java.beans.*; +import java.sql.Date; +import java.text.DateFormat; +import java.util.*; + +import javax.swing.*; + +import java.awt.*; +import java.awt.event.*; + +import businessLogic.ApplicationFacadeInterface; + +import com.toedter.calendar.JCalendar; + +import domain.Offer; +import domain.RuralHouse; +import exceptions.OverlappingOfferExists; +import exceptions.BadDates; + + + +public class SetAvailability2GUI extends JFrame { +private static final long serialVersionUID = 1L; + + private JComboBox jComboBox1; + private JLabel jLabel1 = new JLabel(); + private JLabel jLabel2 = new JLabel(); + private JTextField jTextField1 = new JTextField(); + private JLabel jLabel3 = new JLabel(); + private JTextField jTextField2 = new JTextField(); + private JLabel jLabel4 = new JLabel(); + private JTextField jTextField3 = new JTextField(); + private JButton jButton1 = new JButton(); + + // Code for JCalendar + private JCalendar jCalendar1 = new JCalendar(); + private JCalendar jCalendar2 = new JCalendar(); + private Calendar calendarInicio = null; + private Calendar calendarFin = null; + private JButton jButton2 = new JButton(); + private JLabel jLabel5 = new JLabel(); + private final JLabel lblNewLabel = new JLabel(""); + + public SetAvailability2GUI(Vector v) + { + try + { + jbInit(v); + } + catch(Exception e) + { + e.printStackTrace(); + } + } + + private void jbInit(Vector v) throws Exception + { + this.getContentPane().setLayout(null); + this.setSize(new Dimension(513, 433)); + this.setTitle("Set availability"); + + + jComboBox1 = new JComboBox(v); + jComboBox1.setBounds(new Rectangle(115, 30, 115, 20)); + jLabel1.setText("List of houses:"); + jLabel1.setBounds(new Rectangle(25, 30, 95, 20)); + jLabel2.setText("First day :"); + jLabel2.setBounds(new Rectangle(25, 75, 85, 25)); + jTextField1.setBounds(new Rectangle(25, 265, 220, 25)); + jTextField1.setEditable(false); + jLabel3.setText("Last day :"); + jLabel3.setBounds(new Rectangle(260, 75, 75, 25)); + jTextField2.setBounds(new Rectangle(260, 265, 220, 25)); + jTextField2.setEditable(false); + jLabel4.setText("Price:"); + jLabel4.setBounds(new Rectangle(260, 30, 75, 20)); + jTextField3.setBounds(new Rectangle(350, 30, 115, 20)); + jTextField3.setText("0"); + jButton1.setText("Accept"); + jButton1.setBounds(new Rectangle(100, 360, 130, 30)); + jTextField3.addFocusListener(new FocusListener() + { + public void focusGained(FocusEvent e) + { + } + + public void focusLost(FocusEvent e) + { + jTextField3_focusLost(); + } + }); + jButton1.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + jButton1_actionPerformed(e); + } + }); + jButton2.setText("Cancel"); + jButton2.setBounds(new Rectangle(270, 360, 130, 30)); + jButton2.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + jButton2_actionPerformed(e); + } + }); + jLabel5.setBounds(new Rectangle(100, 320, 300, 20)); + jLabel5.setForeground(Color.red); + jLabel5.setSize(new Dimension(305, 20)); + jCalendar1.setBounds(new Rectangle(25, 100, 220, 165)); + jCalendar2.setBounds(new Rectangle(260, 100, 220, 165)); + + // Code for JCalendar + this.jCalendar1.addPropertyChangeListener(new PropertyChangeListener() + { + public void propertyChange(PropertyChangeEvent propertychangeevent) + { + if (propertychangeevent.getPropertyName().equals("locale")) + { + jCalendar1.setLocale((Locale) propertychangeevent.getNewValue()); + DateFormat dateformat = DateFormat.getDateInstance(1, jCalendar1.getLocale()); + jTextField1.setText(dateformat.format(calendarInicio.getTime())); + } + else if (propertychangeevent.getPropertyName().equals("calendar")) + { + calendarInicio = (Calendar) propertychangeevent.getNewValue(); + DateFormat dateformat1 = DateFormat.getDateInstance(1, jCalendar1.getLocale()); + jTextField1.setText(dateformat1.format(calendarInicio.getTime())); + jCalendar1.setCalendar(calendarInicio); + } + } + }); + + this.jCalendar2.addPropertyChangeListener(new PropertyChangeListener() + { + public void propertyChange(PropertyChangeEvent propertychangeevent) + { + if (propertychangeevent.getPropertyName().equals("locale")) + { + jCalendar2.setLocale((Locale) propertychangeevent.getNewValue()); + DateFormat dateformat = DateFormat.getDateInstance(1, jCalendar2.getLocale()); + jTextField2.setText(dateformat.format(calendarFin.getTime())); + } + else if (propertychangeevent.getPropertyName().equals("calendar")) + { + calendarFin = (Calendar) propertychangeevent.getNewValue(); + DateFormat dateformat1 = DateFormat.getDateInstance(1, jCalendar2.getLocale()); + jTextField2.setText(dateformat1.format(calendarFin.getTime())); + jCalendar2.setCalendar(calendarFin); + } + } + }); + + + this.getContentPane().add(jCalendar2, null); + this.getContentPane().add(jCalendar1, null); + this.getContentPane().add(jLabel5, null); + this.getContentPane().add(jButton2, null); + this.getContentPane().add(jButton1, null); + this.getContentPane().add(jTextField3, null); + this.getContentPane().add(jLabel4, null); + this.getContentPane().add(jTextField2, null); + this.getContentPane().add(jLabel3, null); + this.getContentPane().add(jTextField1, null); + this.getContentPane().add(jLabel2, null); + this.getContentPane().add(jLabel1, null); + this.getContentPane().add(jComboBox1, null); + lblNewLabel.setBounds(115, 301, 298, 38); + + getContentPane().add(lblNewLabel); + } + + private void jButton1_actionPerformed(ActionEvent e) + { + RuralHouse ruralHouse=((RuralHouse)jComboBox1.getSelectedItem()); + + // The next instruction creates a java.sql.Date object from the date selected in the JCalendar object + Date firstDay=new Date(jCalendar1.getCalendar().getTime().getTime()); + // The next instruction removes the hour, minute, second and ms from the date + // This has to be made because the date will be stored in db4o as a java.util.Date object + // that would store those data, and that would give problems when comparing dates later + firstDay=Date.valueOf(firstDay.toString()); + + + Date lastDay=new Date(jCalendar2.getCalendar().getTime().getTime()); + //Remove the hour:minute:second:ms from the date + lastDay=Date.valueOf(lastDay.toString()); + + + try { + + //It could be to trigger an exception if the introduced string is not a number + float price= Float.parseFloat(jTextField3.getText()); + + //Obtain the business logic from a StartWindow class (local or remote) + ApplicationFacadeInterface facade=StartWindow.getBusinessLogic(); + + Offer o = facade.createOffer(ruralHouse, firstDay, lastDay, price); + System.out.println("Offer created: "+o.toString()); + + if (o==null) + jLabel5.setText("Bad dates or there exists an overlapping offer"); + else jLabel5.setText("Offer created"); + + } catch (java.lang.NumberFormatException e1) { + jLabel5.setText(jTextField3.getText()+ " is not a valid price"); + } catch (OverlappingOfferExists e1) { + jLabel5.setText("There exists an overlapping offer"); + } + catch (BadDates e1) { + jLabel5.setText("Last day is before first day in the offer"); + } catch (Exception e1) { + + e1.printStackTrace(); + } + } + private void jButton2_actionPerformed(ActionEvent e) + { + this.setVisible(false); + } + + private void jTextField3_focusLost() + { + try + { + new Integer (jTextField3.getText()); + jLabel5.setText(""); + } + catch (NumberFormatException ex) + { + jLabel5.setText("Error: Introduce a number"); + } + } +} \ No newline at end of file diff --git a/ruralHouses/src/gui/SetAvailabilityGUI.java b/ruralHouses/src/gui/SetAvailabilityGUI.java new file mode 100644 index 0000000..92e44d9 --- /dev/null +++ b/ruralHouses/src/gui/SetAvailabilityGUI.java @@ -0,0 +1,125 @@ +package gui; + +import javax.swing.ComboBoxModel; +import javax.swing.JPanel; +import javax.swing.JFrame; +import javax.swing.JComboBox; + +import java.awt.Rectangle; +import java.util.Set; +import java.util.Vector; + +import javax.swing.JButton; + +import businessLogic.ApplicationFacadeInterface; +import domain.Owner; +import domain.RuralHouse; +import javax.swing.JLabel; + + +public class SetAvailabilityGUI extends JFrame { + + private static final long serialVersionUID = 1L; + private JPanel jContentPane = null; + private JComboBox jComboBox = null; + private JButton jButton = null; + private JLabel lblNewLabel; + + /** + * This is the default constructor + */ + public SetAvailabilityGUI() { + super(); + initialize(); + } + + /** + * This method initializes this + * + * @return void + */ + private void initialize() { + this.setSize(449, 293); + this.setContentPane(getJContentPane()); + this.setTitle("Choose Owner"); + + } + + /** + * This method initializes jContentPane + * + * @return javax.swing.JPanel + */ + private JPanel getJContentPane() { + if (jContentPane == null) { + jContentPane = new JPanel(); + jContentPane.setLayout(null); + jContentPane.add(getJComboBox(), null); + jContentPane.add(getJButton(), null); + + lblNewLabel = new JLabel(""); + lblNewLabel.setBounds(77, 194, 300, 32); + jContentPane.add(lblNewLabel); + } + return jContentPane; + } + + /** + * This method initializes jComboBox + * + * @return javax.swing.JComboBox + */ + private JComboBox getJComboBox() { + + if (jComboBox == null) { + try { + ApplicationFacadeInterface facade=StartWindow.getBusinessLogic(); + Vector owners=facade.getOwners(); + jComboBox = new JComboBox(owners); + jComboBox.setBounds(new Rectangle(136, 39, 175, 44)); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + return jComboBox; + } + + /** + * This method initializes jButton + * + * @return javax.swing.JButton + */ + private JButton getJButton() { + if (jButton == null) { + jButton = new JButton(); + jButton.setBounds(new Rectangle(172, 115, 95, 59)); + jButton.setText("Aceptar"); + jButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent e) { + Owner owner=(Owner)jComboBox.getSelectedItem(); + Vector houseList=null; + try { + +// ApplicationFacadeInterface facade=StartWindow.getBusinessLogic(); +// houseList=facade.getRuralHouses(owner); // Not needed to ask the business logic because + houseList=owner.getRuralHouses(); // Owner has been serialized with its rural houses !! + + } catch (Exception e1) { + e1.printStackTrace(); + } + if (houseList.isEmpty()!=true) { + JFrame a = new SetAvailability2GUI(houseList); + a.setVisible(true); + } else if (houseList.isEmpty()==true){ + lblNewLabel.setText("Owner does not exist or without houses "); + } + + } + }); + } + return jButton; + } +} // @jve:decl-index=0:visual-constraint="222,33" diff --git a/ruralHouses/src/gui/StartWindow.java b/ruralHouses/src/gui/StartWindow.java index f33bc0f..3e538ca 100644 --- a/ruralHouses/src/gui/StartWindow.java +++ b/ruralHouses/src/gui/StartWindow.java @@ -1,167 +1,229 @@ package gui; -import javax.swing.*; +/** + * @author willCodeForFood + */ +import exceptions.DB4oManagerCreationException; +import gui.BookRuralHouseGUI; -import java.awt.*; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; +import javax.swing.*; -import businessLogic.FacadeImplementation; +import configuration.ConfigXML; +//import businessLogic.FacadeImplementation; import businessLogic.ApplicationFacadeInterface; +import businessLogic.FacadeImplementation; import java.rmi.*; +import java.awt.Color; +import java.awt.Font; +import java.awt.Rectangle; +import java.awt.Dimension; +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.GridLayout; +import java.awt.GridBagLayout; +import java.awt.GridBagConstraints; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; -import configuration.Config; public class StartWindow extends JFrame { - public static boolean clientServer = false; - private static final long serialVersionUID = 1L; private JPanel jContentPane = null; - private JButton bookHouseButton = null; - private JButton createOfferButton = null; - private JButton searchAvailabilityButton = null; - private JButton exitButton = null; + private JButton boton1 = null; + private JButton boton2 = null; + private JButton boton3 = null; + private static configuration.ConfigXML c; public static ApplicationFacadeInterface facadeInterface; + private JLabel lblNewLabel; + public static void main(String[] args) { + + StartWindow a = new StartWindow(); + a.setVisible(true); + + try { + + c=ConfigXML.getInstance(); + + System.setProperty("java.security.policy", c.getJavaPolicyPath()); + + System.setSecurityManager(new RMISecurityManager()); + + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + + c=configuration.ConfigXML.getInstance(); + if (c.isBusinessLogicLocal()) + facadeInterface=new FacadeImplementation(); + else { + + final String businessLogicNode = c.getBusinessLogicNode(); + // Remote service name + String serviceName = "/"+c.getServiceRMI(); + // RMI server port number + int portNumber = Integer.parseInt(c.getPortRMI()); + // RMI server host IP IP + facadeInterface = (ApplicationFacadeInterface) Naming.lookup("rmi://" + + businessLogicNode + ":" + portNumber + serviceName); + } + + } catch (java.rmi.ConnectException e) { + a.lblNewLabel.setText("No business logic: Run BusinessLogicServer first!!"); + a.lblNewLabel.setForeground(Color.RED); + System.out.println("Error in StartWindow: "+e.toString()); + } catch (java.rmi.NotBoundException e) { + a.lblNewLabel.setText("No business logic: Maybe problems running BusinessLogicServer"); + a.lblNewLabel.setForeground(Color.RED); + System.out.println("Error in StartWindow: "+e.toString()); + } catch (com.db4o.ext.DatabaseFileLockedException e) { + a.lblNewLabel.setText("Database locked: Do not run BusinessLogicServer or BusinessLogicServer!!"); + a.lblNewLabel.setForeground(Color.RED); + System.out.println("Error in StartWindow: "+e.toString()); + } catch (Exception e) { + a.lblNewLabel.setText("Error: "+e.toString()); + a.lblNewLabel.setForeground(Color.RED); + System.out.println("Error in StartWindow: "+e.toString()); + } + //a.pack(); + + + + } + /** + * This is the default constructor + */ + public StartWindow() { super(); + + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + ApplicationFacadeInterface facade=StartWindow.facadeInterface; + try { + if (c.isBusinessLogicLocal()) facade.close(); + } catch (Exception e1) { + // TODO Auto-generated catch block + System.out.println("Error: "+e1.toString()+" , probably problems with Business Logic or Database"); + } + System.exit(1); + } + }); initialize(); - this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } - public static ApplicationFacadeInterface getBusinessLogic(){ return facadeInterface; } + + /** + * This method initializes this + * + * @return void + */ private void initialize() { // this.setSize(271, 295); - this.setSize(350, 400); + this.setSize(495, 290); this.setContentPane(getJContentPane()); this.setTitle("Rural Houses"); } + /** + * This method initializes jContentPane + * + * @return javax.swing.JPanel + */ private JPanel getJContentPane() { if (jContentPane == null) { + GridLayout gridLayout = new GridLayout(); + gridLayout.setRows(4); + gridLayout.setColumns(1); jContentPane = new JPanel(); -// jContentPane.setLayout(null); - jContentPane.setLayout(new BoxLayout(jContentPane, - BoxLayout.Y_AXIS)); - jContentPane.add(Box.createRigidArea(new Dimension(0,40))); - jContentPane.add(getBookHouseButton()); - jContentPane.add(Box.createRigidArea(new Dimension(0,40))); - jContentPane.add(getSearchAvailabilityButton()); - jContentPane.add(Box.createRigidArea(new Dimension(0,40))); - jContentPane.add(getCreateOfferButton()); - jContentPane.add(Box.createRigidArea(new Dimension(0,40))); - jContentPane.add(getExitButton()); - jContentPane.add(Box.createRigidArea(new Dimension(0,40))); + jContentPane.setLayout(gridLayout); + jContentPane.add(getLblNewLabel()); + jContentPane.add(getBoton2(), null); + jContentPane.add(getBoton3(), null); + jContentPane.add(getBoton1(), null); } return jContentPane; } - private JButton getBookHouseButton() { - if (bookHouseButton == null) { - bookHouseButton = new JButton(); - bookHouseButton.setFont(new Font("Tahoma", Font.PLAIN, 24)); - bookHouseButton.setText("Book rural house"); - bookHouseButton.setAlignmentX(Component.CENTER_ALIGNMENT); - bookHouseButton.addActionListener(new java.awt.event.ActionListener() { + /** + * This method initializes boton1 + * + * @return javax.swing.JButton + */ + private JButton getBoton1() { + if (boton1 == null) { + boton1 = new JButton(); + boton1.setText("Book rural house"); + boton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { + // C?digo cedido por la univerdad JFrame a = new BookRuralHouseGUI(); a.setVisible(true); } }); } - return bookHouseButton; + return boton1; } - private JButton getCreateOfferButton() { - if (createOfferButton == null) { - createOfferButton = new JButton(); - createOfferButton.setFont(new Font("Tahoma", Font.PLAIN, 24)); - createOfferButton.setText("Introduce new offer"); - createOfferButton.setAlignmentX(Component.CENTER_ALIGNMENT); - createOfferButton.addActionListener(new java.awt.event.ActionListener() { + /** + * This method initializes boton2 + * + * @return javax.swing.JButton + */ + private JButton getBoton2() { + if (boton2 == null) { + boton2 = new JButton(); + boton2.setText("Login"); + boton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { + // C?digo cedido por la universidad JFrame a = new LoginGUI(); a.setVisible(true); } }); } - return createOfferButton; + return boton2; } - private JButton getSearchAvailabilityButton() { - if (searchAvailabilityButton == null) { - searchAvailabilityButton = new JButton(); - searchAvailabilityButton.setFont(new Font("Tahoma", Font.PLAIN, 24)); - searchAvailabilityButton.setText("Search availability"); - searchAvailabilityButton.setAlignmentX(Component.CENTER_ALIGNMENT); - searchAvailabilityButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - JFrame a = new SearchOffersGUI(); - a.setVisible(true); - } - }); - } - return searchAvailabilityButton; - } - - private JButton getExitButton() { - if (exitButton == null) { - exitButton = new JButton(); - exitButton.setText("Exit"); - exitButton.setFont(new Font("Tahoma", Font.PLAIN, 24)); - exitButton.setAlignmentX(Component.CENTER_ALIGNMENT); - exitButton.addActionListener(new java.awt.event.ActionListener() { + /** + * This method initializes boton3 + * + * @return javax.swing.JButton + */ + private JButton getBoton3() { + if (boton3 == null) { + boton3 = new JButton(); + boton3.setText("Query availability"); + boton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { + // C?digo cedido por la universidad //JFrame a = new QueryAvailabilityWindow(); - ApplicationFacadeInterface facade=StartWindow.facadeInterface; - try { - - setVisible(false); - System.exit(1); - } - catch (Exception e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } + JFrame a = new QueryAvailabilityGUI(); + + a.setVisible(true); } }); } - return exitButton; + return boton3; } - public static void main(String[] args) { - try { - UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - - Config c=Config.getInstance(); - if (!clientServer) - facadeInterface=new FacadeImplementation(); - else { - final String serverRMI = c.getServerRMI(); - // Remote service name - String serviceName = "/"+c.getServiceRMI(); - //System.setSecurityManager(new RMISecurityManager()); - // RMI server port number - int portNumber = Integer.parseInt(c.getPortRMI()); - // RMI server host IP IP - facadeInterface = (ApplicationFacadeInterface) Naming.lookup("rmi://" - + serverRMI + ":" + portNumber + serviceName); - } + private JLabel getLblNewLabel() { + if (lblNewLabel == null) { + lblNewLabel = new JLabel("Select option:"); + lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 13)); + lblNewLabel.setForeground(Color.BLACK); + lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER); } - catch (Exception e) { - //System.out.println(e.toString()); - e.printStackTrace(); - } - JFrame a = new StartWindow(); - a.setVisible(true); + return lblNewLabel; } -} //@jve:decl-index=0:visual-constraint="0,0" +} // @jve:decl-index=0:visual-constraint="0,0" +