View Javadoc

1   /**
2    * Copyright (c) 2011, University of Konstanz, Distributed Systems Group
3    * All rights reserved.
4    * 
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions are met:
7    * * Redistributions of source code must retain the above copyright
8    * notice, this list of conditions and the following disclaimer.
9    * * Redistributions in binary form must reproduce the above copyright
10   * notice, this list of conditions and the following disclaimer in the
11   * documentation and/or other materials provided with the distribution.
12   * * Neither the name of the University of Konstanz nor the
13   * names of its contributors may be used to endorse or promote products
14   * derived from this software without specific prior written permission.
15   * 
16   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19   * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
20   * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21   * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24   * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26   */
27  
28  package org.treetank.service.xml.serialize;
29  
30  import static com.google.common.base.Preconditions.checkState;
31  
32  import java.io.BufferedReader;
33  import java.io.File;
34  import java.io.FileReader;
35  import java.io.IOException;
36  import java.lang.reflect.Field;
37  import java.util.concurrent.ConcurrentHashMap;
38  import java.util.concurrent.ConcurrentMap;
39  
40  /**
41   * <h1>XMLSerializerProperties</h1>
42   * 
43   * <p>
44   * XMLSerializer properties.
45   * </p>
46   * 
47   * @author Johannes Lichtenberger, University of Konstanz
48   * 
49   */
50  public final class XMLSerializerProperties {
51  
52      // ============== Class constants. =================
53  
54      /** YES maps to true. */
55      private static final boolean YES = true;
56  
57      /** NO maps to false. */
58      private static final boolean NO = false;
59  
60      // ============ Shredding constants. ===============
61  
62      /** Serialize TT-ID: yes/no. */
63      public static final Object[] S_ID = {
64          "serialize-id", NO
65      };
66  
67      /** Serialization parameter: yes/no. */
68      public static final Object[] S_INDENT = {
69          "indent", YES
70      };
71  
72      /** Specific serialization parameter: number of spaces to indent. */
73      public static final Object[] S_INDENT_SPACES = {
74          "indent-spaces", 2
75      };
76  
77      /** Serialize REST: yes/no. */
78      public static final Object[] S_REST = {
79          "serialize-rest", NO
80      };
81  
82      /** Serialize XML declaration: yes/no. */
83      public static final Object[] S_XMLDECL = {
84          "xmldecl", YES
85      };
86  
87      /** Property file. */
88      private static String mFilePath;
89  
90      /** Properties. */
91      private final ConcurrentMap<String, Object> mProps = new ConcurrentHashMap<String, Object>();
92  
93      /**
94       * Constructor.
95       */
96      public XMLSerializerProperties() {
97          try {
98              for (final Field f : getClass().getFields()) {
99                  final Object obj = f.get(null);
100                 if (!(obj instanceof Object[])) {
101                     continue;
102                 }
103                 final Object[] arr = (Object[])obj;
104                 mProps.put(arr[0].toString(), arr[1]);
105             }
106         } catch (IllegalAccessException exc) {
107             exc.printStackTrace();
108         }
109     }
110 
111     /**
112      * <h2>Read properties</h2>
113      * 
114      * <p>
115      * Read properties file into a concurrent HashMap. Format of properties file:
116      * </p>
117      * 
118      * <ul>
119      * <li>xmldecl=yes (possible values: yes/no)</li>
120      * <li>indent=no (possible values: yes/no)</li>
121      * <li>indent-spaces=2 (possible values: Integer)</li>
122      * <li>serialize-rest=no (possible values: yes/no)</li>
123      * <li>serialize-id=no (possible values: yes/no)</li>
124      * </ul>
125      * 
126      * <p>
127      * Note that currently all properties have to be set. If specific key/value pairs are specified more than
128      * once the last values are preserved, so the default values are overridden by user specified values.
129      * </p>
130      * 
131      * @param paramFilePath
132      *            Path to properties file.
133      * @return ConcurrentMap which holds property key/values.
134      */
135     public ConcurrentMap<String, Object> readProps(final String paramFilePath) {
136         mFilePath = paramFilePath;
137         checkState(new File(mFilePath).exists(), "Properties file doesn't exist!");
138 
139         try {
140             // Read and parse file.
141             final BufferedReader buffReader = new BufferedReader(new FileReader(mFilePath));
142             for (String line = buffReader.readLine(); line != null; line = buffReader.readLine()) {
143                 line = line.trim();
144                 if (line.isEmpty()) {
145                     continue;
146                 }
147 
148                 final int equals = line.indexOf('=');
149                 if (equals < 0) {
150                     System.out.println("Properties file has no '=' sign in line -- parsing error!");
151                 }
152 
153                 final String key = line.substring(0, equals).toUpperCase();
154                 final String value = line.substring(equals + 1);
155 
156                 mProps.put(key, value);
157                 buffReader.close();
158             }
159         } catch (final IOException exc) {
160             exc.printStackTrace();
161         }
162 
163         return mProps;
164     }
165 
166     // /**
167     // * Writes the properties to disk.
168     // */
169     // public final synchronized void write() {
170     // final File file = new File(mFilePath);
171     //
172     // try {
173     // // User has already specified key/values, so cache it.
174     // final StringBuilder strBuilder = new StringBuilder();
175     // if (file.exists()) {
176     // final BufferedReader buffReader = new BufferedReader(new
177     // FileReader(file));
178     //
179     // for (String line = buffReader.readLine(); line != null; line =
180     // buffReader.readLine()) {
181     // strBuilder.append(line + ECharsForSerializing.NEWLINE);
182     // }
183     //
184     // buffReader.close();
185     // }
186     //
187     // // Write map properties to file.
188     // final BufferedWriter buffWriter = new BufferedWriter(new
189     // FileWriter(file));
190     // for (final Field f : getClass().getFields()) {
191     // final Object obj = f.get(null);
192     // if (!(obj instanceof Object[]))
193     // continue;
194     // final String key = ((Object[])obj)[0].toString();
195     // final Object value = ((Object[])obj)[1];
196     // buffWriter.write(key + " = " + value + ECharsForSerializing.NEWLINE);
197     // }
198     //
199     // // Append cached properties.
200     // buffWriter.write(strBuilder.toString());
201     // buffWriter.close();
202     // } catch (final Exception e) {
203     // LOGGER.error(e.getMessage(), e);
204     // }
205     // }
206 
207     /**
208      * Get properties map.
209      * 
210      * @return ConcurrentMap with key/value property pairs.
211      */
212     public ConcurrentMap<String, Object> getmProps() {
213         return mProps;
214     }
215 
216 }