001package org.hl7.fhir.utilities;
002
003/*
004  Copyright (c) 2011+, HL7, Inc.
005  All rights reserved.
006  
007  Redistribution and use in source and binary forms, with or without modification, 
008  are permitted provided that the following conditions are met:
009    
010   * Redistributions of source code must retain the above copyright notice, this 
011     list of conditions and the following disclaimer.
012   * Redistributions in binary form must reproduce the above copyright notice, 
013     this list of conditions and the following disclaimer in the documentation 
014     and/or other materials provided with the distribution.
015   * Neither the name of HL7 nor the names of its contributors may be used to 
016     endorse or promote products derived from this software without specific 
017     prior written permission.
018  
019  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
020  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
021  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
022  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
023  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
024  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
025  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
026  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
027  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
028  POSSIBILITY OF SUCH DAMAGE.
029  
030 */
031
032
033
034import java.io.BufferedReader;
035import java.io.File;
036import java.io.FileNotFoundException;
037import java.io.FileReader;
038import java.io.FileWriter;
039import java.io.IOException;
040import java.io.InputStream;
041import java.io.InputStreamReader;
042import java.io.OutputStream;
043import java.io.OutputStreamWriter;
044import java.io.Reader;
045import java.io.Writer;
046
047import java.text.DateFormat;
048import java.text.ParseException;
049import java.text.SimpleDateFormat;
050import java.time.ZonedDateTime;
051import java.time.ZoneId;
052import java.time.format.DateTimeFormatter;
053import java.util.*;
054
055import org.hl7.fhir.utilities.filesystem.CSFile;
056import org.hl7.fhir.utilities.filesystem.ManagedFileAccess;
057
058
059/**
060 * IniFile class provides methods for manipulating (Read/Write) windows ini files.
061 * 
062 * @author Prasad P. Khandekar
063 * @version 1.0
064 * @since 1.0
065 */
066public final class IniFile
067{
068    /** Variable to represent the date format */
069    private String mstrDateFmt = "yyyy-MM-dd";
070
071    /** Variable to represent the timestamp format */
072    private String mstrTimeStampFmt = "yyyy-MM-dd HH:mm:ss";
073
074    /** Variable to denote the successful load operation. */
075    @SuppressWarnings("unused")
076    private boolean fileSuccessfullyLoaded = false;
077
078    /** Variable to hold the ini file name and full path */
079    private String filepath;
080
081    /** Variable to hold the sections in an ini file. */
082    private LinkedHashMap<String, INISection> iniSections;
083
084    /** Variable to hold environment variables **/
085    private Properties mpropEnv;
086
087    /**
088     * Create a IniFile object from the file named in the parameter.
089     * @param pathname The full path and name of the ini file to be used.
090     */
091    public IniFile(String pathname)
092    {
093        this.mpropEnv = getEnvVars();
094        this.iniSections = new LinkedHashMap<String, INISection>();
095        this.filepath = pathname;
096        // Load the specified INI file.
097        if (checkFile(pathname)) loadFile();
098    }
099
100    public IniFile(InputStream stream) {
101      this.mpropEnv = getEnvVars();
102      this.iniSections = new LinkedHashMap<String, INISection>();
103      this.filepath = null;
104      // Load the specified INI file.
105      loadStream(stream);
106    }
107
108    /*------------------------------------------------------------------------------
109 * Getters
110------------------------------------------------------------------------------*/
111    /**
112     * Returns the ini file name being used.
113     * @return the INI file name.
114     */
115    public String getFileName()
116    {
117        return this.filepath;
118    }
119
120    /**
121     * Returns the specified string property from the specified section.
122     * @param pstrSection the INI section name.
123     * @param pstrProp the property to be retrieved.
124     * @return the string property value.
125     */
126    public String getStringProperty(String pstrSection, String pstrProp)
127    {
128        String      strRet   = null;
129        INIProperty objProp  = null;
130        INISection  objSec   = null;
131
132        objSec = (INISection) this.iniSections.get(pstrSection);
133        if (objSec != null)
134        {
135            objProp = objSec.getProperty(pstrProp);
136            if (objProp != null)
137            {
138                strRet = objProp.getPropValue();
139                objProp = null;
140            }
141            objSec = null;
142        }
143        return strRet;
144    }
145
146    /**
147     * Returns the specified boolean property from the specified section.
148     * This method considers the following values as boolean values.
149     * <ol>
150     *      <li>YES/yes/Yes - boolean true</li>
151     *      <li>NO/no/No  - boolean false</li>
152     *      <li>1 - boolean true</li>
153     *      <li>0 - boolean false</li>
154     *      <li>TRUE/True/true - boolean true</li>
155     *      <li>FALSE/False/false - boolean false</li>
156     * </ol>
157     * @param pstrSection the INI section name.
158     * @param pstrProp the property to be retrieved.
159     * @return the boolean value
160     */
161    public Boolean getBooleanProperty(String pstrSection, String pstrProp)
162    {
163        boolean     blnRet  = false;
164        String      strVal  = null;
165        INIProperty objProp = null;
166        INISection  objSec  = null;
167
168        objSec = (INISection) this.iniSections.get(pstrSection);
169        if (objSec != null)
170        {
171            objProp = objSec.getProperty(pstrProp);
172            if (objProp != null)
173            {
174                strVal = objProp.getPropValue().toUpperCase();
175                if (strVal.equals("YES") || strVal.equals("TRUE") ||
176                    strVal.equals("1"))
177                {
178                    blnRet = true;
179                }
180                objProp = null;
181            }
182            objSec = null;
183        }
184        return new Boolean(blnRet);
185    }
186
187    /**
188     * Returns the specified integer property from the specified section.
189     * @param pstrSection the INI section name.
190     * @param pstrProp the property to be retrieved.
191     * @return the integer property value.
192     */
193    public Integer getIntegerProperty(String pstrSection, String pstrProp)
194    {
195        Integer     intRet  = null;
196        String      strVal  = null;
197        INIProperty objProp = null;
198        INISection  objSec  = null;
199
200        objSec = (INISection) this.iniSections.get(pstrSection);
201        if (objSec != null)
202        {
203            objProp = objSec.getProperty(pstrProp);
204            try
205            {
206                if (objProp != null)
207                {
208                    strVal = objProp.getPropValue();
209                    if (strVal != null) intRet = new Integer(strVal);
210                }
211            }
212            catch (NumberFormatException NFExIgnore)
213            {
214            }
215            finally
216            {
217                if (objProp != null) objProp = null;
218            }
219            objSec = null;
220        }
221        return intRet;
222    }
223
224    /**
225     * Returns the specified long property from the specified section.
226     * @param pstrSection the INI section name.
227     * @param pstrProp the property to be retrieved.
228     * @return the long property value.
229     */
230    public Long getLongProperty(String pstrSection, String pstrProp)
231    {
232        Long        lngRet  = null;
233        String      strVal  = null;
234        INIProperty objProp = null;
235        INISection  objSec  = null;
236
237        objSec = (INISection) this.iniSections.get(pstrSection);
238        if (objSec != null)
239        {
240            objProp = objSec.getProperty(pstrProp);
241            try
242            {
243                if (objProp != null)
244                {
245                    strVal = objProp.getPropValue();
246                    if (strVal != null) lngRet = new Long(strVal);
247                }
248            }
249            catch (NumberFormatException NFExIgnore)
250            {
251            }
252            finally
253            {
254                if (objProp != null) objProp = null;
255            }
256            objSec = null;
257        }
258        return lngRet;
259    }
260
261    /**
262     * Returns the specified double property from the specified section.
263     * @param pstrSection the INI section name.
264     * @param pstrProp the property to be retrieved.
265     * @return the double property value.
266     */
267    public Double getDoubleProperty(String pstrSection, String pstrProp)
268    {
269        Double      dblRet  = null;
270        String      strVal  = null;
271        INIProperty objProp = null;
272        INISection  objSec  = null;
273
274        objSec = (INISection) this.iniSections.get(pstrSection);
275        if (objSec != null)
276        {
277            objProp = objSec.getProperty(pstrProp);
278            try
279            {
280                if (objProp != null)
281                {
282                    strVal = objProp.getPropValue();
283                    if (strVal != null) dblRet = new Double(strVal);
284                }
285            }
286            catch (NumberFormatException NFExIgnore)
287            {
288            }
289            finally
290            {
291                if (objProp != null) objProp = null;
292            }
293            objSec = null;
294        }
295        return dblRet;
296    }
297
298    /**
299     * Returns the specified date property from the specified section.
300     * @param pstrSection the INI section name.
301     * @param pstrProp the property to be retrieved.
302     * @return the date property value.
303     */
304    public Date getDateProperty(String pstrSection, String pstrProp)
305    {
306        Date        dtRet   = null;
307        String      strVal  = null;
308        DateFormat  dtFmt   = null;
309        INIProperty objProp = null;
310        INISection  objSec  = null;
311
312        objSec = (INISection) this.iniSections.get(pstrSection);
313        if (objSec != null)
314        {
315            objProp = objSec.getProperty(pstrProp);
316            try
317            {
318                if (objProp != null) strVal = objProp.getPropValue();
319                if (strVal != null)
320                {
321                    dtFmt = new SimpleDateFormat(this.mstrDateFmt);
322                    dtRet = dtFmt.parse(strVal);
323                }
324            }
325            catch (ParseException PExIgnore)
326            {
327            }
328            catch (IllegalArgumentException IAEx)
329            {
330            }
331            finally
332            {
333                if (objProp != null) objProp = null;
334            }
335            objSec = null;
336        }
337        return dtRet;
338    }
339
340    /**
341     * Returns the specified date property from the specified section.
342     * @param iniSectionName the INI section name.
343     * @param propertyKey the property to be retrieved.
344     * @return the date property value.
345     */
346    public Date getTimestampProperty(String iniSectionName, String propertyKey) {
347
348      Date dateToReturn = null;
349
350      INISection iniSection = this.iniSections.get(iniSectionName);
351      if (iniSection != null) {
352        INIProperty objProp = iniSection.getProperty(propertyKey);
353        try {
354          String propertyStringValue = null;
355          if (objProp != null) propertyStringValue = objProp.getPropValue();
356          if (propertyStringValue != null) {
357            DateTimeFormatter dtFmt = DateTimeFormatter.ofPattern(this.mstrTimeStampFmt).withZone(ZoneId.systemDefault());
358
359            ZonedDateTime zonedDateTime = ZonedDateTime.parse(propertyStringValue, dtFmt);
360            dateToReturn = Date.from(zonedDateTime.toInstant());
361          }
362        } catch (IllegalArgumentException IAEx) {
363        }
364      }
365      return dateToReturn;
366    }
367
368/*------------------------------------------------------------------------------
369 * Setters
370------------------------------------------------------------------------------*/
371    /**
372     * Sets the comments associated with a section.
373     * @param pstrSection the section name
374     * @param pstrComments the comments.
375     */
376    public void addSection(String pstrSection, String pstrComments)
377    {
378        INISection objSec   = null;
379
380        objSec = (INISection) this.iniSections.get(pstrSection);
381        if (objSec == null)
382        {
383            objSec = new INISection(pstrSection);
384            this.iniSections.put(pstrSection, objSec);
385        }
386        objSec.setSecComments(delRemChars(pstrComments));
387        objSec = null;
388    }
389
390    /**
391     * Sets the specified string property.
392     * @param pstrSection the INI section name.
393     * @param pstrProp the property to be set.
394     * @pstrVal the string value to be persisted
395     */
396    public void setStringProperty(String pstrSection, String pstrProp, 
397                                                String pstrVal, String pstrComments)
398    {
399        INISection objSec   = null;
400
401        objSec = (INISection) this.iniSections.get(pstrSection);
402        if (objSec == null)
403        {
404            objSec = new INISection(pstrSection);
405            this.iniSections.put(pstrSection, objSec);
406        }
407        objSec.setProperty(pstrProp, pstrVal, pstrComments);
408    }
409
410    /**
411     * Sets the specified boolean property.
412     * @param pstrSection the INI section name.
413     * @param pstrProp the property to be set.
414     * @param pblnVal the boolean value to be persisted
415     */
416    public void setBooleanProperty(String pstrSection, String pstrProp, 
417                                                boolean pblnVal, String pstrComments)
418    {
419        INISection objSec   = null;
420
421        objSec = (INISection) this.iniSections.get(pstrSection);
422        if (objSec == null)
423        {
424            objSec = new INISection(pstrSection);
425            this.iniSections.put(pstrSection, objSec);
426        }
427        if (pblnVal)
428            objSec.setProperty(pstrProp, "TRUE", pstrComments);
429        else
430            objSec.setProperty(pstrProp, "FALSE", pstrComments);
431    }
432
433    /**
434     * Sets the specified integer property.
435     * @param pstrSection the INI section name.
436     * @param pstrProp the property to be set.
437     * @param pintVal the int property to be persisted.
438     */
439    public void setIntegerProperty(String pstrSection, String pstrProp, 
440                                                int pintVal, String pstrComments)
441    {
442        INISection objSec   = null;
443
444        objSec = (INISection) this.iniSections.get(pstrSection);
445        if (objSec == null)
446        {
447            objSec = new INISection(pstrSection);
448            this.iniSections.put(pstrSection, objSec);
449        }
450        objSec.setProperty(pstrProp, Integer.toString(pintVal), pstrComments);
451    }
452
453    /**
454     * Sets the specified long property.
455     * @param pstrSection the INI section name.
456     * @param pstrProp the property to be set.
457     * @param plngVal the long value to be persisted.
458     */
459    public void setLongProperty(String pstrSection, String pstrProp, 
460                                        long plngVal, String pstrComments)
461    {
462        INISection objSec   = null;
463
464        objSec = (INISection) this.iniSections.get(pstrSection);
465        if (objSec == null)
466        {
467            objSec = new INISection(pstrSection);
468            this.iniSections.put(pstrSection, objSec);
469        }
470        objSec.setProperty(pstrProp, Long.toString(plngVal), pstrComments);
471    }
472
473    /**
474     * Sets the specified double property.
475     * @param pstrSection the INI section name.
476     * @param pstrProp the property to be set.
477     * @param pdblVal the double value to be persisted.
478     */
479    public void setDoubleProperty(String pstrSection, String pstrProp, 
480                                                double pdblVal, String pstrComments)
481    {
482        INISection objSec   = null;
483
484        objSec = (INISection) this.iniSections.get(pstrSection);
485        if (objSec == null)
486        {
487            objSec = new INISection(pstrSection);
488            this.iniSections.put(pstrSection, objSec);
489        }
490        objSec.setProperty(pstrProp, Double.toString(pdblVal), pstrComments);
491    }
492
493    /**
494     * Sets the specified java.util.Date property.
495     * @param pstrSection the INI section name.
496     * @param pstrProp the property to be set.
497     * @param pdtVal the date value to be persisted.
498     */
499    public void setDateProperty(String pstrSection, String pstrProp, 
500                                        Date pdtVal, String pstrComments)
501    {
502        INISection objSec   = null;
503
504        objSec = (INISection) this.iniSections.get(pstrSection);
505        if (objSec == null)
506        {
507            objSec = new INISection(pstrSection);
508            this.iniSections.put(pstrSection, objSec);
509        }
510        objSec.setProperty(pstrProp, utilDateToStr(pdtVal, this.mstrDateFmt), 
511                                pstrComments);
512    }
513
514    /**
515     * Sets the specified java.sql.Timestamp property.
516     * @param iniSection the INI section name.
517     * @param propertyKey the property to be set.
518     * @param propertyValue the timestamp value to be persisted.
519     */
520    public void setTimestampProperty(String iniSection, String propertyKey,
521                                                        ZonedDateTime propertyValue, String propertyComments)
522    {
523        INISection objSec   = null;
524
525        objSec = (INISection) this.iniSections.get(iniSection);
526        if (objSec == null)
527        {
528            objSec = new INISection(iniSection);
529            this.iniSections.put(iniSection, objSec);
530        }
531        objSec.setProperty(propertyKey, timeToString(propertyValue, this.mstrTimeStampFmt),
532                                propertyComments);
533    }
534
535    /**
536     * Sets the format to be used to interpret date values.
537     * @param pstrDtFmt the format string
538     * @throws IllegalArgumentException if the if the given pattern is invalid
539     */
540    public void setDateFormat(String pstrDtFmt) throws IllegalArgumentException
541    {
542        if (!checkDateTimeFormat(pstrDtFmt))
543            throw new IllegalArgumentException("The specified date pattern is invalid!");
544        this.mstrDateFmt = pstrDtFmt;
545    }
546
547    /**
548     * Sets the format to be used to interpreat timestamp values.
549     * @param pstrTSFmt the format string
550     * @throws IllegalArgumentException if the if the given pattern is invalid
551     */
552    public void setTimeStampFormat(String pstrTSFmt)
553    {
554        if (!checkDateTimeFormat(pstrTSFmt))
555            throw new IllegalArgumentException("The specified timestamp pattern is invalid!");
556        this.mstrTimeStampFmt = pstrTSFmt;
557    }
558
559/*------------------------------------------------------------------------------
560 * Public methods
561------------------------------------------------------------------------------*/
562    public int getTotalSections()
563    {
564        return this.iniSections.size();
565    }
566
567    /**
568     * Returns a string array containing names of all sections in INI file.
569     * @return the string array of section names
570     */
571    public String[] getAllSectionNames()
572    {
573        int        iCntr  = 0;
574        Iterator<String>   iter   = null;
575        String[]   arrRet = null;
576
577        try
578        {
579            if (this.iniSections.size() > 0)
580            {
581                arrRet = new String[this.iniSections.size()];
582                for (iter = this.iniSections.keySet().iterator();; iter.hasNext())
583                {
584                    arrRet[iCntr] = (String) iter.next();
585                    iCntr++;
586                }
587            }
588        }
589        catch (NoSuchElementException NSEExIgnore)
590        {
591        }
592        finally
593        {
594            if (iter != null) iter = null;
595        }
596        return arrRet;
597    }
598
599    /**
600     * Returns a string array containing names of all the properties under specified section.
601     * @param pstrSection the name of the section for which names of properties is to be retrieved.
602     * @return the string array of property names.
603     */
604    public String[] getPropertyNames(String pstrSection)
605    {
606        String[]   arrRet = null;
607        INISection objSec = null;
608
609        objSec = (INISection) this.iniSections.get(pstrSection);
610        if (objSec != null)
611        {
612            arrRet = objSec.getPropNames();
613            objSec = null;
614        }
615        return arrRet;
616    }
617
618    /**
619     * Returns a map containing all the properties under specified section.
620     * @param pstrSection the name of the section for which properties are to be retrieved.
621     * @return the map of properties.
622     */
623    public Map<String, INIProperty> getProperties(String pstrSection)
624    {
625        Map<String, INIProperty>        hmRet = null;
626        INISection objSec = null;
627
628        objSec = (INISection) this.iniSections.get(pstrSection);
629        if (objSec != null)
630        {
631            hmRet = objSec.getProperties();
632            objSec = null;
633        }
634        return hmRet;
635    }
636
637    /**
638     * Removed specified property from the specified section. If the specified
639     * section or the property does not exist, does nothing.
640     * @param pstrSection the section name.
641     * @param pstrProp the name of the property to be removed.
642     */
643    public void removeProperty(String pstrSection, String pstrProp)
644    {
645        INISection objSec = null;
646
647        objSec = (INISection) this.iniSections.get(pstrSection);
648        if (objSec != null)
649        {
650            objSec.removeProperty(pstrProp);
651                objSec = null;
652        }
653    }
654
655    /**
656     * Removes the specified section if one exists, otherwise does nothing.
657     * @param pstrSection the name of the section to be removed.
658     */
659    public void removeSection(String pstrSection)
660    {
661        if (this.iniSections.containsKey(pstrSection))
662            this.iniSections.remove(pstrSection);
663    }
664
665    /**
666     * Flush changes back to the disk file. If the disk file does not exists then
667     * creates the new one. 
668     * @ 
669     */
670    public boolean save() 
671    {
672        boolean    blnRet    = false;
673        File       objFile   = null;
674        String     strName   = null;
675        String     strTemp   = null;
676        Iterator<String>   itrSec    = null;
677        INISection objSec    = null;
678        FileWriter objWriter = null;
679
680        try
681        {
682            if (this.iniSections.size() == 0) return false;
683            objFile = ManagedFileAccess.csfile(this.filepath);
684            if (objFile.exists()) objFile.delete();
685            objWriter = new FileWriter(objFile);
686            itrSec = this.iniSections.keySet().iterator();
687            while (itrSec.hasNext())
688            {
689                strName = (String) itrSec.next();
690                objSec = (INISection) this.iniSections.get(strName);
691                strTemp = objSec.toString();
692                objWriter.write(strTemp);
693                objWriter.write("\r\n");
694                objSec = null;
695            }
696            blnRet = true;
697        }
698        catch (IOException IOExIgnore)
699        {
700        }
701        finally
702        {
703            if (objWriter != null)
704            {
705                closeWriter(objWriter);
706                objWriter = null;
707            }
708            if (objFile != null) objFile = null;
709            if (itrSec != null) itrSec = null;
710        }
711        return blnRet;
712    }
713
714    public boolean save(OutputStream stream) 
715    {
716        boolean    blnRet    = false;
717        String     strName   = null;
718        String     strTemp   = null;
719        Iterator<String>   itrSec    = null;
720        INISection objSec    = null;
721        OutputStreamWriter objWriter = null;
722
723        try
724        {
725            if (this.iniSections.size() == 0) return false;
726            objWriter = new OutputStreamWriter(stream, "UTF-8");
727            itrSec = this.iniSections.keySet().iterator();
728            while (itrSec.hasNext())
729            {
730                strName = (String) itrSec.next();
731                objSec = (INISection) this.iniSections.get(strName);
732                strTemp = objSec.toString();
733                objWriter.write(strTemp);
734                objWriter.write("\r\n");
735                objSec = null;
736            }
737            blnRet = true;
738        }
739        catch (IOException IOExIgnore)
740        {
741        }
742        finally
743        {
744            if (objWriter != null)
745            {
746                closeWriter(objWriter);
747                objWriter = null;
748            }
749            if (itrSec != null) itrSec = null;
750        }
751        return blnRet;
752    }
753
754    
755/*------------------------------------------------------------------------------
756 * Helper functions
757 *----------------------------------------------------------------------------*/
758    /**
759     * Procedure to read environment variables.
760     * Thanx to http://www.rgagnon.com/howto.html for this implementation.
761     */
762    private Properties getEnvVars()
763    {
764        Process p = null;
765        Properties envVars = new Properties();
766
767        try
768        {
769            Runtime r = Runtime.getRuntime();
770            String OS = System.getProperty("os.name").toLowerCase();
771
772            if (OS.indexOf("windows 9") > -1)
773            {
774                p = r.exec("command.com /c set");
775            }
776            else if ((OS.indexOf("nt") > -1) ||
777                     (OS.indexOf("windows 2000") > -1) ||
778                     (OS.indexOf("windows xp") > -1))
779            {
780                p = r.exec("cmd.exe /c set");
781            }
782            else
783            {
784                // our last hope, we assume Unix (thanks to H. Ware for the fix)
785                p = r.exec("env");
786            }
787            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
788            String line;
789            while((line = br.readLine()) != null)
790            {
791                int idx = line.indexOf('=');
792                String key = line.substring(0, idx);
793                String value = line.substring(idx + 1);
794                envVars.setProperty(key, value);
795            }
796        }
797        catch (Exception ExIgnore)
798        {
799        }
800        return envVars;
801    }
802
803    /**
804     * Helper function to check the date time formats.
805     * @param pstrDtFmt the date time format string to be checked.
806     * @return true for valid date/time format, false otherwise.
807     */
808    private boolean checkDateTimeFormat(String pstrDtFmt)
809    {
810        boolean    blnRet = false;
811        DateFormat objFmt = null;
812
813        try
814        {
815            objFmt = new SimpleDateFormat(pstrDtFmt);
816            blnRet = true;
817        }
818        catch (NullPointerException NPExIgnore)
819        {
820        }
821        catch (IllegalArgumentException IAExIgnore)
822        {
823        }
824        finally
825        {
826            if (objFmt != null) objFmt = null;
827        }
828        return blnRet;
829    }
830
831    /**
832     * Reads the INI file and load its contentens into a section collection after 
833     * parsing the file line by line. 
834     */
835    private void loadStream(InputStream stream)
836    {
837        int            iPos       = -1;
838        String         strLine    = null;
839        String         strSection = null;
840        String         strRemarks = null;
841        BufferedReader objBRdr    = null;
842        InputStreamReader     objFRdr    = null;
843        INISection     objSec     = null;
844
845        try
846        {
847            objFRdr = new InputStreamReader(stream);
848            if (objFRdr != null)
849            {
850                objBRdr = new BufferedReader(objFRdr);
851                if (objBRdr != null)
852                {
853                    while (objBRdr.ready())
854                    {
855                        iPos = -1;
856                        strLine  = null;
857                        strLine = objBRdr.readLine().trim();
858                        if (strLine == null)
859                        {
860                        }
861                        else if (strLine.length() == 0)
862                        {
863                        }
864                        else if (strLine.substring(0, 1).equals(";"))
865                        {
866                            if (strRemarks == null)
867                                strRemarks = strLine.substring(1);
868                            else if (strRemarks.length() == 0)
869                                strRemarks = strLine.substring(1);
870                            else
871                                strRemarks = strRemarks + "\r\n" + strLine.substring(1);
872                        }
873                        else if (strLine.startsWith("[") && strLine.endsWith("]"))
874                        {
875                            // Section start reached create new section
876                            if (objSec != null) 
877                                this.iniSections.put(strSection.trim(), objSec);
878                            objSec = null;
879                            strSection = strLine.substring(1, strLine.length() - 1);
880                            objSec = new INISection(strSection.trim(), strRemarks);
881                            strRemarks = null;
882                        }
883                        else if ((iPos = strLine.indexOf("=")) > 0 && objSec != null)
884                        {
885                            // read the key value pair 012345=789
886                            objSec.setProperty(strLine.substring(0, iPos).trim(), 
887                                                strLine.substring(iPos + 1).trim(), 
888                                                strRemarks);
889                            strRemarks = null;
890                        }
891                        else 
892                        {
893                            objSec.setProperty(strLine, "", strRemarks);
894                      
895                        }
896                    }
897                    if (objSec != null)
898                        this.iniSections.put(strSection.trim(), objSec);
899                    this.fileSuccessfullyLoaded = true;
900                }
901            }
902        }
903        catch (FileNotFoundException FNFExIgnore)
904        {
905            this.iniSections.clear();
906        }
907        catch (IOException IOExIgnore)
908        {
909            this.iniSections.clear();
910        }
911        catch (NullPointerException NPExIgnore)
912        {
913            this.iniSections.clear();
914        }
915        finally
916        {
917            if (objBRdr != null)
918            {
919                closeReader(objBRdr);
920                objBRdr = null;
921            }
922            if (objFRdr != null)
923            {
924                closeReader(objFRdr);
925                objFRdr = null;
926            }
927            if (objSec != null) objSec = null;
928        }
929    }
930
931    /**
932     * Reads the INI file and load its contentens into a section collection after 
933     * parsing the file line by line. 
934     */
935    private void loadFile()
936    {
937        int            iPos       = -1;
938        String         strLine    = null;
939        String         strSection = null;
940        String         strRemarks = null;
941        BufferedReader objBRdr    = null;
942        FileReader     objFRdr    = null;
943        INISection     objSec     = null;
944
945        try
946        {
947            objFRdr = new FileReader(this.filepath);
948            if (objFRdr != null)
949            {
950                objBRdr = new BufferedReader(objFRdr);
951                if (objBRdr != null)
952                {
953                    while (objBRdr.ready())
954                    {
955                        iPos = -1;
956                        strLine  = null;
957                        strLine = objBRdr.readLine().trim();
958                        if (strLine == null)
959                        {
960                        }
961                        else if (strLine.length() == 0)
962                        {
963                        }
964                        else if (strLine.substring(0, 1).equals(";"))
965                        {
966                            if (strRemarks == null)
967                                strRemarks = strLine.substring(1);
968                            else if (strRemarks.length() == 0)
969                                strRemarks = strLine.substring(1);
970                            else
971                                strRemarks = strRemarks + "\r\n" + strLine.substring(1);
972                        }
973                        else if (strLine.startsWith("[") && strLine.endsWith("]"))
974                        {
975                            // Section start reached create new section
976                            if (objSec != null) 
977                                this.iniSections.put(strSection.trim(), objSec);
978                            objSec = null;
979                            strSection = strLine.substring(1, strLine.length() - 1);
980                            objSec = new INISection(strSection.trim(), strRemarks);
981                            strRemarks = null;
982                        }
983                        else if ((iPos = strLine.indexOf("=")) > 0 && objSec != null)
984                        {
985                            // read the key value pair 012345=789
986                            objSec.setProperty(strLine.substring(0, iPos).trim(), 
987                                                strLine.substring(iPos + 1).trim(), 
988                                                strRemarks);
989                            strRemarks = null;
990                        }
991                        else 
992                        {
993                            objSec.setProperty(strLine, "", strRemarks);
994                      
995                        }
996                    }
997                    if (objSec != null)
998                        this.iniSections.put(strSection.trim(), objSec);
999                    this.fileSuccessfullyLoaded = true;
1000                }
1001            }
1002        }
1003        catch (FileNotFoundException FNFExIgnore)
1004        {
1005            this.iniSections.clear();
1006        }
1007        catch (IOException IOExIgnore)
1008        {
1009            this.iniSections.clear();
1010        }
1011        catch (NullPointerException NPExIgnore)
1012        {
1013            this.iniSections.clear();
1014        }
1015        finally
1016        {
1017            if (objBRdr != null)
1018            {
1019                closeReader(objBRdr);
1020                objBRdr = null;
1021            }
1022            if (objFRdr != null)
1023            {
1024                closeReader(objFRdr);
1025                objFRdr = null;
1026            }
1027            if (objSec != null) objSec = null;
1028        }
1029    }
1030
1031    /**
1032     * Helper function to close a reader object.
1033     * @param pobjRdr the reader to be closed.
1034     */
1035    private void closeReader(Reader pobjRdr)
1036    {
1037        if (pobjRdr == null) return;
1038        try
1039        {
1040            pobjRdr.close();
1041        }
1042        catch (IOException IOExIgnore)
1043        {
1044        }
1045    }
1046
1047    /**
1048     * Helper function to close a writer object.
1049     * @param pobjWriter the writer to be closed.
1050     */
1051    private void closeWriter(Writer pobjWriter)
1052    {
1053        if (pobjWriter == null) return;
1054
1055        try
1056        {
1057            pobjWriter.close();
1058        }
1059        catch (IOException IOExIgnore)
1060        {
1061        }
1062    }
1063    
1064    /**
1065     * Helper method to check the existance of a file.
1066     * @param pathName the full path and name of the file to be checked.
1067     * @return true if file exists, false otherwise.
1068     */
1069    private boolean checkFile(String pathName)
1070    {
1071        boolean blnRet  = false;
1072        File    objFile = null;
1073
1074        try
1075        {
1076            objFile = ManagedFileAccess.csfile(pathName);
1077            blnRet = (objFile.exists() && objFile.isFile());
1078        }
1079        catch (Exception e)
1080        {
1081            blnRet = false;
1082        }
1083        finally
1084        {
1085            if (objFile != null) objFile = null;
1086        }
1087        return blnRet;
1088    }
1089
1090    /**
1091     * Converts a java.util.date into String 
1092     * @param date Date to be converted to String
1093     * @param dateFormat The date format pattern.
1094     * @return String
1095     */
1096    private String utilDateToStr(Date date, String dateFormat)
1097    {
1098        String strRet = null;
1099        SimpleDateFormat dtFmt = null;
1100
1101        try
1102        {
1103            dtFmt = new SimpleDateFormat(dateFormat);
1104            strRet = dtFmt.format(date);
1105        }
1106        catch (Exception e)
1107        {
1108            strRet = null;
1109        }
1110        finally
1111        {
1112            if (dtFmt != null) dtFmt = null;
1113        }
1114        return strRet;
1115    }
1116
1117    /**
1118     * Converts the given sql timestamp object to a string representation. The format
1119     * to be used is to be obtained from the configuration file.
1120     *  
1121     * @param zonedDateTime the sql timestamp object to be converted.
1122     * @param timeFormat the time format used to store the zonedDateTime value.
1123     * @return the formatted string representation of the timestamp.
1124     */
1125    private String timeToString(ZonedDateTime zonedDateTime, String timeFormat)
1126    {
1127        String stringValue = null;
1128      DateTimeFormatter dateTimeFormatter = null;
1129
1130        try
1131        {
1132            dateTimeFormatter = DateTimeFormatter.ofPattern(timeFormat);
1133            stringValue = dateTimeFormatter.format(zonedDateTime);
1134        }
1135        catch (IllegalArgumentException  iae)
1136        {
1137            stringValue = "";
1138        }
1139        catch (NullPointerException npe)
1140        {
1141            stringValue = "";
1142        }
1143        finally
1144        {
1145            if (dateTimeFormatter != null) dateTimeFormatter = null;
1146        }
1147        return stringValue;
1148    }
1149
1150    /**
1151     * This function deletes the remark characters ';' from source string
1152     * @param pstrSrc the source  string
1153     * @return the converted string
1154     */
1155    private String delRemChars(String pstrSrc)
1156    {
1157        int    intPos = 0;
1158
1159        if (pstrSrc == null) return null;
1160        while ((intPos = pstrSrc.indexOf(";")) >= 0)
1161        {
1162            if (intPos == 0)
1163                pstrSrc = pstrSrc.substring(intPos + 1);
1164            else if (intPos > 0)
1165                pstrSrc = pstrSrc.substring(0, intPos) + pstrSrc.substring(intPos + 1);
1166        }
1167        return pstrSrc;
1168    }
1169
1170    /**
1171     * This function adds a remark character ';' in source string.
1172     * @param pstrSrc source string
1173     * @return converted string.
1174     */
1175    private String addRemChars(String pstrSrc)
1176    {
1177        int intLen  = 2;
1178        int intPos  = 0;
1179        int intPrev = 0;
1180
1181        String strLeft  = null;
1182        String strRight = null;
1183
1184        if (pstrSrc == null) return null;
1185        while (intPos >= 0)
1186        {
1187            intLen = 2;
1188            intPos = pstrSrc.indexOf("\r\n", intPrev);
1189            if (intPos < 0)
1190            {
1191                intLen = 1;
1192                intPos = pstrSrc.indexOf("\n", intPrev);
1193                if (intPos < 0) intPos = pstrSrc.indexOf("\r", intPrev);
1194            }
1195            if (intPos == 0)
1196            {
1197                pstrSrc = ";\r\n" + pstrSrc.substring(intPos + intLen);
1198                intPrev = intPos + intLen + 1;
1199            }
1200            else if (intPos > 0)
1201            {
1202                strLeft = pstrSrc.substring(0, intPos);
1203                strRight = pstrSrc.substring(intPos + intLen);
1204                if (strRight == null)
1205                    pstrSrc = strLeft;
1206                else if (strRight.length() == 0)
1207                    pstrSrc = strLeft;
1208                else
1209                    pstrSrc = strLeft + "\r\n;" + strRight;
1210                intPrev = intPos + intLen + 1;
1211            }
1212        }
1213        if (!pstrSrc.substring(0, 1).equals(";"))
1214            pstrSrc = ";" + pstrSrc;
1215        pstrSrc = pstrSrc + "\r\n";
1216        return pstrSrc;
1217    }
1218/*------------------------------------------------------------------------------
1219 * Main entry point to test the functionality.
1220 *----------------------------------------------------------------------------*/
1221    /**
1222     * The main entry point for testing.
1223     * @param pstrArgs the command line arguments array if any.
1224     * @ 
1225     */
1226    public static void main(String[] pstrArgs) 
1227    {
1228        IniFile objINI = null;
1229        String  strFile = null;
1230
1231        if (pstrArgs.length == 0) return;
1232
1233        strFile = pstrArgs[0];
1234        // Following call will load the strFile if one exists.
1235        objINI = new IniFile(strFile);
1236
1237//        objINI.addSection("QADatabase", "QA database connection details\nUsed for QA Testing");
1238//        objINI.setStringProperty("QADatabase", "SID", "ORCL", null);
1239//        objINI.setStringProperty("QADatabase", "UserId", "System", null);
1240//        objINI.setStringProperty("QADatabase", "Password", "Manager", null);
1241//        objINI.setStringProperty("QADatabase", "HostName", "DBServer", null);
1242//        objINI.setIntegerProperty("QADatabase", "Port", 1521, null);
1243//        objINI.setStringProperty("QADatabase", "OracleHome", "%ORACLE_HOME%", null);
1244//        
1245        // objINI.setSectionComments("Folders", "Directories where generated files are stored");
1246        objINI.setStringProperty("Folders", "folder1", "G:\\Temp", null);
1247        objINI.setStringProperty("Folders", "folder2", "G:\\Temp\\Backup", null);
1248
1249        // Save changes back to strFile.
1250        objINI.save();
1251        objINI = null;
1252    }
1253
1254/*------------------------------------------------------------------------------
1255 * Private class representing the INI Section.
1256 *----------------------------------------------------------------------------*/
1257    /**
1258     * Class to represent the individual ini file section.
1259     * @author Prasad P. Khandekar
1260     * @version 1.0
1261     * @since 1.0
1262     */
1263    private class INISection
1264    {
1265        /** Variable to hold any comments associated with this section */
1266        private String mstrComment;
1267
1268        /** Variable to hold the section name. */
1269        private String mstrName;
1270        
1271        /** Variable to hold the properties falling under this section. */
1272        private LinkedHashMap<String, INIProperty> mhmapProps;
1273
1274        /**
1275         * Construct a new section object identified by the name specified in 
1276         * parameter.
1277         * @param pstrSection The new sections name.
1278         */
1279        public INISection(String pstrSection)
1280        {
1281            this.mstrName =  pstrSection;
1282            this.mhmapProps = new LinkedHashMap<String, INIProperty>();
1283        }
1284
1285        /**
1286         * Construct a new section object identified by the name specified in 
1287         * parameter and associated comments.
1288         * @param pstrSection The new sections name.
1289         * @param pstrComments the comments associated with this section.
1290         */
1291        public INISection(String pstrSection, String pstrComments)
1292        {
1293            this.mstrName =  pstrSection;
1294            this.mstrComment = delRemChars(pstrComments);
1295            this.mhmapProps = new LinkedHashMap<String, INIProperty>();
1296        }
1297        
1298        /**
1299         * Sets the comments associated with this section.
1300         * @param pstrComments the comments
1301         */
1302        public void setSecComments(String pstrComments)
1303        {
1304            this.mstrComment = delRemChars(pstrComments);
1305        }
1306
1307        /**
1308         * Removes specified property value from this section. 
1309         * @param pstrProp The name of the property to be removed.
1310         */
1311        public void removeProperty(String pstrProp)
1312        {
1313            if (this.mhmapProps.containsKey(pstrProp))
1314                this.mhmapProps.remove(pstrProp);
1315        }
1316
1317        /**
1318         * Creates or modifies the specified property value.
1319         * @param pstrProp The name of the property to be created or modified. 
1320         * @param pstrValue The new value for the property.
1321         * @param pstrComments the associated comments
1322         */
1323        public void setProperty(String pstrProp, String pstrValue, String pstrComments)
1324        {
1325            this.mhmapProps.put(pstrProp, new INIProperty(pstrProp, pstrValue, pstrComments));
1326        }
1327
1328        /**
1329         * Returns a map of all properties.
1330         * @return a map of all properties
1331         */
1332        public Map<String, INIProperty> getProperties()
1333        {
1334            return Collections.unmodifiableMap(this.mhmapProps);
1335        }
1336
1337        /**
1338         * Returns a string array containing names of all the properties under 
1339         * this section. 
1340         * @return the string array of property names.
1341         */
1342        public String[] getPropNames()
1343        {
1344            int      iCntr  = 0;
1345            String[] arrRet = null;
1346            Iterator<String> iter   = null;
1347
1348            try
1349            {
1350                if (this.mhmapProps.size() > 0)
1351                {
1352                    arrRet = new String[this.mhmapProps.size()]; 
1353                    for (iter = this.mhmapProps.keySet().iterator();iter.hasNext();)
1354                    {
1355                        arrRet[iCntr] = (String) iter.next();
1356                        iCntr++;
1357                    }
1358                }
1359            }
1360            catch (NoSuchElementException NSEExIgnore)
1361            {
1362                arrRet = null;
1363            }
1364            return arrRet;
1365        }
1366
1367        /**
1368         * Returns underlying value of the specified property. 
1369         * @param pstrProp the property whose underlying value is to be etrieved.
1370         * @return the property value.
1371         */
1372        public INIProperty getProperty(String pstrProp)
1373        {
1374            INIProperty objRet = null;
1375
1376            if (this.mhmapProps.containsKey(pstrProp))
1377                objRet = (INIProperty) this.mhmapProps.get(pstrProp);
1378            return objRet;
1379        }
1380
1381        /* (non-Javadoc)
1382         * @see java.lang.Object#toString()
1383         */
1384        @Override
1385                public String toString()
1386        {
1387            Set<String>          colKeys = null;
1388            String       strRet  = "";
1389            Iterator<String>     iter    = null;
1390            INIProperty  objProp = null;
1391            StringBuffer objBuf  = new StringBuffer();
1392
1393            if (this.mstrComment != null)
1394                objBuf.append(addRemChars(this.mstrComment));
1395            objBuf.append("[" + this.mstrName + "]\r\n");
1396            colKeys = this.mhmapProps.keySet();
1397            if (colKeys != null)
1398            {
1399                iter = colKeys.iterator();
1400                if (iter != null)
1401                {
1402                    while (iter.hasNext())
1403                    {
1404                        objProp = (INIProperty) this.mhmapProps.get(iter.next());
1405                        objBuf.append(objProp.toString());
1406                        objBuf.append("\r\n");
1407                        objProp = null;
1408                    }
1409                }
1410            }
1411            strRet = objBuf.toString();
1412
1413            objBuf  = null;
1414            iter    = null;
1415            colKeys = null;
1416            return strRet;
1417        }
1418    }
1419
1420/*------------------------------------------------------------------------------
1421 * Private class representing the INI Property.
1422 *----------------------------------------------------------------------------*/
1423    /**
1424     * This class represents a key value pair called property in an INI file. 
1425     * @author Prasad P. Khandekar
1426     * @version 1.0
1427     * @since 1.0
1428     */
1429    private class INIProperty
1430    {
1431        /** Variable to hold name of this property */
1432        private String mstrName;
1433        /** Variable to hold value of this property */
1434        private String mstrValue;
1435        /** Variable to hold comments associated with this property */
1436        private String mstrComments;
1437
1438        /**
1439         * Constructor
1440         * @param pstrName the name of this property.
1441         * @param pstrValue the value of this property.
1442         * @param pstrComments the comments associated with this property.
1443         */
1444        public INIProperty(String pstrName, String pstrValue, String pstrComments)
1445        {
1446            this.mstrName = pstrName;
1447            this.mstrValue = pstrValue;
1448            this.mstrComments = delRemChars(pstrComments);
1449        }
1450
1451        /**
1452         * Returns value of this property. If value contains a reference to 
1453         * environment avriable then this reference is replaced by actual value
1454         * before the value is returned.
1455         * @return the value of this property.
1456         */
1457        public String getPropValue()
1458        {
1459            int    intStart = 0;
1460            int    intEnd   = 0;
1461            String strVal   = null;
1462            String strVar   = null;
1463            String strRet   = null;
1464
1465            strRet = this.mstrValue;
1466            intStart = strRet.indexOf("%");
1467            if (intStart >= 0)
1468            {
1469                intEnd = strRet.indexOf("%", intStart + 1);
1470                strVar = strRet.substring(intStart + 1, intEnd);
1471                strVal = mpropEnv.getProperty(strVar);
1472                if (strVal != null)
1473                {
1474                    strRet = strRet.substring(0, intStart) + strVal + 
1475                                strRet.substring(intEnd + 1);
1476                }
1477            }
1478            return strRet;
1479        }
1480
1481        /* (non-Javadoc)
1482         * @see java.lang.Object#toString()
1483         */
1484        @Override
1485                public String toString()
1486        {
1487            String strRet = "";
1488
1489            if (this.mstrComments != null)
1490                strRet = addRemChars(mstrComments);
1491            strRet = strRet + this.mstrName + " = " + this.mstrValue;
1492            return strRet;
1493        }
1494    }
1495
1496    public boolean hasSection(String sectionName) {
1497      if (getAllSectionNames() != null) {
1498        for (String s : getAllSectionNames()) {
1499          if (s.equalsIgnoreCase(sectionName)) {
1500            return true;
1501          }
1502        }
1503      }
1504      return false;
1505    }
1506
1507    public boolean hasProperty(String section, String name) {
1508      return getStringProperty(section, name) != null;
1509    }
1510}