View Javadoc

1   package com.wickle.Jdiary;
2   
3   import java.io.FileNotFoundException;
4   import java.io.FileOutputStream;
5   import java.io.IOException;
6   import java.io.PrintStream;
7   import java.util.Iterator;
8   import java.util.List;
9   
10  import org.jdom.*;
11  import org.jdom.input.SAXBuilder;
12  import org.jdom.output.XMLOutputter;
13  
14  import com.wickle.Jdiary.EntryDiary;
15  
16    class DiaryObject {
17  		private String name;
18  		private String propietary;
19  		private EntryDiary entry;
20  		private Document diarioDoc;
21  		private SAXBuilder builder;
22  		private String fileDiary;
23  		
24  	public DiaryObject(){
25  		 builder = new SAXBuilder();
26  		 if (fileDiary==null){
27  		 	fileDiary=System.getProperty("user.home")+System.getProperty("file.separator")+"diario.xml";
28  		 }
29  	}
30  	
31  	
32  	/***
33  	 * Trata de abrir el diario.xml del directorio por defecto, de lo contrario
34  	 * deberia crearlo (implementarlo)
35  	 *
36  	 */
37  	
38  	public void getDiary(){
39  		System.out.println(fileDiary);
40  				try {
41  					 diarioDoc = builder.build(fileDiary);
42  					}
43  					// indicates a well-formedness error
44  					catch (JDOMException e) { 
45  					  System.out.println("diario.xml is not well-formed.");
46  					  System.out.println(e.getMessage());
47  					}  
48  					catch (IOException e) {
49  					  System.out.println("creando diario nuevo ..."+e);
50  					  CreateDiary();
51  					  getDiary();
52  					}
53  		
54  	}
55  
56  	/***
57  	 * Devuelve la entrada del diario asociado a la fecha que se le pasa
58  	 * para ello recorre todo el objeto XML en busqueda de un entry con el atributo
59  	 * date igual al que se le pasa como parametro.
60  	 * @param fecha
61  	 * @return Objeto EntryDiary con la entrada el dairio asociada
62  	 */
63  	public EntryDiary getEntrybyDate(String fecha){
64  		EntryDiary entrada = new EntryDiary();
65  		Element root = diarioDoc.getRootElement();
66  		List entry=root.getChildren("entry");
67  		Iterator i = entry.iterator();
68  			 while (i.hasNext()) {
69  			   Element entradatmp = (Element) i.next();
70  			   //System.out.println("-"+entradatmp.getAttribute("date").getValue().toString()+"-");
71  			   if(entradatmp.getAttribute("date").getValue().toString().equals(fecha)){
72  				entrada.setTitle(entradatmp.getChild("tittle").getText().toString());
73  				entrada.setDescription(entradatmp.getChild("description").getText().toString());
74  				entrada.setDate(fecha);
75  				entrada.setPostID(entradatmp.getChild("postID").getText().toString());
76  			   }else{
77  				//System.out.println("NO");
78  			   }
79  			   			   
80  			 }
81  		
82  		return entrada;
83  	}
84  
85  	
86  	/***
87  	 * funcion que devuelve true si la fecha que le pasamos contiene datos , devuelve false
88  	 * si no contiene ningun dato.
89  	 * function NOT USED at these moment
90  	 * @param fecha
91  	 * @return
92  	 */
93  	public boolean ChequeaEntrada(String fecha){
94  		boolean valor=false;
95  		Element test=null;
96  		EntryDiary entrada = new EntryDiary();
97  		Element root = diarioDoc.getRootElement();
98  		List entry=root.getChildren("entry");
99  		Iterator i = entry.iterator();
100 			while (i.hasNext()) {
101 			   Element entradatmp = (Element) i.next();
102 			   if(entradatmp.getAttribute("date").getValue().toString().equals(fecha)){
103 				valor=true;
104 			   }else{
105 				valor=false;
106 			   }
107 			   			   
108 			 }
109 		
110 		return valor;
111 	}
112 	/***
113 	 * Si la entrada que se le pasa como parametro ya existe (se comprueba con la fecha), 
114 	 * entonces modifica la entrada antigua con los valores de la entrada que se le pasa como
115 	 * parametro. Si dicha fecha no tiene ningun registro asociado, se devuelve false
116 	 * @param entrada Objeto EntryDiary a comprobar si existe, caso afirmativo se reescribe.
117 	 * @return true if there are no problems modifying the entry parsed as argument , 
118 	 * and return false if the entry is new.
119 	 */
120 	public boolean LimpiaEntrada(EntryDiary entrada){
121 		boolean valor=false;
122 		Element test=null;
123 		//EntryDiary entrada = new EntryDiary();
124 		Element root = diarioDoc.getRootElement();
125 		List entry=root.getChildren("entry");
126 		Iterator i = entry.iterator();
127 			while (i.hasNext()) {
128 			   Element entradatmp = (Element) i.next();
129 			   if(entradatmp.getAttribute("date").getValue().toString().equals(entrada.getDate())){
130 				entradatmp.getChild("tittle").setText(entrada.getTitle());
131 				entradatmp.getChild("description").setText(entrada.getDescription());
132 				valor=true;
133 			   }else{
134 				valor=false;
135 			   }
136 			   			   
137 			 }
138 			 return valor;
139 		
140 	}
141 	
142 	/***
143 	 * Se crea una entrada XML con el formato de una entrada de diario 
144 	 * <entry date="fecha"><tittle>titulo</tittle><description>LA DESCRIPCION</description>
145 	 * Se le pasa un objeto de tipo EntryDiary que contiene los campos de una entrada del 
146 	 * diario 
147 	 * 
148 	 * @param ent
149 	 */
150 	public void PersistEntry(EntryDiary ent){
151 		Element root = diarioDoc.getRootElement();
152 		Element child1;
153 		if (LimpiaEntrada(ent)){
154 			System.out.println("EXISTE");
155 	
156 		}else{
157 			System.out.println("NO EXISTE");
158 			child1 = new Element("entry").setAttribute("date",ent.getDate().toString());
159 			root.addContent(child1);
160 			Element child2 = new Element("tittle").setText(ent.getTitle().toString());
161 			Element child3 = new Element("description").setText(ent.getDescription().toString());
162 			Element child4;
163 			if (ent.getPostID() != null){
164 				 child4 = new Element("postID").setText(ent.getPostID().toString());
165 			}else{
166 				 child4 = new Element("postID").setText("0");
167 			}
168 			//root.addContent(child1);
169 			child1.addContent(child2);
170 			child1.addContent(child3);
171 			child1.addContent(child4);
172 		}
173 		PersistDiary();
174 	}
175 	
176 	/***
177 	 * Crea la estructura basica de un diario, esto solo se llama la primera vez que
178 	 * se ejecuta el programa y sino existe un diario.xml, aqui se inicializa.
179 	 *
180 	 */
181 	public void CreateDiary(){
182 		try {
183 			  FileOutputStream out = new FileOutputStream(fileDiary);
184 			  PrintStream ps = new PrintStream(out);
185 			  ps.print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
186 			  ps.print("<diary>\r\n");
187 			  ps.print("</diary>");
188 			  out.close();
189 			}
190 			catch (IOException e) {
191 			  System.err.println(e);
192 			}
193 	}
194 	/***
195 	 * Persiste el diario al archivo diario.xml de disco duro ...
196 	 *
197 	 */
198 	public void PersistDiary(){
199 		//diarioDoc
200 		//Document doc = new Document(root);
201 		// serialize it into a file
202 		try {
203 		  FileOutputStream out = new FileOutputStream(fileDiary);
204 		  XMLOutputter serializer = new XMLOutputter();
205 		  serializer.output(diarioDoc, out);
206 		  out.flush();
207 		  out.close();
208 		}
209 		catch (IOException e) {
210 		  System.err.println(e);
211 		}
212 		
213 		//System.out.println(title+description);
214 	}
215 		
216 		/***
217 		 * @return Returns the fileDiary.
218 		 */
219 		public String getFileDiary() {
220 			return fileDiary;
221 		}
222 		/***
223 		 * @param fileDiary The fileDiary to set.
224 		 */
225 		public void setFileDiary(String fileDiary) {
226 			this.fileDiary = fileDiary;
227 		}
228 }