KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > subversion > config > KVFile


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19 package org.netbeans.modules.subversion.config;
20
21 import java.io.ByteArrayOutputStream JavaDoc;
22 import java.io.EOFException JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.OutputStream JavaDoc;
27 import java.io.UnsupportedEncodingException JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.TreeMap JavaDoc;
32 import org.netbeans.modules.subversion.util.FileUtils;
33 import org.openide.ErrorManager;
34
35 /**
36  * Handles the credential or property files used by Subversion.
37  *
38  * @author Tomas Stupka
39  *
40  */

41 public class KVFile {
42
43     /** a Map holding the entries*/
44     private Map JavaDoc<Key, byte[]> map;
45     /** a Map holding the keys*/
46     private Map JavaDoc<String JavaDoc, Key> keyMap;
47     /** the credential or property file */
48     private final File JavaDoc file;
49
50     /**
51      * Creates a new instance
52      *
53      * @parameter file the credential or property file
54      */

55     public KVFile(File JavaDoc file) {
56         this.file = file;
57         try {
58             if(file.exists()) {
59                 parse();
60             }
61         } catch (IOException JavaDoc ex) {
62             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
63         }
64     }
65         
66     /**
67      * Returns the value for the given Key
68      *
69      * @param key
70      * @return the value stored under the given Key
71      */

72     protected byte[] getValue(Key key) {
73         return (byte[]) getMap().get(key);
74     }
75
76     /**
77      * Returns the value for the given Key as a String
78      *
79      * @param key
80      * @return the value stored under the given Key as a String
81      */

82     protected String JavaDoc getStringValue(Key key) {
83         try {
84             byte[] value = getValue(key);
85
86             if (value == null) {
87                 return null;
88             }
89             return new String JavaDoc(value, "UTF8");
90         } catch (UnsupportedEncodingException JavaDoc ex) {
91             ErrorManager.getDefault().notify(ErrorManager.ERROR, ex);
92             return null;
93         }
94     }
95     
96     /**
97      * Stores the given value under the given Key
98      *
99      */

100     protected void setValue(Key key, byte[] value) {
101         getMap().put(key, value);
102     }
103  
104     /**
105      * Returns the Map holding the Key and value pairs
106      *
107      * @return map
108      */

109     public Map JavaDoc<Key, byte[]> getMap() {
110         if(map==null) {
111             map = new TreeMap JavaDoc<Key, byte[]>();
112         }
113         return map;
114     }
115
116     /**
117      * Returns the Map holding the Keys
118      *
119      * @return map
120      */

121     private Map JavaDoc<String JavaDoc, Key> getKeyMap() {
122         if(keyMap == null) {
123             keyMap = new HashMap JavaDoc<String JavaDoc, Key>();
124         }
125         return keyMap;
126     }
127
128     protected Key getKey(Key key) {
129         Key storedKey = getKey(key.getName());
130         if(storedKey == null) {
131             setKey(key);
132             return key;
133         }
134         return storedKey;
135     }
136     
137     private Key getKey(String JavaDoc name) {
138         return getKeyMap().get(name);
139     }
140     
141     protected void setKey(Key key) {
142         getKeyMap().put(key.getName(), key);
143     }
144
145     /**
146      * Parses the instances file.
147      *
148      */

149     private void parse() throws IOException JavaDoc {
150         InputStream JavaDoc is = null;
151         try {
152             is = FileUtils.createInputStream(file);
153             int keyIdx = 0;
154             while(!checkEOF(is)) {
155                int keyLength = readEntryLength(is); // key length
156
byte[] keyName = new byte[keyLength];
157                is.read(keyName);
158                is.read(); // skip '\n'
159
int valueLength = readEntryLength(is); // value length
160
byte[] value = new byte[valueLength];
161                is.read(value);
162                Key key = new Key(keyIdx, new String JavaDoc(keyName, "UTF8"));
163                setKey(key);
164                getMap().put(key, value);
165                is.read(); // skip '\n'
166
keyIdx++;
167             }
168         } catch (EOFException JavaDoc eofe) {
169             if(getMap().size() > 0) {
170                 // there are already some key-value pairs ->
171
// something in the file structure seems to be wrong
172
throw new EOFException JavaDoc(file.getAbsolutePath());
173             }
174             // otherwise skip the exception, could be just an empty file
175
} finally {
176             try {
177                 if (is != null) {
178                     is.close();
179                 }
180             } catch (IOException JavaDoc e) {
181                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e); // should not happen
182
}
183         }
184     }
185     
186     private boolean checkEOF(InputStream JavaDoc is) throws IOException JavaDoc {
187         is.mark(3);
188         byte[] end = new byte[3];
189         is.read(end);
190         is.reset();
191         if(end[0] == -1 || end[1] == -1 || end[2] == -1) {
192             throw new EOFException JavaDoc();
193         }
194         return end[0] == 'E' && end[1] == 'N' && end[2] == 'D';
195     }
196     
197     private int readEntryLength(InputStream JavaDoc is) throws IOException JavaDoc {
198         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
199         byte b = (byte) is.read();
200         while ( b != '\n') {
201             if(b == -1) {
202                 throw new EOFException JavaDoc();
203             }
204             baos.write(b);
205             b = (byte) is.read();
206         }
207         String JavaDoc line = baos.toString();
208         return Integer.decode(line.substring(2)).intValue();
209     }
210
211     public void store() throws IOException JavaDoc {
212         store(file);
213     }
214     
215     public void store(File JavaDoc file) throws IOException JavaDoc {
216         OutputStream JavaDoc os = null;
217         try {
218             File JavaDoc parent = file.getParentFile();
219             if(parent!=null && !parent.exists()) {
220                 parent.mkdirs();
221             }
222             os = FileUtils.createOutputStream(file);
223             for (Iterator JavaDoc it = getMap().keySet().iterator(); it.hasNext();) {
224                 Key key = (Key) it.next();
225                 byte[] value = (byte[]) map.get(key);
226                 
227                 StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
228                 sb.append("K "); // NOI18N
229
sb.append(key.getName().length());
230                 sb.append("\n"); // NOI18N
231
sb.append(key.getName());
232                 sb.append("\n"); // NOI18N
233
sb.append("V "); // NOI18N
234
sb.append(value.length);
235                 sb.append("\n"); // NOI18N
236
os.write(sb.toString().getBytes("UTF8"));
237                 os.write(value);
238                 os.write("\n".getBytes()); // NOI18N
239
}
240             os.write("END\n".getBytes()); // NOI18N
241
os.flush();
242             
243         } finally {
244             if(os != null) {
245                 try {
246                     os.close();
247                 } catch (IOException JavaDoc ex) {
248                     ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
249                 }
250             }
251         }
252     }
253     
254     protected File JavaDoc getFile() {
255         return file;
256     }
257
258     void setValue(Key key, String JavaDoc value) {
259         setValue(key, value.getBytes());
260     }
261
262     /**
263      * Represents a key
264      */

265     protected static class Key implements Comparable JavaDoc {
266         /** the key index */
267         private final int idx;
268         /** the keys name */
269         private final String JavaDoc name;
270         /** creates a new instance */
271         protected Key(int idx, String JavaDoc name) {
272             this.name = name;
273             this.idx = idx;
274         }
275         public int getIndex() {
276             return idx;
277         }
278         public String JavaDoc getName() {
279             return name;
280         }
281         public boolean equals(Object JavaDoc obj) {
282             if( !(obj instanceof Key) ) {
283                 return false;
284             }
285             Key key = (Key) obj;
286             return key.getIndex() == getIndex() && key.getName().equals(getName());
287         }
288         public int hashCode() {
289             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
290             sb.append(getName());
291             sb.append(getIndex());
292             return sb.toString().hashCode();
293         }
294         public int compareTo(Object JavaDoc obj) {
295             if( !(obj instanceof Key) ) {
296                 return 0;
297             }
298             Key key = (Key) obj;
299             if (key.getIndex() < getIndex()) {
300                 return 1;
301             } else if (key.getIndex() > getIndex()) {
302                 return -1;
303             }
304             return 0;
305         }
306         public String JavaDoc toString() {
307             return name;
308         }
309     }
310    
311 }
312
Popular Tags