]> sjero.net Git - linphone/blob - p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/NullConfigurator.java
bc3f0a96088fbba9b344e7b643d9b4d103b607b0
[linphone] / p2pproxy / dependencies-src / jxse-src-2.5 / impl / src / net / jxta / impl / peergroup / NullConfigurator.java
1 /*
2  * Copyright (c) 2001-2007 Sun Microsystems, Inc.  All rights reserved.
3  *  
4  *  The Sun Project JXTA(TM) Software License
5  *  
6  *  Redistribution and use in source and binary forms, with or without 
7  *  modification, are permitted provided that the following conditions are met:
8  *  
9  *  1. Redistributions of source code must retain the above copyright notice,
10  *     this list of conditions and the following disclaimer.
11  *  
12  *  2. Redistributions in binary form must reproduce the above copyright notice, 
13  *     this list of conditions and the following disclaimer in the documentation 
14  *     and/or other materials provided with the distribution.
15  *  
16  *  3. The end-user documentation included with the redistribution, if any, must 
17  *     include the following acknowledgment: "This product includes software 
18  *     developed by Sun Microsystems, Inc. for JXTA(TM) technology." 
19  *     Alternately, this acknowledgment may appear in the software itself, if 
20  *     and wherever such third-party acknowledgments normally appear.
21  *  
22  *  4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must 
23  *     not be used to endorse or promote products derived from this software 
24  *     without prior written permission. For written permission, please contact 
25  *     Project JXTA at http://www.jxta.org.
26  *  
27  *  5. Products derived from this software may not be called "JXTA", nor may 
28  *     "JXTA" appear in their name, without prior written permission of Sun.
29  *  
30  *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
31  *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
32  *  FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN 
33  *  MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
34  *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
35  *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
36  *  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
37  *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
38  *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
39  *  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  *  
41  *  JXTA is a registered trademark of Sun Microsystems, Inc. in the United 
42  *  States and other countries.
43  *  
44  *  Please see the license information page at :
45  *  <http://www.jxta.org/project/www/license.html> for instructions on use of 
46  *  the license in source files.
47  *  
48  *  ====================================================================
49  *  
50  *  This software consists of voluntary contributions made by many individuals 
51  *  on behalf of Project JXTA. For more information on Project JXTA, please see 
52  *  http://www.jxta.org.
53  *  
54  *  This license is based on the BSD license adopted by the Apache Foundation. 
55  */
56 package net.jxta.impl.peergroup;
57
58 import net.jxta.document.AdvertisementFactory;
59 import net.jxta.document.MimeMediaType;
60 import net.jxta.document.StructuredDocumentFactory;
61 import net.jxta.document.XMLDocument;
62 import net.jxta.exception.ConfiguratorException;
63 import net.jxta.impl.protocol.PlatformConfig;
64 import net.jxta.logging.Logging;
65 import net.jxta.protocol.ConfigParams;
66
67 import java.io.*;
68 import java.net.URI;
69 import java.util.logging.Level;
70 import java.util.logging.Logger;
71
72 /**
73  * A minimal Platform Configurator. This implementation can load a
74  * configuration from an existing PlatformConfig file and also save a
75  * configuration to the PlatformConfig file.
76  * <p/>
77  * This configurator provides no explict validation of the PlatformConfig
78  * as it is read from the file (Some is done by the PlatformConfig class) and
79  * provides no mechanism for reconfiguration. The NullConfigurator provides a
80  * useful base implementation for extending your own Configurator and also
81  * provides the minimal implementation needed for applications which perform
82  * their own configuration.
83  */
84 public class NullConfigurator implements PlatformConfigurator {
85
86     /**
87      * logger
88      */
89     private final static transient Logger LOG = Logger.getLogger(NullConfigurator.class.getName());
90
91     /**
92      * The location in which the configuration files will reside.
93      */
94     protected final URI jxtaHome;
95
96     /**
97      * The file in which contains the platform configurtation.
98      */
99     protected final URI configFile;
100
101     /**
102      * The platform config
103      */
104     protected PlatformConfig advertisement = null;
105
106     /**
107      * Constructor for the NullConfigurator
108      *
109      * @param homeRoot The location in which the configuration files will reside.
110      * @throws ConfiguratorException If there is a problem accessing the configuration information.
111      */
112     public NullConfigurator(URI homeRoot) throws ConfiguratorException {
113         if (!homeRoot.isAbsolute()) {
114             throw new IllegalArgumentException("homeRoot must be an absoluteURI");
115         }
116
117         jxtaHome = homeRoot;
118
119         if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) {
120             LOG.config("JXTA_HOME = " + jxtaHome.toASCIIString());
121         }
122
123         if ("file".equalsIgnoreCase(jxtaHome.getScheme())) {
124             File jxtaHomeDir = new File(jxtaHome);
125
126             if (jxtaHomeDir.exists() && !jxtaHomeDir.isDirectory()) {
127                 throw new IllegalArgumentException("'" + jxtaHomeDir + "' is not a directory.");
128             }
129
130             if (!jxtaHomeDir.exists()) {
131                 if (!jxtaHomeDir.mkdirs()) {
132                     throw new IllegalStateException("Could not create '" + jxtaHomeDir + "'.");
133                 }
134             }
135
136             configFile = new File(jxtaHomeDir, "PlatformConfig").toURI();
137         } else {
138             configFile = jxtaHome.resolve("PlatformConfig");
139         }
140     }
141
142     /**
143      * @inheritDoc
144      */
145     public PlatformConfig getPlatformConfig() throws ConfiguratorException {
146         advertisement = (PlatformConfig) load();
147
148         return advertisement;
149     }
150
151     /**
152      * @inheritDoc
153      */
154     public final void setPlatformConfig(PlatformConfig config) {
155         advertisement = config;
156     }
157
158     /**
159      * @inheritDoc
160      */
161     public ConfigParams getConfigParams() throws ConfiguratorException {
162         return getPlatformConfig();
163     }
164
165     /**
166      * @inheritDoc
167      */
168     public void setConfigParams(ConfigParams cp) {
169         setPlatformConfig((PlatformConfig) cp);
170     }
171
172     /**
173      * @inheritDoc
174      */
175     public void setReconfigure(boolean reconfigure) {// This implementation doesn't do configuration so ignores this operation.
176     }
177
178     /**
179      * @inheritDoc
180      */
181     public boolean isReconfigure() {
182         return false;
183     }
184
185     /**
186      * {@inheritDoc}
187      */
188     public ConfigParams load() throws ConfiguratorException {
189         return load(configFile);
190     }
191
192     /**
193      * Retrieves the persisted parameters associated with this configuration
194      * from the standard location.
195      *
196      * @param loadFile The location from which the configuration data should be
197      *                 loaded.
198      * @return The configuration parameters.
199      * @throws ConfiguratorException If there was a failure in retrieving the
200      *                               persisted parameters. This is normally a chained exception to the
201      *                               underlying cause.
202      * @deprecated Loading of existing configuration is best accomplished by use
203      *             of specific constructors of the implementing configurator. This method
204      *             complicates the state management of configuration parameters and may have
205      *             unpredictable results depending upon the constructor and configuration
206      *             set methods used prior to it's execution.
207      */
208     @Deprecated
209     protected PlatformConfig load(URI loadFile) throws ConfiguratorException {
210         if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) {
211             LOG.fine("Reading Platform Config from : " + loadFile);
212         }
213
214         InputStream advStream = null;
215
216         try {
217             advStream = loadFile.toURL().openStream();
218
219             XMLDocument xmlDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, advStream);
220             PlatformConfig result = (PlatformConfig) AdvertisementFactory.newAdvertisement(xmlDoc);
221
222             if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) {
223                 LOG.fine("Recovered Platform Config from : " + loadFile);
224             }
225
226             return result;
227         } catch (FileNotFoundException e) {
228             if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) {
229                 LOG.warning("Platform Config not found : " + loadFile);
230             }
231
232             return null;
233         } catch (Exception e) {
234             if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) {
235                 LOG.log(Level.WARNING, "Failed to Recover \'" + loadFile + "\' due to : ", e);
236             }
237
238             throw new ConfiguratorException("Failed to recover PlatformConfig", e);
239         } finally {
240             try {
241                 if (advStream != null) {
242                     advStream.close();
243                 }
244                 advStream = null;
245             } catch (Exception ignored) {// ignored
246             }
247         }
248     }
249
250     /**
251      * {@inheritDoc}
252      */
253     public boolean save() throws ConfiguratorException {
254         return save(configFile);
255     }
256
257     /**
258      * Persist the parameters associated with this configuration to the
259      * specified location.
260      *
261      * @param saveFile The location to which the configuration should be saved.
262      * @return <code>true</code> if the configuration was successfully saved
263      *         otherwise <code>false</code>. If the parameters are not persisted then
264      *         <code>false/code> is returned.
265      * @throws ConfiguratorException If there was a failure in persisting the
266      *                               parameters. This is normally a chained exception to the underlying
267      *                               cause.
268      */
269     protected boolean save(URI saveFile) throws ConfiguratorException {
270
271         // Save the adv as input for future reconfiguration
272         OutputStream out = null;
273
274         try {
275             XMLDocument aDoc = (XMLDocument) advertisement.getDocument(MimeMediaType.XMLUTF8);
276
277             if ("file".equalsIgnoreCase(saveFile.getScheme())) {
278                 out = new FileOutputStream(new File(saveFile));
279             } else {
280                 out = saveFile.toURL().openConnection().getOutputStream();
281             }
282
283             OutputStreamWriter os = new OutputStreamWriter(out, "UTF-8");
284
285             aDoc.sendToWriter(os);
286             os.flush();
287         } catch (IOException e) {
288             if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) {
289                 LOG.log(Level.WARNING, "Could not save to : " + saveFile, e);
290             }
291
292             throw new ConfiguratorException("Could not save to : " + saveFile, e);
293         } finally {
294             try {
295                 if (null != out) {
296                     out.close();
297                 }
298             } catch (Exception ignored) {// ignored
299             }
300             out = null;
301         }
302         return true;
303     }
304 }