1 /*************************************************************************
2  *
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * Copyright 2000, 2010 Oracle and/or its affiliates.
6  *
7  * OpenOffice.org - a multi-platform office productivity suite
8  *
9  * This file is part of OpenOffice.org.
10  *
11  * OpenOffice.org is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU Lesser General Public License version 3
13  * only, as published by the Free Software Foundation.
14  *
15  * OpenOffice.org is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Lesser General Public License version 3 for more details
19  * (a copy is included in the LICENSE file that accompanied this code).
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * version 3 along with OpenOffice.org.  If not, see
23  * <http://www.openoffice.org/license.html>
24  * for a copy of the LGPLv3 License.
25  *
26  ************************************************************************/
27 
28 import java.io.*;
29 import java.util.*;
30 
31 public class pdbcomparison
32 {
33 
34   private String LOGTAG  ="LOGFILE";
35   private String OUTTAG  ="OUTFILE";
36   private String LISTTAG ="LISTFILE";
37   private String PDBTAG1 ="PDBNAME1";
38   private String PDBTAG2 ="PDBNAME2";
39 
40   private String OUTFILE="pdbcomparison.out";
41   private String LOGFILE="pdbcomparison.log";
42 
43   private String pdbarr1[];
44   private String pdbarr2[];
45 
46 
47    /**
48    * Default Constructor
49    *
50    *  @param
51    *  @return
52    *
53    */
54    public void pdbcomparison()
55    {
56    }
57 
58    /**
59    * Prints the command line arguments for this class
60    *
61    * @param
62    *
63    * @return void
64    *
65    */
66    public void usage()
67    {
68       String str = new String();
69       str += "********************************************************\n";
70       str += " java pdbcomparison.java <propFile> \n";
71       str += "   where propFile is name of Property File...\n";
72       str += "********************************************************\n";
73 
74       System.out.println(str);
75 
76    }
77 
78    /**
79    * This method, read the Property file and validates the
80    * entries in that file, and accordingly sets the log file
81    * output file and updates the array pdbarr1 and pdbarr2 with
82    * list of pdb's to be compared.
83    *
84    * @param propFile Property filename which list the log/outputfile/list/pdb
85    *                 names
86    * @return
87    *
88    */
89    public void parsePropertyFile(String propFile)
90    {
91      Properties defaultProps = new Properties();
92 
93      try {
94        FileInputStream in = new FileInputStream(propFile);
95        defaultProps.load(in);
96        in.close();
97      } catch (IOException e) {
98        System.out.println("Could not open Property File " + propFile);
99        return;
100      }
101 
102 
103      String logFile  = defaultProps.getProperty(this.LOGTAG);
104      String outFile  = defaultProps.getProperty(this.OUTTAG);
105      String listFile = defaultProps.getProperty(this.LISTTAG);
106      String pdbname1 = defaultProps.getProperty(this.PDBTAG1);
107      String pdbname2 = defaultProps.getProperty(this.PDBTAG2);
108 
109     // validate all command line arguments
110     if ((listFile == null) && ((pdbname1 == null) || (pdbname2 == null)))
111     {
112        System.out.println("Missing listFile or missing pdb filenames in Property file " + propFile);
113        return;
114     }
115 
116     if (logFile == null || logFile.length() == 0)
117        logFile = this.LOGFILE;
118 
119     if (outFile == null || outFile.length() == 0)
120        outFile = this.LOGFILE;
121 
122 
123      // validate log and output files
124      if (! validateAndCreateFile(logFile)) return;
125      if (! validateAndCreateFile(outFile)) return;
126      LOGFILE = logFile;
127      OUTFILE = outFile;
128 
129      System.out.println("Output is written to log file... " + LOGFILE);
130      if (listFile != null)
131      {
132        if (! checkFile(listFile)) return;
133        populatePDBArray(listFile);
134      } else {
135        if (! checkFile(pdbname1)) return;
136        if (! checkFile(pdbname2)) return;
137        populatePDBArray(pdbname1, pdbname2);
138      }
139    }
140 
141    /**
142    * This method validates if the file passed exists.
143    * If it does , then it is moved to <filename>.bak and then creates a newFile.
144    * Also validates permissions to create.
145    *
146    *  @param  filename  name of file to be created
147    *  @return true, if file could be created
148    *          false, if could not.
149    *
150    */
151    private boolean validateAndCreateFile (String filename)
152    {
153      if (filename == null) return false;
154 
155      File f = null;
156      try {
157        f = new File(filename);
158      } catch (NullPointerException e) {
159        System.out.println("Could not create a File object for file " + filename);
160        return false;
161      }
162 
163      if (f.exists())
164      {
165        String newFile = filename + ".bak";
166        File newF=null;
167        try {
168          newF = new File(newFile);
169        } catch (Exception ex) {
170          System.out.println("Could not get File Object instance for " + newFile);
171          return false;
172        }
173 
174        if (newF.exists())
175        {
176          try {
177            newF.delete();
178          } catch ( SecurityException se) {
179            System.out.println("Could not get delete " + newFile);
180            return false;
181          }
182        }
183 
184        try {
185          if (! f.renameTo(newF))
186          {
187              System.out.println("Could not rename " + filename + "  to " + newFile );
188              return false;
189          }
190        } catch  (SecurityException s) {
191              System.out.println("SecurityException: " + s.toString());
192              return false;
193        } catch  (NullPointerException n) {
194              System.out.println("NullPointerException: " + n.toString());
195              return false;
196        }
197      } else {
198        try {
199         if (! f.createNewFile())
200         {
201            System.out.println("Could not create " + filename + " Check permissions..");
202            return false;
203         }
204        } catch (IOException e) {
205            System.out.println("IOException: " + e.toString());
206            return false;
207        } catch  (SecurityException s) {
208            System.out.println("SecuriityException: " + s.toString() );
209            return false;
210        }
211 
212      }
213 
214      return true;
215 
216    }
217 
218    /**
219    * This method validates if the file exists and is readable
220    *
221    *  @param  filename  name of file to be created
222    *  @return true, if file exists and is readable
223    *          false, if not.
224    *
225    */
226    private boolean  checkFile(String filename)
227    {
228      if (filename == null) return false;
229 
230      File f = null;
231      try {
232        f = new File(filename);
233      } catch (NullPointerException e) {
234        System.out.println("Could not create a File object for file " + filename);
235        return false;
236      }
237 
238      if (! f.exists())
239      {
240        System.out.println("File " + filename + " does not exist... ");
241        return false;
242      }
243 
244      if (! f.canRead())
245      {
246        System.out.println("Cannot read file " + filename);
247        return false;
248      }
249 
250      return true;
251 
252    }
253 
254    /**
255    * This method populates the pdb arrays with the names of the pdbs to
256    * compare. Ths listFile lists a series of entries, wherein each
257    * line indicates the PDB names to be compared.
258    * <pdbname1>=<pdbname2>
259    *
260    *  @param  listFile  name of the listfile
261    *  @return
262    *
263    */
264    private void  populatePDBArray(String listFile)
265    {
266 	// open ListFile and populate the PDB list to be compared
267 	if (listFile != null)
268 	{
269 	    Properties listProps = new Properties();
270 	    try {
271 		FileInputStream in = new FileInputStream(listFile);
272 		listProps.load(in);
273 		in.close();
274 	    } catch (IOException ex) {
275 		 System.out.println("Could not open List File " + listFile);
276 		 return;
277 	    }
278 
279 	    pdbarr1 = new String[listProps.size()];
280 	    pdbarr2 = new String[listProps.size()];
281 	    Enumeration e = listProps.keys();
282 	    int j=0;
283 	    while (e.hasMoreElements())
284 	    {
285 		    pdbarr1[j] = (String)e.nextElement();
286 		    pdbarr2[j] = listProps.getProperty(pdbarr1[j]);
287                     j++;
288 	    }
289 
290         }
291    }
292 
293    /**
294    * This method populates the pdb arrays with the names of the pdbs to
295    * compare.
296    *
297    *  @param  pdbname1 Name of 2nd PDB file to be compared
298    *  @param  pdbname2 Name of 2nd PDB file to be compared
299    *  @return
300    *
301    */
302    private void  populatePDBArray(String pdbname1, String pdbname2)
303    {
304       if (pdbname1 == null) return;
305       if (pdbname2 == null) return;
306 
307       if ((pdbname1 != null) && (pdbname2 != null))
308       {
309 	 pdbarr1 = new String[1];
310 	 pdbarr2 = new String[1];
311 
312 	 pdbarr1[0] = pdbname1;
313 	 pdbarr2[0] = pdbname2;
314       }
315    }
316 
317    /**
318    * This method populates the pdb arrays with the names of the pdbs to
319    * compare.
320    *
321    *  @param  arrayno  Array number which corresponds to the pdb array
322    *                   containing  list of pdbs
323    *                   If 1 then send pdbarr1, if 2 send pdbarr2 else null
324    *
325    *  @return PDB string array containing list of PDB's
326    *
327    */
328    private String[]  getPDBArray(int arrayno)
329    {
330     if (arrayno == 1) return pdbarr1;
331     if (arrayno == 2) return pdbarr2;
332 
333     return null;
334    }
335 
336    /**
337    * This method comares 2 PDB's and returns true if comparison is equal.
338    * It uses the PDB Decoder class to decode to a PDB structure and then
339    * does record comparison
340    *
341    * @param  pdbname1 Name of one  PDB file  to be compared
342    * @param  pdbname2 Name of other  PDB file  to be compared
343    *
344    * @return returns true if both PDB's are equal else returns false
345    *
346    */
347    private boolean  comparePDB(String pdbname1, String pdbname2)
348    {
349        PalmDB pdb1=null, pdb2=null;
350        PDBDecoder decoder = new PDBDecoder();
351        try {
352          pdb1 = decoder.parse(pdbname1);
353        } catch (Exception e) {
354          System.out.println("Could not parse PDB " + pdbname1);
355          return false;
356        }
357 
358        try {
359          pdb2 = decoder.parse(pdbname2);
360        } catch (Exception e) {
361          System.out.println("Could not parse PDB " + pdbname2);
362          return false;
363        }
364 
365        if (pdb1.equals(pdb2)) {
366         writeToLog("PDB " + pdbname1 + "  and PDB " + pdbname2 + " are equal");
367 
368         return true;
369        } else {
370         writeToLog("PDB " + pdbname1 + "  and PDB " + pdbname2 + " are not equal");
371         return false;
372        }
373    }
374 
375 
376 
377    /**
378    *  Write message to LOGFILE
379    *
380    *  @param msg Message to be written to log file
381    *  @return
382    *
383    */
384    private void writeToLog(String msg)
385    {
386      if (msg == null) return;
387 
388      // Get Output Stream from Log file
389      RandomAccessFile raf=null;
390      try {
391       raf = new RandomAccessFile(LOGFILE, "rw");
392      } catch (Exception e) {
393       System.out.println ("Could not open file " + LOGFILE);
394       return;
395      }
396 
397      try {
398            long len = raf.length();
399            raf.seek(len);
400            raf.write(msg.getBytes());
401            raf.write("\n".getBytes());
402       } catch (IOException e) {
403          System.out.println("ERROR: Could not write to File " + LOGFILE);
404          return;
405       }
406    }
407 
408    /**
409    *  Write status of comparison  to OUTFILE
410    *
411    *  @param status Indicates whether comparsion of PDB's PASSED or FAILED
412    *  @param pdbname1 file name of pdb which was compared.
413    *  @param pdbname2 file name of pdb which was compared.
414    *
415    *  @return
416    *
417    */
418    private void writeToOutputFile(String status, String pdbname1, String pdbname2)
419    {
420      if (status == null) return;
421      if (pdbname1 == null) return;
422      if (pdbname2 == null) return;
423 
424      String msg = pdbname1 + "=" + pdbname2 + ":" + status;
425 
426      // Get Output Stream from Log file
427      RandomAccessFile raf=null;
428      try {
429       raf = new RandomAccessFile(OUTFILE, "rw");
430      } catch (Exception e) {
431       System.out.println ("Could not open file " + OUTFILE);
432       return;
433      }
434 
435      try {
436            long len = raf.length();
437            raf.seek(len);
438 
439            raf.write(msg.getBytes());
440            raf.write("\n".getBytes());
441       } catch (IOException e) {
442          System.out.println("ERROR: Could not write to File " + OUTFILE);
443          return;
444       }
445 
446      try {
447        raf.close();
448      } catch (Exception e) {
449        System.out.println("ERROR: Could not close File " + OUTFILE);
450        return;
451      }
452 
453    }
454 
455 
456 
457    /**
458    *  Main starting block of execution
459    *
460    *  @param command line args captured in an array of Strings
461    *  @return
462    *
463    */
464    public static void main(String args[])
465    {
466 
467      Date startTime = new Date();
468      pdbcomparison pdbcmp = new pdbcomparison();
469      int nargs = args.length;
470      int status=0;
471 
472      if (nargs != 1)
473      {
474          System.out.println("Incorrect no. of arguments passed...");
475          pdbcmp.usage();
476          System.exit(-1);
477 
478      }
479 
480      String propFile = args[0];
481 
482      File f=null;
483      try {
484        f = new File(propFile);
485      } catch (Exception e) {
486        System.out.println("Exception: Could not open file " + propFile);
487        System.exit(-1);
488      }
489 
490      if (! f.canRead()) {
491        System.out.println("Exception: " + propFile + " is not a file ");
492        System.exit(-1);
493      }
494 
495      if (! f.canRead()) {
496        System.out.println("Exception: Cannot open file for reading. Please check permissions ");
497        System.exit(-1);
498      }
499 
500      // parse Property file
501      pdbcmp.parsePropertyFile(propFile);
502 
503      String pdbarr1[] = pdbcmp.getPDBArray(1);
504      String pdbarr2[] = pdbcmp.getPDBArray(2);
505      if ( (pdbarr1 == null) ||
506           (pdbarr2 == null) ||
507           (pdbarr1.length == 0) ||
508           (pdbarr1.length == 0))
509      {
510        System.out.println("pdbArray is empty. No PDBS to compare... \n");
511        System.exit(-1);
512      }
513 
514 
515      pdbcmp.writeToLog("************** Start *****************");
516      pdbcmp.writeToLog("PDB Comparison: start time " + startTime);
517      for (int i=0; i<pdbarr1.length; i++)
518      {
519        Date pdb_startTime = new Date();
520        pdbcmp.writeToLog("\n");
521        pdbcmp.writeToLog("start time " + pdb_startTime);
522        boolean val = pdbcmp.comparePDB(pdbarr1[i], pdbarr2[i]);
523        Date pdb_endTime = new Date();
524        pdbcmp.writeToLog("end time " + pdb_endTime);
525 
526        if (val) {
527         pdbcmp.writeToOutputFile("PASSED", pdbarr1[i], pdbarr2[i]);
528         status=0;
529        } else {
530         pdbcmp.writeToOutputFile("FAILED", pdbarr1[i], pdbarr2[i]);
531         status=-1;
532        }
533      }
534 
535      Date endTime = new Date();
536      pdbcmp.writeToLog("PDB Comparison: end time " + endTime);
537      pdbcmp.writeToLog("************** End *****************n");
538      pdbcmp.writeToLog("\n");
539 
540      System.exit(status);
541    }
542 }
543