1 /*
2 Copyright (C) 2000 - 2007 Grid Systems, S.A.
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License, version 2, as
6 published by the Free Software Foundation.
7
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 */
17 package com.gridsystems.utils;
18
19 import java.io.IOException;
20 import java.io.File;
21 import java.io.InputStream;
22 import java.io.FileOutputStream;
23 import java.util.Properties;
24 import java.io.OutputStreamWriter;
25 import java.io.BufferedWriter;
26
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29
30 /**
31 * This class implements a SecureProperties object linked to a File object.
32 * A SecureProperties file assures that it is not corrupted.
33 *
34 * @author Luis Gaspart
35 * @version 1.0
36 */
37 public class SecureFileProperties extends FileProperties {
38
39 /**
40 * Default Serial UID.
41 */
42 private static final long serialVersionUID = 1324523452343L;
43
44 /**
45 * Class logger.
46 */
47 private static final Log LOG = LogFactory.getLog(SecureFileProperties.class);
48
49 /**
50 * Creates a new instance.
51 *
52 * @param f The file to link this instance to
53 * @param defaults The default values
54 */
55 public SecureFileProperties(File f, Properties defaults) {
56 super(f, defaults);
57 }
58
59 /**
60 * Creates a new instance.
61 *
62 * @param f The file to link this instance to
63 */
64 public SecureFileProperties(File f) {
65 super(f);
66 }
67
68 /**
69 * Propagates changes in memory to the file associated with this object.
70 */
71 @Override public synchronized void commit() {
72 FileOutputStream fos = null;
73 try {
74 fos = new FileOutputStream(f);
75 this.store(fos, header);
76 BufferedWriter wb = new BufferedWriter(new OutputStreamWriter(fos, "8859_1"));
77 wb.write("completed=ok"); //Checks that the file is not corrupt
78 wb.newLine();
79 wb.close();
80 } catch (IOException e) {
81 LOG.warn("Could not commit SecureFileProperties changes", e);
82 } finally {
83 FileUtils.close(fos);
84 this.lastModified = f.lastModified();
85 }
86 }
87
88 /**
89 * {@inheritDoc}
90 */
91 @Override
92 public synchronized void load(InputStream inStream) throws IOException {
93 this.clear();
94 super.load(inStream); //uses Properties.load
95 String prop = (String) this.get("completed");
96 if (!"ok".equals(prop)) {
97 this.clear();
98 throw new IOException("The file is corrupt:" + f.getName());
99 } else {
100 this.remove("completed");
101 }
102 }
103 }