KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > websvc > api > jaxws > project > WSUtils


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.websvc.api.jaxws.project;
21
22 import java.io.BufferedReader JavaDoc;
23 import java.io.BufferedWriter JavaDoc;
24 import java.io.File JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.InputStream JavaDoc;
27 import java.io.InputStreamReader JavaDoc;
28 import java.io.OutputStream JavaDoc;
29 import java.io.OutputStreamWriter JavaDoc;
30 import java.net.URI JavaDoc;
31 import java.net.URL JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.Set JavaDoc;
35 import org.netbeans.api.java.project.JavaProjectConstants;
36 import org.netbeans.api.project.Project;
37 import org.netbeans.api.project.SourceGroup;
38 import org.netbeans.api.project.Sources;
39 import org.netbeans.modules.websvc.api.jaxws.project.config.JaxWsModel;
40 import org.netbeans.modules.xml.retriever.RetrieveEntry;
41 import org.netbeans.modules.xml.retriever.Retriever;
42 import org.netbeans.modules.xml.retriever.RetrieverImpl;
43 import org.netbeans.spi.project.support.ant.EditableProperties;
44 import org.openide.DialogDisplayer;
45 import org.openide.ErrorManager;
46 import org.openide.NotifyDescriptor;
47 import org.openide.cookies.SaveCookie;
48 import org.openide.filesystems.FileLock;
49 import org.openide.filesystems.FileObject;
50 import org.openide.filesystems.FileSystem;
51 import org.openide.filesystems.FileSystem.AtomicAction;
52 import org.openide.filesystems.FileUtil;
53 import org.openide.loaders.DataFolder;
54 import org.openide.loaders.DataObject;
55 import org.openide.util.NbBundle;
56 import org.openide.util.Utilities;
57
58 /**
59  *
60  * @author mkuchtiak
61  */

62 public class WSUtils {
63
64     private static final String JavaDoc ENDORSED_DIR_PROPERTY="jaxws.endorsed.dir"; //NOI18N
65
/** downloads XML resources from source URI to target folder
66      * (USAGE : this method can download a wsdl file and all wsdl/XML schemas,
67      * that are recursively imported by this wsdl)
68      * @param targetFolder A folder inside a NB project (ONLY) to which the retrieved resource will be copied to. All retrieved imported/included resources will be copied relative to this directory.
69      * @param source URI of the XML resource that will be retrieved into the project
70      * @return FileObject of the retrieved resource in the local file system
71      */

72     public static FileObject retrieveResource(FileObject targetFolder, URI JavaDoc source)
73     throws java.net.UnknownHostException JavaDoc, java.net.URISyntaxException JavaDoc, IOException JavaDoc{
74         try {
75             Retriever retriever = new RetrieverImpl();
76             FileObject result = retriever.retrieveResource(targetFolder, source);
77             if (result==null) {
78                 Map JavaDoc map = retriever.getRetrievedResourceExceptionMap();
79                 if (map!=null) {
80                     Set JavaDoc keys = map.keySet();
81                     Iterator JavaDoc it = keys.iterator();
82                     while (it.hasNext()) {
83                         RetrieveEntry key = (RetrieveEntry)it.next();
84                         Object JavaDoc exc = map.get(key);
85                         if (exc instanceof IOException JavaDoc) {
86                             throw (IOException JavaDoc)exc;
87                         } else if (exc instanceof java.net.URISyntaxException JavaDoc) {
88                             throw (java.net.URISyntaxException JavaDoc)exc;
89                         } else if (exc instanceof Exception JavaDoc) {
90                             IOException JavaDoc ex = new IOException JavaDoc(NbBundle.getMessage(WSUtils.class,"ERR_retrieveResource",key.getCurrentAddress()));
91                             ex.initCause((Exception JavaDoc)exc);
92                             throw (IOException JavaDoc)(ex);
93                         }
94                     }
95                 }
96             }
97             return result;
98         } catch (RuntimeException JavaDoc ex) {
99             throw (IOException JavaDoc)(new IOException JavaDoc(ex.getLocalizedMessage()).initCause(ex));
100         }
101     }
102     
103     public static String JavaDoc findProperServiceName(String JavaDoc name, JaxWsModel jaxWsModel) {
104         if (jaxWsModel.findServiceByName(name)==null) return name;
105         for (int i = 1;; i++) {
106             String JavaDoc destName = name + "_" + i; // NOI18N
107
if (jaxWsModel.findServiceByName(destName)==null)
108                 return destName;
109         }
110     }
111     
112     public static void retrieveJaxWsFromResource(FileObject projectDir) throws IOException JavaDoc {
113         final String JavaDoc jaxWsContent =
114                 readResource(WSUtils.class.getResourceAsStream("/org/netbeans/modules/websvc/jaxwsmodel/resources/jax-ws.xml")); //NOI18N
115
final FileObject nbprojFo = projectDir.getFileObject("nbproject"); //NOI18N
116
assert nbprojFo != null : "Cannot find nbproject directory"; //NOI18N
117
FileSystem fs = nbprojFo.getFileSystem();
118         fs.runAtomicAction(new FileSystem.AtomicAction() {
119             public void run() throws IOException JavaDoc {
120                 FileObject jaxWsFo = FileUtil.createData(nbprojFo, "jax-ws.xml");//NOI18N
121
FileLock lock = jaxWsFo.lock();
122                 try {
123                     BufferedWriter JavaDoc bw = new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(jaxWsFo.getOutputStream(lock)));
124                     bw.write(jaxWsContent);
125                     bw.close();
126                 } finally {
127                     lock.releaseLock();
128                 }
129             }
130         });
131     }
132     
133     public static void retrieveHandlerConfigFromResource(final FileObject targetDir, final String JavaDoc handlerConfigName) throws IOException JavaDoc {
134         final String JavaDoc handlerContent =
135                 readResource(WSUtils.class.getResourceAsStream("/org/netbeans/modules/websvc/jaxwsmodel/resources/handler.xml")); //NOI18N
136
FileSystem fs = targetDir.getFileSystem();
137         fs.runAtomicAction(new FileSystem.AtomicAction() {
138             public void run() throws IOException JavaDoc {
139                 FileObject handlerFo = FileUtil.createData(targetDir, handlerConfigName);//NOI18N
140
FileLock lock = handlerFo.lock();
141                 BufferedWriter JavaDoc bw = null;
142                 OutputStream JavaDoc os = null;
143                 try {
144                     os = handlerFo.getOutputStream(lock);
145                     bw = new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(os));
146                     bw.write(handlerContent);
147                     bw.close();
148                 } finally {
149                     if(bw != null)
150                         bw.close();
151                     if(os != null)
152                         os.close();
153                     if(lock != null)
154                         lock.releaseLock();
155                 }
156             }
157         });
158     }
159     
160     public static void generateSunJaxwsFile(final FileObject targetDir) throws IOException JavaDoc {
161         final String JavaDoc sunJaxwsContent =
162                 readResource(WSUtils.class.getResourceAsStream("/org/netbeans/modules/websvc/jaxwsmodel/resources/sun-jaxws.xml")); //NOI18N
163
FileSystem fs = targetDir.getFileSystem();
164         fs.runAtomicAction(new FileSystem.AtomicAction() {
165             public void run() throws IOException JavaDoc {
166                 FileObject sunJaxwsFo = FileUtil.createData(targetDir, "sun-jaxws.xml");//NOI18N
167
FileLock lock = sunJaxwsFo.lock();
168                 BufferedWriter JavaDoc bw = null;
169                 OutputStream JavaDoc os = null;
170                 OutputStreamWriter JavaDoc osw = null;
171                 try {
172                     os = sunJaxwsFo.getOutputStream(lock);
173                     osw = new OutputStreamWriter JavaDoc(os);
174                     bw = new BufferedWriter JavaDoc(osw);
175                     bw.write(sunJaxwsContent);
176                 } finally {
177                     if(bw != null)
178                         bw.close();
179                     if(os != null)
180                         os.close();
181                     if(osw != null)
182                         osw.close();
183                     if(lock != null)
184                         lock.releaseLock();
185                 }
186             }
187         });
188     }
189     
190     private static String JavaDoc readResource(InputStream JavaDoc is) throws IOException JavaDoc {
191         // read the config from resource first
192
StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
193         String JavaDoc lineSep = System.getProperty("line.separator");//NOI18N
194
BufferedReader JavaDoc br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(is));
195         String JavaDoc line = br.readLine();
196         while (line != null) {
197             sb.append(line);
198             sb.append(lineSep);
199             line = br.readLine();
200         }
201         br.close();
202         return sb.toString();
203     }
204     
205     public static void removeImplClass(Project project, String JavaDoc implClass) {
206         Sources sources = (Sources)project.getLookup().lookup(Sources.class);
207         String JavaDoc resource = implClass.replace('.','/')+".java"; //NOI18N
208
if (sources!=null) {
209             SourceGroup[] srcGroup = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
210             for (int i=0;i<srcGroup.length;i++) {
211                 final FileObject srcRoot = srcGroup[i].getRootFolder();
212                 final FileObject implClassFo = srcRoot.getFileObject(resource);
213                 if (implClassFo!=null) {
214                     try {
215                         FileSystem fs = implClassFo.getFileSystem();
216                         fs.runAtomicAction(new AtomicAction() {
217                             public void run() {
218                                 FileObject parent = implClassFo.getParent();
219                                 deleteFile(implClassFo);
220                                 while (parent!=srcRoot && parent.getChildren().length==0) {
221                                     FileObject fileToDelete=parent;
222                                     parent = parent.getParent();
223                                     deleteFile(fileToDelete);
224                                 }
225                             }
226                         });
227                     } catch (IOException JavaDoc ex) {
228                         ErrorManager.getDefault().notify(ex);
229                     }
230                     return;
231                 }
232             }
233         }
234     }
235     
236     private static void deleteFile(FileObject f) {
237         FileLock lock = null;
238         try {
239             lock = f.lock();
240             if (f.isFolder()) {
241                 DataFolder folder = DataFolder.findFolder(f);
242                 // save all opened files
243
if (folder!=null) {
244                     DataObject[] children = folder.getChildren();
245                     for (int i=0;i<children.length;i++) {
246                         SaveCookie save = (SaveCookie)children[i].getCookie(SaveCookie.class);
247                         if (save!=null) save.save();
248                     }
249                 }
250             }
251             f.delete(lock);
252         } catch(java.io.IOException JavaDoc e) {
253             NotifyDescriptor ndd =
254                     new NotifyDescriptor.Message(NbBundle.getMessage(WSUtils.class, "MSG_Unable_Delete_File", f.getNameExt()),
255                     NotifyDescriptor.ERROR_MESSAGE);
256             DialogDisplayer.getDefault().notify(ndd);
257         } finally {
258             if(lock != null) {
259                 lock.releaseLock();
260             }
261         }
262     }
263     
264     /** Copy files from source folder to target folder recursively */
265     public static void copyFiles(FileObject sourceFolder, FileObject targetFolder) throws IOException JavaDoc {
266         FileObject[] children = sourceFolder.getChildren();
267         for (int i=0;i<children.length;i++) {
268             if (children[i].isFolder()) {
269                 FileObject folder = targetFolder.createFolder(children[i].getName());
270                 copyFiles(children[i],folder);
271             } else {
272                 children[i].copy(targetFolder, children[i].getName(), children[i].getExt());
273             }
274         }
275     }
276     
277     public static FileObject backupAndGenerateJaxWs(FileObject projectDir, FileObject oldJaxWs, RuntimeException JavaDoc reason) throws IOException JavaDoc {
278         DialogDisplayer.getDefault().notify(
279                 new NotifyDescriptor.Message(NbBundle.getMessage(WSUtils.class,"ERR_corruptedJaxWs",oldJaxWs.getPath(),reason.getMessage()),NotifyDescriptor.ERROR_MESSAGE));
280         FileObject parent = oldJaxWs.getParent();
281         FileObject oldBackup = parent.getFileObject("jax-ws.xml.old"); //NOI18N
282
FileLock lock = null;
283         if (oldBackup!=null) {
284             // remove old backup
285
try {
286                 lock = oldBackup.lock();
287                 oldBackup.delete(lock);
288             } finally {
289                 if (lock!=null) lock.releaseLock();
290             }
291         }
292         // renaming old jax-ws.xml;
293
try {
294             lock = oldJaxWs.lock();
295             oldJaxWs.rename(lock, "jax-ws.xml","old"); //NOI18N
296
} finally {
297             if (lock!=null) lock.releaseLock();
298         }
299         retrieveJaxWsFromResource(projectDir);
300         return projectDir.getFileObject(GeneratedFilesHelper.JAX_WS_XML_PATH);
301     }
302     
303     /** Set jaxws.endorsed.dir property for wsimport, wsgen tasks
304      * to specify jvmarg value : -Djava.endorsed.dirs=${jaxws.endorsed.dir}"
305      */

306     public static void setJaxWsEndorsedDirProperty(EditableProperties ep) {
307         String JavaDoc oldJaxWsEndorsedDirs = ep.getProperty(ENDORSED_DIR_PROPERTY);
308         String JavaDoc javaVersion = System.getProperty("java.specification.version"); //NOI18N
309
if ("1.6".equals(javaVersion)) { //NOI18N
310
String JavaDoc jaxWsEndorsedDirs = getJaxWsApiDir();
311             if (jaxWsEndorsedDirs!=null && !jaxWsEndorsedDirs.equals(oldJaxWsEndorsedDirs))
312             ep.setProperty(ENDORSED_DIR_PROPERTY, jaxWsEndorsedDirs);
313         } else {
314             if (oldJaxWsEndorsedDirs!=null) {
315                 ep.remove(ENDORSED_DIR_PROPERTY);
316             }
317         }
318     }
319     
320     private static String JavaDoc getJaxWsApiDir() {
321         URL JavaDoc wsFeatureUrl = WSUtils.class.getClassLoader().getResource("javax/xml/ws/WebServiceFeature.class");
322         if (wsFeatureUrl!=null) {
323             String JavaDoc prefix = "jar:file:"; //NOI18N
324
String JavaDoc postfix = "/jaxws-api.jar!/javax/xml/ws/WebServiceFeature.class"; //NOI18N
325
String JavaDoc jaxWsUrl = wsFeatureUrl.toExternalForm();
326             if (jaxWsUrl.startsWith(prefix) && jaxWsUrl.endsWith(postfix));
327             // the resource name on Windows starts with (example) : "jar:file:/C:/Program Files/java/..."
328
// on Linux : "jar:file:/usr/java/...
329
int startPosition = Utilities.isWindows() ? 10 : 9;
330             int endPosition = jaxWsUrl.indexOf(postfix);
331             return jaxWsUrl.substring(startPosition,endPosition);
332         }
333         return null;
334     }
335 }
Popular Tags