KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > autoupdate > XMLAutoupdateType


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
20 package org.netbeans.modules.autoupdate;
21
22 import java.io.UnsupportedEncodingException JavaDoc;
23 import java.net.MalformedURLException JavaDoc;
24 import java.net.URL JavaDoc;
25 import java.net.URLEncoder JavaDoc;
26 import java.text.MessageFormat JavaDoc;
27 import java.text.ParseException JavaDoc;
28 import java.util.StringTokenizer JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.InputStream JavaDoc;
31 import java.io.InputStreamReader JavaDoc;
32 import java.io.Reader JavaDoc;
33 import java.net.URLConnection JavaDoc;
34 import java.text.DateFormat JavaDoc;
35 import java.text.SimpleDateFormat JavaDoc;
36 import java.util.Collections JavaDoc;
37 import java.util.Date JavaDoc;
38 import java.util.MissingResourceException JavaDoc;
39 import java.util.ResourceBundle JavaDoc;
40 import java.util.concurrent.Callable JavaDoc;
41 import java.util.logging.Level JavaDoc;
42 import java.util.logging.LogRecord JavaDoc;
43 import java.util.logging.Logger JavaDoc;
44 import org.openide.util.NbBundle;
45 import org.openide.filesystems.FileObject;
46 import org.openide.filesystems.FileStateInvalidException;
47 import org.openide.filesystems.FileSystem;
48 import org.openide.util.Exceptions;
49 import org.openide.util.HelpCtx;
50
51 /** Options autoupdate module
52 *
53 * @author Ales Kemr
54 */

55 public class XMLAutoupdateType extends AutoupdateType {
56
57     final static String JavaDoc PROP_URL_SPEC = "urlSpec"; // NOI18N
58
final static String JavaDoc PROP_URL = "URL"; // NOI18N
59

60     /** Holds value of property URL. */
61     private String JavaDoc urlSpec;
62     private URL JavaDoc url;
63     
64     /** Holds value of property defaultURL. */
65     private String JavaDoc defaultURL;
66     
67     /** System property holding autoupdate version */
68     private static final String JavaDoc UPDATE_VERSION_PROP = "netbeans.autoupdate.version"; // NOI18N
69

70     /** System property holding ide identity */
71     private static final String JavaDoc IDE_HASH_CODE = "netbeans.hash.code"; // NOI18N
72

73     /** Current internal version of autoupdate */
74     public static final String JavaDoc UPDATE_VERSION = "1.18"; // NOI18N
75

76     /** Important system properies */
77     private static final String JavaDoc SYSPROP_COUNTRY = "netbeans.autoupdate.country"; // NOI18N
78
private static final String JavaDoc SYSPROP_LANGUAGE = "netbeans.autoupdate.language"; // NOI18N
79
private static final String JavaDoc SYSPROP_VARIANT = "netbeans.autoupdate.variant"; // NOI18N
80
private static final String JavaDoc TIME_STAMP_ATTRIBUTE_NAME = "timestamp"; // NOI18N
81
private static final String JavaDoc TIME_STAMP_FORMAT = "ss/mm/hh/dd/MM/yyyy"; // NOI18N
82

83     private static final Logger JavaDoc err = Logger.getLogger("org.netbeans.modules.autoupdate"); // NOI18N
84

85     /** serialVersionUID */
86     static final long serialVersionUID = 362844553432169452L;
87     
88     /** Holds value of property displayName */
89     private String JavaDoc displayName = null;
90     
91     private FileObject typeFileObject = null;
92     
93     /** Holds value of property url_key. */
94     private String JavaDoc url_key;
95     
96     /** Holds value of property localizing bundle in update center declaration. */
97     private String JavaDoc localizingBundleName;
98
99     private boolean valid = true;
100     
101     /** Creates new XMLAutoupdateType */
102     public XMLAutoupdateType() {
103         urlSpec = getDefaultURL ();
104     }
105     
106     public XMLAutoupdateType(URL JavaDoc url) {
107         this.urlSpec = url.toExternalForm ();
108     }
109     
110     public XMLAutoupdateType(URL JavaDoc url, String JavaDoc displayName, String JavaDoc url_key, Boolean JavaDoc enabled) {
111         this( url, displayName, null, url_key, enabled );
112     }
113     
114     public XMLAutoupdateType(URL JavaDoc url, String JavaDoc displayName, FileObject fo, String JavaDoc url_key, Boolean JavaDoc enabled) {
115         this (url, displayName, fo, url_key, enabled, null);
116     }
117     
118     public XMLAutoupdateType(URL JavaDoc url, String JavaDoc displayName, FileObject fo, String JavaDoc url_key, Boolean JavaDoc enabled, String JavaDoc localizingBundleName) {
119         this.typeFileObject = fo;
120         this.urlSpec = url.toExternalForm ();
121         this.displayName = displayName;
122         this.url_key = url_key;
123         this.localizingBundleName = localizingBundleName;
124
125         if ( enabled != null )
126             setEnabled( enabled.booleanValue() );
127     }
128     
129     public static XMLAutoupdateType createXMLAutoupdateType(FileObject fo) throws IOException JavaDoc {
130         URL JavaDoc url;
131         String JavaDoc sKey = (String JavaDoc)fo.getAttribute("url_key"); // NOI18N
132
String JavaDoc remoteBundleName = (String JavaDoc)fo.getAttribute ("SystemFileSystem.localizingBundle"); // NOI18N
133
ResourceBundle JavaDoc bundle = getBundleFromName (remoteBundleName);
134         if (sKey != null) {
135             String JavaDoc localizedValue;
136             try {
137                 localizedValue = bundle.getString (sKey);
138             } catch (MissingResourceException JavaDoc mre) {
139                 localizedValue = "http://"; // XXX What set if the key is not in any bundle
140
}
141             //System.out.println (remoteBundleName + " for <" + sKey + "> returns " + localizedValue);
142
url = new URL JavaDoc (localizedValue);
143         } else {
144             Object JavaDoc o = fo.getAttribute("url"); // NOI18N
145
if (o instanceof String JavaDoc) {
146                 url = new URL JavaDoc((String JavaDoc)o);
147             } else {
148                 url = (URL JavaDoc)o;
149             }
150         }
151         
152         Boolean JavaDoc en = (Boolean JavaDoc)fo.getAttribute("enabled");
153         
154         return new XMLAutoupdateType( url, null, fo, sKey, en, remoteBundleName );
155     }
156     
157     /** @return human presentable name */
158     public String JavaDoc displayName() {
159         if (displayName == null) {
160             if (typeFileObject != null) {
161                 try {
162                     FileSystem fs = typeFileObject.getFileSystem();
163                     FileSystem.Status s = fs.getStatus();
164                     String JavaDoc x = s.annotateName("", Collections.singleton(typeFileObject)); // NOI18N
165
if (!x.equals("")) { // NOI18N
166
displayName = x;
167                     }
168                 } catch (FileStateInvalidException e) {
169                     // OK, never mind.
170
}
171             }
172             if (displayName == null) {
173                 displayName = NbBundle.getBundle( Settings.class).getString("CTL_XMLAutoupdateType_Name");
174             }
175         }
176         return displayName;
177     }
178     
179     /** Getter for property URL_SPEC.
180      * @return Value of property URL_SPEC..
181      * @since 2.18
182     */

183     public String JavaDoc getUrlSpec () {
184         return urlSpec;
185     }
186     
187     /** Setter for property URL_SPEC.
188      * @param String New value of property URL_SPEC.
189      * @since 2.18
190     */

191     public void setUrlSpec (String JavaDoc spec) {
192         try {
193             //validate input
194
new URL JavaDoc (spec);
195         } catch (MalformedURLException JavaDoc ex) {
196             class UserIllegalException extends IllegalArgumentException JavaDoc implements Callable JavaDoc/*<LogRecord[]>*/ {
197                 public UserIllegalException(String JavaDoc s) {
198                     super(s);
199                 }
200                 public Object JavaDoc call() throws Exception JavaDoc {
201                     LogRecord JavaDoc r = new LogRecord JavaDoc(OwnLevel.USER, getMessage());
202                     return new LogRecord JavaDoc[] { r };
203                 }
204             }
205             
206             IllegalArgumentException JavaDoc iae = new UserIllegalException(ex.getMessage());
207             String JavaDoc msg = MessageFormat.format(
208                 NbBundle.getMessage(XMLAutoupdateType.class, "FMT_EXC_BAD_URL"), //NOI18N
209
new Object JavaDoc [] {spec}
210             );
211             Exceptions.attachLocalizedMessage(iae, msg);
212             throw iae;
213         }
214         
215         String JavaDoc old = this.urlSpec;
216         this.urlSpec = spec;
217         firePropertyChange (PROP_URL_SPEC, old, urlSpec);
218     }
219     
220     /** Getter for property URL.
221      * @return Value of property URL.
222      * @deprecated Use String getUrlSpec () instead. Since 2.18
223     */

224     public URL JavaDoc getURL() {
225         URL JavaDoc url = null;
226         try {
227             url = new URL JavaDoc (this.getUrlSpec());
228         } catch (MalformedURLException JavaDoc ex) {
229             assert false : ex;
230         }
231         return url;
232     }
233     
234     /** Setter for property URL.
235      * @param URL New value of property URL.
236      * @deprecated Use setUrlSpec (String urlSpec) instead. Since 2.18
237     */

238     public void setURL(URL JavaDoc url) {
239         if (url != null) {
240             this.setUrlSpec (url.toExternalForm ());
241         } else {
242             this.setUrlSpec (null);
243         }
244     }
245     
246     public HelpCtx getHelpCtx () {
247         return new HelpCtx( org.netbeans.modules.autoupdate.XMLAutoupdateType.class );
248     }
249     
250     public Updates connectForUpdates() {
251         URL JavaDoc url = null;
252         try {
253             url = new URL JavaDoc (getUrlSpec());
254         } catch (MalformedURLException JavaDoc ex) {
255             assert false : ex;
256         }
257         return new XMLUpdates( modifyURL (url));
258     }
259     
260     /** Gets the update URL */
261     protected URL JavaDoc modifyURL (URL JavaDoc original) {
262         
263         URL JavaDoc updateURL = null;
264         
265         if ( System.getProperty( UPDATE_VERSION_PROP ) == null ) {
266             System.setProperty( UPDATE_VERSION_PROP, UPDATE_VERSION );
267         }
268         
269         if (System.getProperty (IDE_HASH_CODE) == null) {
270             String JavaDoc id = ""; // NOI18N
271
try {
272                 id = Settings.getShared ().getIdeIdentity ();
273             } catch (NullPointerException JavaDoc npe) {
274                 // can ignore it, property used only for logging purposes
275
Logger.getAnonymousLogger().warning("Property PROP_IDE_IDENTITY hasn't been initialized yet."); // NOI18N
276
}
277             String JavaDoc prefix = NbBundle.getBundle (XMLAutoupdateType.class).getString ("URL_Prefix_Hash_Code"); // NOI18N
278
System.setProperty (IDE_HASH_CODE, "".equals (id) ? prefix + "0" : prefix + id); // NOI18N
279
}
280         
281         try {
282             updateURL = new URL JavaDoc( encode( replace( original.toString() ) ) );
283         }
284         catch (java.net.MalformedURLException JavaDoc e) {
285             Exceptions.printStackTrace(e);
286         }
287
288         return updateURL;
289         
290     }
291     
292     /** Utility method for replacing {$xxx} with value of system property xxx,
293      * or with another special value - see getReplacement
294     */

295
296     protected String JavaDoc replace( String JavaDoc string ) {
297
298         // First of all set our system properties
299
setSystemProperties();
300
301         if ( string == null )
302             return null;
303
304         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
305
306         int index, prevIndex;
307         index = prevIndex = 0;
308         while( ( index = string.indexOf( "{", index )) != -1 && index < string.length() - 1) { // NOI18N
309

310             if ( string.charAt( index + 1 ) == '{' || string.charAt( index + 1 ) != '$' ) {
311                 ++index;
312                 continue;
313             }
314
315             sb.append( string.substring( prevIndex, index ) );
316             int endBracketIndex = string.indexOf( "}", index ); // NOI18N
317
if ( endBracketIndex != -1 ) {
318                 String JavaDoc whatToReplace = string.substring( index + 2, endBracketIndex );
319                 sb.append( getReplacement(whatToReplace) );
320             }
321             prevIndex = endBracketIndex == -1 ? index + 2 : endBracketIndex + 1;
322             ++index;
323         }
324
325         if ( prevIndex < string.length() - 1 )
326             sb.append( string.substring( prevIndex ) );
327
328         return sb.toString();
329     }
330
331     boolean isValid () {
332         return valid;
333     }
334
335     /** What to replace by what in URL string
336     */

337     protected String JavaDoc getReplacement(String JavaDoc whatToReplace) {
338         return System.getProperty( whatToReplace, "" );
339     }
340
341     protected String JavaDoc encode(String JavaDoc stringURL) {
342     String JavaDoc rval = stringURL;
343             int q = stringURL.indexOf('?');
344             if(q > 0) {
345         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(stringURL.substring(0, q+1));
346         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(stringURL.substring(q + 1), "&");
347         while(st.hasMoreTokens()) {
348                     String JavaDoc a = st.nextToken();
349                     try {
350                         int ei = a.indexOf('=');
351                         if(ei < 0) {
352                             buf.append(URLEncoder.encode(a, "UTF-8"));
353                         } else {
354                             buf.append(URLEncoder.encode(a.substring(0, ei), "UTF-8"));
355                             buf.append('=');
356                             String JavaDoc tna = a.substring(ei+1);
357                             int tni = tna.indexOf("%");
358                             if( tni < 0) {
359                                 buf.append(URLEncoder.encode(tna, "UTF-8"));
360                             } else {
361                                 buf.append(URLEncoder.encode(tna.substring(0, tni), "UTF-8"));
362                                 buf.append('%');
363                                 buf.append(URLEncoder.encode(tna.substring(tni+1), "UTF-8"));
364                             }
365                         }
366                     } catch (UnsupportedEncodingException JavaDoc ex) {
367                         err.log (Level.INFO, ex.getMessage (), ex);
368                     }
369                     if (st.hasMoreTokens())
370                         buf.append('&');
371                 }
372                 rval = buf.toString();
373             }
374
375     return rval;
376     }
377     
378     /** Reads time stamp from AutoupdateType's URL and then compares with stored the last time stamp.
379      *
380      * @return Boolean.TRUE if this AutoupdateType has new content, Boolean.FALSE if doesn't have and null if cannot resolve it.
381      */

382     Boolean JavaDoc hasNewContent () {
383         InputStream JavaDoc is = null;
384         Date JavaDoc timeStamp = null;
385         try {
386             URL JavaDoc url = modifyURL (new URL JavaDoc (getUrlSpec ()));
387             err.log (Level.FINER, "Found Update Center " + getName () + "[" + url + "]");
388             URLConnection JavaDoc conn = url.openConnection ();
389             is = conn.getInputStream ();
390             Reader JavaDoc r = new InputStreamReader JavaDoc (is);
391             StringBuffer JavaDoc sb = new StringBuffer JavaDoc (1024);
392
393             int c;
394             while ((c = is.read ()) != -1 && sb.length () < 1024) {
395                 sb.append ((char) c);
396             }
397             err.log (Level.FINER, "Successfully checked " + url); // NOI18N
398

399             String JavaDoc content = sb.toString ();
400             String JavaDoc time = null;
401             int pos;
402             if ((pos = content.indexOf (TIME_STAMP_ATTRIBUTE_NAME)) != -1) {
403                 content = content.substring (pos + TIME_STAMP_ATTRIBUTE_NAME.length () + 1 + 1);
404                 if ((pos = content.indexOf ('>')) != -1) {
405                     time = content.substring (0, pos - 1);
406                 }
407             }
408
409             DateFormat JavaDoc format = new SimpleDateFormat JavaDoc (TIME_STAMP_FORMAT);
410             timeStamp = format.parse (time);
411             err.log (Level.FINER, "Successfully read time " + timeStamp); // NOI18N
412

413             err.log (Level.FINER, "Last Time Stamp on " + getName () + " is " + getLastTimeStamp ());
414
415
416         } catch (MalformedURLException JavaDoc ex) {
417             err.log (Level.FINE, null, ex);
418         } catch (IOException JavaDoc ioe) {
419             err.log (Level.FINE, null, ioe);
420         } catch (ParseException JavaDoc ex) {
421             err.log (Level.FINE, null, ex);
422         } finally {
423             if (is != null) {
424                 try {
425                     is.close ();
426                 } catch (IOException JavaDoc ex) {
427                     err.log (Level.FINE, null, ex);
428                 }
429             }
430         }
431
432         if (getLastTimeStamp () == null) {
433             return Boolean.TRUE;
434         }
435
436         return timeStamp == null ? null : (timeStamp.after (getLastTimeStamp ()) ? Boolean.TRUE : Boolean.FALSE);
437
438     }
439
440     
441     private static ResourceBundle JavaDoc getOldLocalizingBundle () {
442         return NbBundle.getBundle (XMLAutoupdateType.class);
443     }
444     
445     private static ResourceBundle JavaDoc getBundleFromName (String JavaDoc name) throws MissingResourceException JavaDoc {
446         ResourceBundle JavaDoc bundle = null;
447         if (name == null) {
448             bundle = getOldLocalizingBundle ();
449         } else {
450             bundle = NbBundle.getBundle (name);
451         }
452         return bundle;
453     }
454     
455     private static void setSystemProperties() {
456             
457         if ( System.getProperty( SYSPROP_COUNTRY, null ) == null ) {
458             System.setProperty( SYSPROP_COUNTRY, java.util.Locale.getDefault().getCountry() );
459         }
460         if ( System.getProperty( SYSPROP_LANGUAGE, null ) == null ) {
461             System.setProperty( SYSPROP_LANGUAGE, java.util.Locale.getDefault().getLanguage() );
462         }
463         if ( System.getProperty( SYSPROP_VARIANT, null ) == null ) {
464             System.setProperty( SYSPROP_VARIANT, java.util.Locale.getDefault().getVariant() );
465         }
466     }
467     
468     protected String JavaDoc getDefaultURL() {
469         if ( defaultURL == null ) {
470             ResourceBundle JavaDoc remoteBundle = null;
471             try {
472                 remoteBundle = getBundleFromName (localizingBundleName);
473                 defaultURL = url_key != null ? remoteBundle.getString( url_key ) : remoteBundle.getString( "URL_Default_N" );
474             } catch (MissingResourceException JavaDoc mre) {
475                 // non-existent localizingBundleName
476
// the module which did this setting declaration, was removed
477
// return null and ignore this setting
478
this.valid = false;
479                 return null;
480             }
481             //System.out.println(localizingBundleName + " for <" + url_key + "> returns " + defaultURL);
482
}
483         return defaultURL;
484     }
485         
486     private void writeObject(java.io.ObjectOutputStream JavaDoc out) throws java.io.IOException JavaDoc {
487         if (urlSpec.equals (getDefaultURL ())) {
488             out.writeObject( null );
489         } else {
490             out.writeObject( urlSpec );
491         }
492         out.writeObject( displayName );
493         out.writeObject( url_key );
494         out.writeObject( localizingBundleName );
495     }
496
497     private void readObject(java.io.ObjectInputStream JavaDoc in) throws java.io.IOException JavaDoc,
498             ClassNotFoundException JavaDoc {
499         try {
500             // initialy is valid
501
valid = true;
502
503             Object JavaDoc urlObject = in.readObject();
504             if (urlObject != null) {
505                 if (urlObject instanceof URL JavaDoc) {
506                     urlSpec = ((URL JavaDoc) urlObject).toExternalForm ();
507                 } else {
508                     assert urlObject instanceof String JavaDoc;
509                     urlSpec = (String JavaDoc) urlObject;
510                 }
511             }
512             
513             String JavaDoc display = (String JavaDoc)in.readObject();
514             if (display != null)
515                 displayName = display;
516
517             String JavaDoc key = (String JavaDoc)in.readObject();
518             if (key != null)
519                 url_key = key;
520             
521             String JavaDoc remoteBundleName = (String JavaDoc)in.readObject ();
522             if (remoteBundleName != null) {
523                 localizingBundleName = remoteBundleName;
524             }
525
526         } catch (java.io.OptionalDataException JavaDoc ode) {
527             if ( ode.eof ) {
528                 // new version
529
setEnabled( true );
530             }
531             else
532                 throw ode;
533         }
534         
535         if (urlSpec == null) {
536             this.urlSpec = getDefaultURL ();
537         }
538
539         if (! isValid ()) {
540             setEnabled (false);
541             displayName = NbBundle.getMessage (XMLAutoupdateType.class, "XMLAutoupdateType_InvalidSetting", displayName); // NOI18N
542
}
543
544     }
545
546     private static final class OwnLevel extends Level JavaDoc {
547         public static final Level JavaDoc USER = new OwnLevel("USER", 1973); // NOI18N
548

549         private OwnLevel(String JavaDoc s, int i) {
550             super(s, i);
551         }
552     } // end of UserLevel
553

554 }
555
Popular Tags