KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > appclient > jws > Util


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.enterprise.appclient.jws;
25
26 import com.sun.appserv.ClassLoaderUtil;
27 import com.sun.enterprise.deployment.Application;
28 import com.sun.enterprise.deployment.ApplicationClientDescriptor;
29 import com.sun.enterprise.deployment.BundleDescriptor;
30 import com.sun.enterprise.deployment.archivist.AppClientArchivist;
31 import com.sun.enterprise.deployment.archivist.ApplicationArchivist;
32 import com.sun.enterprise.deployment.deploy.shared.AbstractArchive;
33 import com.sun.enterprise.deployment.deploy.shared.ArchiveFactory;
34 import com.sun.enterprise.deployment.util.ModuleDescriptor;
35 import com.sun.enterprise.instance.BaseManager;
36 import java.io.BufferedInputStream JavaDoc;
37 import java.io.BufferedOutputStream JavaDoc;
38 import java.io.BufferedReader JavaDoc;
39 import java.io.BufferedWriter JavaDoc;
40 import java.io.File JavaDoc;
41 import java.io.FileNotFoundException JavaDoc;
42 import java.io.FileOutputStream JavaDoc;
43 import java.io.FileInputStream JavaDoc;
44 import java.io.IOException JavaDoc;
45 import java.io.InputStream JavaDoc;
46 import java.io.InputStreamReader JavaDoc;
47 import java.io.OutputStreamWriter JavaDoc;
48 import java.net.MalformedURLException JavaDoc;
49 import java.net.URISyntaxException JavaDoc;
50 import java.net.URL JavaDoc;
51 import java.net.URLClassLoader JavaDoc;
52 import java.util.Enumeration JavaDoc;
53 import java.util.Properties JavaDoc;
54 import java.util.Vector JavaDoc;
55 import java.util.jar.JarFile JavaDoc;
56 import java.util.regex.Matcher JavaDoc;
57 import java.util.regex.Pattern JavaDoc;
58
59 /**
60  *Implements several stateless utility methods.
61  *
62  * @author tjquinn
63  */

64 public class Util {
65
66     /** Pattern to match placeholders in dynamic document templates.
67      *The pattern specifies a non-aggressive match for ${token-name} strings.
68      *(Non-aggressive means the pattern consumes as little of the input string
69      *as possible in searching for a match.) The pattern also stores the token
70      *name in group 1 of the pattern matcher.
71      */

72     private static Pattern JavaDoc placeholderPattern = Pattern.compile("\\$\\{(.*?)\\}");
73
74     /** used in finding the name of the first class in a jar file */
75     private static final String JavaDoc CLASS_SUFFIX = ".class";
76     
77     /** size of buffer used to load resources */
78     private static final int BUFFER_SIZE = 1024;
79     
80     /** Creates a new instance of Util */
81     public Util() {
82     }
83
84     /**
85      *Searches for placeholders of the form ${token-name} in the input String, retrieves
86      *the property with name token-name from the Properties object, and (if
87      *found) replaces the token in the input string with the property value.
88      *@param s String possibly containing tokens
89      *@param values Properties object containing name/value pairs for substitution
90      *@return the original string with tokens substituted using their values
91      *from the Properties object
92      */

93     public static String JavaDoc replaceTokens(String JavaDoc s, Properties JavaDoc values) {
94         Matcher JavaDoc m = placeholderPattern.matcher(s);
95
96         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
97         /*
98          *For each match, retrieve group 1 - the token - and use its value from
99          *the Properties object (if found there) to replace the token with the
100          *value.
101          */

102         while (m.find()) {
103             String JavaDoc propertyName = m.group(1);
104             String JavaDoc propertyValue = values.getProperty(propertyName);
105
106             if (propertyValue != null) {
107                 /*
108                  *The next line quotes any $ signs in the replacement string
109                  *so they are not interpreted as meta-characters by the regular expression
110                  *processor's appendReplacement. The replaceAll replaces all occurrences
111                  *of $ with \$. The extra slashes are needed to quote the backslash
112                  *for the Java language processor and then again for the regex
113                  *processor (!).
114                  */

115                 String JavaDoc adjustedPropertyValue = propertyValue.replaceAll("\\$", "\\\\\\$");
116                 String JavaDoc x = s.substring(m.start(),m.end());
117                 try {
118                     m.appendReplacement(sb, adjustedPropertyValue);
119                 } catch (IllegalArgumentException JavaDoc iae) {
120                     System.err.println("**** appendReplacement failed: segment is " + x + "; original replacement was " + propertyValue + " and adj. replacement is " + adjustedPropertyValue + "; exc follows");
121                     throw iae;
122                 }
123             }
124         }
125         /*
126          *There are no more matches, so append whatever remains of the matcher's input
127          *string to the output.
128          */

129         m.appendTail(sb);
130
131         return sb.toString();
132     }
133
134      /**
135       *Returns the main class name for the app client represented by the module descriptor.
136       *@param moduleDescr the module descriptor for the app client of interest
137       *@return main class name of the app client
138       */

139      public static String JavaDoc getMainClassNameForAppClient(ModuleDescriptor moduleDescr) throws IOException JavaDoc, FileNotFoundException JavaDoc, org.xml.sax.SAXParseException JavaDoc {
140          BundleDescriptor bd = moduleDescr.getDescriptor();
141          ApplicationClientDescriptor acDescr = (ApplicationClientDescriptor) bd;
142          
143          String JavaDoc mainClassName = acDescr.getMainClassName();
144          
145          return mainClassName;
146      }
147      
148      /**
149       *Writes the provided text to a temporary file marked for deletion on exit.
150       *@param the content to be written
151       *@param prefix for the temp file, conforming to the File.createTempFile requirements
152       *@param suffix for the temp file
153       *@param whether to keep the file
154       *@return File object for the newly-created temp file
155       *@throws IOException for any errors writing the temporary file
156       *@throws FileNotFoundException if the temp file cannot be opened for any reason
157       */

158      public static File JavaDoc writeTextToTempFile(String JavaDoc content, String JavaDoc prefix, String JavaDoc suffix, boolean retainFile) throws IOException JavaDoc, FileNotFoundException JavaDoc {
159         BufferedWriter JavaDoc wtr = null;
160         try {
161             File JavaDoc result = File.createTempFile(prefix, suffix);
162             if ( ! retainFile) {
163                 result.deleteOnExit();
164             }
165             FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(result);
166             wtr = new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(fos));
167             wtr.write(content);
168             wtr.close();
169             return result;
170         } finally {
171             if (wtr != null) {
172                 wtr.close();
173             }
174         }
175     }
176     
177     /**
178      *Writes the provided text to a temporary file marked for deletion on exit.
179      *@param the content to be written
180      *@param prefix for the temp file, conforming to the File.createTempFile requirements
181      *@param suffix for the temp file
182      *@return File object for the newly-created temp file
183      *@throws IOException for any errors writing the temporary file
184      *@throws FileNotFoundException if the temp file cannot be opened for any reason
185      */

186     public static File JavaDoc writeTextToTempFile(String JavaDoc content, String JavaDoc prefix, String JavaDoc suffix) throws IOException JavaDoc, FileNotFoundException JavaDoc {
187         return writeTextToTempFile(content, prefix, suffix, false);
188     }
189
190      /**
191       *Finds the jar file or directory that contains the current class and returns its URI.
192       *@param the class, the containing jar file or directory of which is of interest
193       *@return URL to the containing jar file or directory
194       */

195      public static URL JavaDoc locateClass(Class JavaDoc target) {
196          return target.getProtectionDomain().getCodeSource().getLocation();
197      }
198
199     /**
200      *Retrieves a resource as a String.
201      *<p>
202      *This method does not save the template in a cache. Use the instance method
203      *getTemplate for that purpose.
204      *
205      *@param a class, the class loader of which should be used for searching for the template
206      *@param the path of the resource to load, relative to the contextClass
207      *@return the resource's contents
208      *@throws IOException if the resource is not found or in case of error while loading it
209      */

210     public static String JavaDoc loadResource(Class JavaDoc contextClass, String JavaDoc resourcePath) throws IOException JavaDoc {
211         String JavaDoc result = null;
212         InputStream JavaDoc is = null;
213         try {
214             is = contextClass.getResourceAsStream(resourcePath);
215             if (is == null) {
216                 throw new IOException JavaDoc("Could not locate the requested resource relative to class " + contextClass.getName());
217             }
218
219             StringBuilder JavaDoc sb = new StringBuilder JavaDoc();
220             BufferedReader JavaDoc reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(is));
221             int charsRead;
222             char [] buffer = new char [BUFFER_SIZE];
223             while ((charsRead = reader.read(buffer)) != -1) {
224                 sb.append(buffer, 0, charsRead);
225             }
226
227             result= sb.toString();
228             return result;
229         } catch (IOException JavaDoc ioe) {
230             IOException JavaDoc wrapperIOE = new IOException JavaDoc("Error loading resource " + resourcePath);
231             wrapperIOE.initCause(ioe);
232             throw wrapperIOE;
233         } finally {
234             if (is != null) {
235                 is.close();
236             }
237         }
238     }
239     
240     /**
241      *Copy an existing file into a temporary file.
242      *@param existing file
243      *@return File object for the temporary file
244      */

245     public static File JavaDoc copyToTempFile(File JavaDoc inputFile, String JavaDoc prefix, String JavaDoc suffix, boolean retainFile) throws IOException JavaDoc, FileNotFoundException JavaDoc {
246         File JavaDoc result = null;
247         BufferedInputStream JavaDoc is = null;
248         BufferedOutputStream JavaDoc os = null;
249         try {
250             result = File.createTempFile(prefix, suffix);
251             if ( ! retainFile) {
252                 result.deleteOnExit();
253             }
254             os = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(result));
255             is = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(inputFile));
256             byte [] buffer = new byte[BUFFER_SIZE];
257             int bytesRead = 0;
258             while ( (bytesRead = is.read(buffer) ) != -1) {
259                 os.write(buffer, 0, bytesRead);
260             }
261             
262             return result;
263         } finally {
264             if (is != null) {
265                 is.close();
266             }
267             if (os != null) {
268                 os.close();
269             }
270         }
271     }
272     
273     /**
274      *Returns a codeBase expression, usable in a policy file, for the specified
275      *URL.
276      *@param classPathElement the URL to be converted
277      *@return the codeBase expression
278      */

279     public static String JavaDoc URLtoCodeBase(URL JavaDoc classPathElement) throws FileNotFoundException JavaDoc, URISyntaxException JavaDoc {
280         /*
281          *We can assume the URL specifies a file.
282          */

283         File JavaDoc file = new File JavaDoc(classPathElement.toURI());
284         if (! file.exists()) {
285             /*
286              *If we cannot locate the file, it may be a jar listed in the
287              *manifest's Class-Path of a top-level archive. The spec does
288              *not require containers to handle such jars, so just
289              *return null.
290              */

291             //throw new FileNotFoundException(classPathElement.toURI().toASCIIString());
292
return null;
293         }
294         
295         /*
296          *The format of the codebase is different for a directory vs. a jar
297          *file. Also note that the codebase must use the platform-neutral
298          *"forward-slash" notation.
299          */

300         String JavaDoc result;
301         if (file.isDirectory()) {
302             result = classPathElement.getProtocol() + ":" + classPathElement.toURI().getPath() + "-";
303         } else {
304             result = classPathElement.getProtocol() + ":" + classPathElement.toURI().getPath();
305         }
306         return result;
307     }
308 }
309
Popular Tags