KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > core > Services


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.core;
21
22 import java.io.IOException JavaDoc;
23 import java.io.ObjectInputStream JavaDoc;
24 import java.io.ObjectOutputStream JavaDoc;
25 import java.util.ArrayList JavaDoc;
26 import java.util.Collection JavaDoc;
27 import java.util.Collections JavaDoc;
28 import java.util.Enumeration JavaDoc;
29 import java.util.HashMap JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.LinkedList JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.Map.Entry;
35 import java.util.logging.Level JavaDoc;
36 import java.util.logging.Logger JavaDoc;
37 import org.openide.ServiceType;
38 import org.openide.cookies.InstanceCookie;
39 import org.openide.filesystems.FileObject;
40 import org.openide.loaders.DataFolder;
41 import org.openide.loaders.DataObject;
42 import org.openide.loaders.DataObjectNotFoundException;
43 import org.openide.loaders.InstanceDataObject;
44 import org.openide.util.Lookup;
45 import org.openide.util.LookupEvent;
46 import org.openide.util.LookupListener;
47 import org.openide.util.io.NbMarshalledObject;
48
49 /** Works with all service types.
50 *
51 * @author Jaroslav Tulach
52 * @deprecated Obsoleted by lookup and new settings system.
53 */

54 @SuppressWarnings JavaDoc({"deprecation","unchecked"})
55 public final class Services extends ServiceType.Registry implements LookupListener {
56     /** serial */
57     static final long serialVersionUID =-7558069607307508327L;
58     
59     /** Result containing all current services. */
60     private Lookup.Result<ServiceType> allTypes;
61     
62     /** Mapping between service name and given ServiceType instance. */
63     private Map JavaDoc<String JavaDoc, ServiceType> name2Service;
64     
65     /** Default instance */
66     public static Services getDefault () {
67         return (Services)Lookup.getDefault ().lookup (org.openide.ServiceType.Registry.class);
68     }
69     
70     public Services() {
71         name2Service = new HashMap JavaDoc<String JavaDoc, ServiceType>();
72     }
73     
74     public ServiceType find(Class JavaDoc clazz) {
75         return (ServiceType)Lookup.getDefault().lookup(clazz);
76     }
77     
78     /** Override to specially look up no-op services. */
79     public ServiceType find (String JavaDoc name) {
80         Map JavaDoc<String JavaDoc, ServiceType> lookupMap = name2Service;
81         ServiceType ret;
82         synchronized (lookupMap) {
83             ret = lookupMap.get(name);
84         }
85         
86         if (ret == null) {
87             ret = super.find(name);
88             synchronized (lookupMap) {
89                 lookupMap.put(name, ret);
90             }
91         }
92         
93         return ret;
94     }
95     
96     /** Result containing all current services. */
97     private Lookup.Result<ServiceType> getTypesResult() {
98         boolean init = false;
99         synchronized (this) {
100             if (allTypes == null) {
101                 allTypes = Lookup.getDefault().lookupResult(ServiceType.class);
102                 allTypes.addLookupListener(this);
103                 init = true;
104             }
105         }
106         if (init) resultChanged(null);
107         return allTypes;
108     }
109     
110     /** A change in lookup occured.
111      * @param ev event describing the change
112      */

113     public void resultChanged(LookupEvent ev) {
114         synchronized (name2Service) {
115             name2Service.clear();
116         }
117     }
118     
119     /** Getter for list of all services types.
120     * @return list of ServiceType
121     */

122     public java.util.List JavaDoc<ServiceType> getServiceTypes () {
123         return new ArrayList JavaDoc<ServiceType>(getTypesResult().allInstances());
124     }
125     
126     /** Setter for list of all services types. This allows to change
127     * instaces of the objects but only of the types that are already registered
128     * to the system by manifest sections.
129     *
130     * @param arr list of ServiceTypes
131     */

132     public synchronized void setServiceTypes (java.util.List JavaDoc/*<ServiceType>*/ arr0) {
133         if (arr0 == null) {
134             throw new NullPointerException JavaDoc();
135         }
136         
137         @SuppressWarnings JavaDoc("unchecked") java.util.List JavaDoc<ServiceType> arr = ensureSingleness((java.util.List JavaDoc<ServiceType>) arr0);
138         
139         HashMap JavaDoc<ServiceType,DataObject> services = new HashMap JavaDoc<ServiceType,DataObject>(20); // <service type, DataObject>
140
searchServices(NbPlaces.getDefault().findSessionFolder("Services").getPrimaryFile(), services); // NOI18N
141

142         // storing services
143
HashMap JavaDoc<DataFolder,List JavaDoc<DataObject>> order = new HashMap JavaDoc<DataFolder,List JavaDoc<DataObject>>(10); // <parent folder, <file>>
144
Iterator JavaDoc<ServiceType> it = arr.iterator();
145         while (it.hasNext()) {
146             ServiceType st = it.next();
147             DataObject dobj = services.get(st);
148             
149             if (dobj != null) {
150                 // store existing
151
try {
152                     dobj = InstanceDataObject.create(dobj.getFolder(), dobj.getPrimaryFile().getName(), st, null);
153                 } catch (IOException JavaDoc ex) {
154                     Logger.getLogger(Services.class.getName()).log(Level.WARNING, null, ex);
155                 }
156                 services.remove(st);
157             } else {
158                 dobj = storeNewServiceType(st);
159             }
160             
161             // compute order in folders
162
if (dobj != null) {
163                 DataFolder parent = dobj.getFolder();
164                 List JavaDoc<DataObject> orderedFiles = order.get(parent);
165                 if (orderedFiles == null) {
166                     orderedFiles = new ArrayList JavaDoc<DataObject>(6);
167                     order.put(parent, orderedFiles);
168                 }
169                 orderedFiles.add(dobj);
170             }
171         }
172         
173         // storing order attribute
174
for (Entry<DataFolder,List JavaDoc<DataObject>> entry: order.entrySet()) {
175             DataObject parent = entry.getKey();
176             List JavaDoc<DataObject> orderedFiles = entry.getValue();
177             if (orderedFiles.size() < 2) continue;
178             
179             Iterator JavaDoc<DataObject> files = orderedFiles.iterator();
180             StringBuffer JavaDoc orderAttr = new StringBuffer JavaDoc(64);
181             while (files.hasNext()) {
182                 DataObject file = files.next();
183                 orderAttr.append(file.getPrimaryFile().getNameExt()).append('/');
184             }
185             orderAttr.deleteCharAt(orderAttr.length() - 1);
186             try {
187                 parent.getPrimaryFile().
188                     setAttribute("OpenIDE-Folder-Order", orderAttr.toString()); // NOI18N
189
} catch (IOException JavaDoc ex) {
190                 Logger.getLogger(Services.class.getName()).log(Level.WARNING, null, ex);
191             }
192         }
193         
194         // remove remaining services from default FS
195
for (DataObject dobj: services.values()) {
196             try {
197                 dobj.delete();
198             } catch (IOException JavaDoc ex) {
199                 Logger.getLogger(Services.class.getName()).log(Level.WARNING, null, ex);
200             }
201         }
202         
203     }
204     
205     private DataObject storeNewServiceType(ServiceType st) {
206         Class JavaDoc stype = st.getClass ();
207         // finds direct subclass of service type
208
while (stype.getSuperclass () != ServiceType.class) {
209             stype = stype.getSuperclass();
210         }
211         
212         try{
213             String JavaDoc folder = org.openide.util.Utilities.getShortClassName(stype);
214
215             DataFolder dfServices = NbPlaces.getDefault().findSessionFolder("Services"); // NOI18N
216
DataFolder dfTarget = DataFolder.create(dfServices, folder);
217             
218             return InstanceDataObject.create(dfTarget, null, st, null);
219         } catch (Exception JavaDoc ex) {
220             Logger.getLogger(Services.class.getName()).log(Level.WARNING, null, ex);
221             return null;
222         }
223     }
224     
225     /** ensure that instance of the service type will be listed just once.
226      */

227     private List JavaDoc<ServiceType> ensureSingleness(List JavaDoc<ServiceType> l) {
228         List JavaDoc<ServiceType> newList = new ArrayList JavaDoc<ServiceType>(l.size());
229         
230     for (ServiceType stype: l) {
231             if (newList.contains(stype)) {
232                 continue;
233             } else {
234                 newList.add(stype);
235             }
236         }
237         
238         return newList;
239     }
240     
241     /** search all data objects containing service type instance. */
242     private void searchServices(FileObject folder, Map JavaDoc<ServiceType,DataObject> services) {
243         FileObject[] fobjs = folder.getChildren();
244         for (int i = 0; i < fobjs.length; i++) {
245             if (!fobjs[i].isValid())
246                 continue;
247             if (fobjs[i].isFolder()) {
248                 searchServices(fobjs[i], services);
249             } else {
250                 try {
251                     DataObject dobj = DataObject.find(fobjs[i]);
252                     InstanceCookie inst = (InstanceCookie) dobj.getCookie(InstanceCookie.class);
253
254                     if (inst == null)
255                         continue;
256                     if (instanceOf(inst, ServiceType.class)) {
257                         ServiceType ser = (ServiceType) inst.instanceCreate();
258
259                         services.put(ser, dobj);
260                     }
261                 }
262                 catch (DataObjectNotFoundException ex) {
263                 }
264                 catch (Exception JavaDoc ex) {
265                     Logger.getLogger(Services.class.getName()).log(Level.WARNING, null, ex);
266                 }
267             }
268         }
269     }
270     
271     /** test if instance cookie is instance of clazz*/
272     private static boolean instanceOf(InstanceCookie inst, Class JavaDoc clazz) {
273         if (inst instanceof InstanceCookie.Of) {
274             return ((InstanceCookie.Of) inst).instanceOf(clazz);
275         } else {
276             try {
277                 return clazz.isAssignableFrom(inst.instanceClass());
278             } catch (Exception JavaDoc ex) {
279                 Logger.getLogger(Services.class.getName()).log(Level.WARNING, null, ex);
280                 return false;
281             }
282         }
283     }
284     
285     /** all services */
286     public Enumeration JavaDoc<ServiceType> services () {
287         return Collections.enumeration (getServiceTypes ());
288     }
289
290     /** Get all available services that are subclass of given class
291     * @param clazz the class that all services should be subclass of
292     * @return an enumeration of {@link ServiceType}s that are subclasses of
293     * given class
294     */

295     public <T extends ServiceType> Enumeration JavaDoc<T> services(Class JavaDoc<T> clazz) {
296         if (clazz == null) return org.openide.util.Enumerations.empty();
297         Collection JavaDoc res = Lookup.getDefault().lookupAll(clazz);
298         return Collections.enumeration(res);
299     }
300     
301     /** Write the object down.
302     */

303     private void writeObject (ObjectOutputStream JavaDoc oos) throws IOException JavaDoc {
304         Enumeration JavaDoc en = services ();
305         while (en.hasMoreElements ()) {
306             ServiceType s = (ServiceType)en.nextElement ();
307
308             NbMarshalledObject obj;
309             try {
310                 obj = new NbMarshalledObject (s);
311             } catch (IOException JavaDoc ex) {
312                 Logger.getLogger(Services.class.getName()).log(Level.WARNING, null, ex);
313                 // skip the object if it cannot be serialized
314
obj = null;
315             }
316             if (obj != null) {
317                 oos.writeObject (obj);
318             }
319         }
320
321         oos.writeObject (null);
322     }
323
324     /** Read the object.
325     */

326     private void readObject (ObjectInputStream JavaDoc oos)
327     throws IOException JavaDoc, ClassNotFoundException JavaDoc {
328         final LinkedList JavaDoc<ServiceType> ll = new LinkedList JavaDoc<ServiceType> ();
329         for (;;) {
330             NbMarshalledObject obj = (NbMarshalledObject) oos.readObject();
331
332             if (obj == null) {
333                 break;
334             }
335             try {
336                 ServiceType s = (ServiceType) obj.get();
337
338                 ll.add(s);
339             }
340             catch (IOException JavaDoc ex) {
341                 Logger.getLogger(Services.class.getName()).log(Level.WARNING, null, ex);
342             }
343             catch (ClassNotFoundException JavaDoc ex) {
344                 Logger.getLogger(Services.class.getName()).log(Level.WARNING, null, ex);
345             }
346         }
347
348         getDefault ().setServiceTypes (ll);
349     }
350
351     /** Only one instance */
352     private Object JavaDoc readResolve () {
353         return getDefault ();
354     }
355 }
356
Popular Tags