KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > varia > deployment > convertor > JarTransformer


1 /*
2 * JBoss, Home of Professional Open Source
3 * Copyright 2005, JBoss Inc., and individual contributors as indicated
4 * by the @authors tag. See the copyright.txt in the distribution for a
5 * full listing of individual contributors.
6 *
7 * This is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation; either version 2.1 of
10 * the License, or (at your option) any later version.
11 *
12 * This software is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this software; if not, write to the Free
19 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21 */

22 package org.jboss.varia.deployment.convertor;
23
24 import java.io.ByteArrayInputStream JavaDoc;
25 import java.io.ByteArrayOutputStream JavaDoc;
26 import java.io.File JavaDoc;
27 import java.io.FileFilter JavaDoc;
28 import java.io.FileInputStream JavaDoc;
29 import java.io.FileOutputStream JavaDoc;
30 import java.io.InputStream JavaDoc;
31 import java.io.IOException JavaDoc;
32 import java.io.OutputStream JavaDoc;
33 import java.util.Properties JavaDoc;
34
35 import org.jboss.logging.Logger;
36
37 /**
38  * JarTransformer is used to transform passed in jar file.
39  * Transformation algorithm:
40  * 1. open JarInputStream on passed in Jar file,
41  * open JarOutputStream for result;
42  * 2. read next Jar entry;
43  * 3. check whether Jar entry is an XML file
44  * - if it's not, copy Jar entry to result and go to step 2.
45  * 4. check whether there is an XSL file with name equal to XML file's
46  * in classpath.
47  * - if there isn't, copy Jar entry to result and go to step 2.
48  * 5. check whether there is a properties file with the name equal to
49  * XML file's name + "-output.properties"
50  * 6. set needed xsl parameters
51  * 7. transform Jar entry with xsl template and output properties
52  * (if were found)
53  * 8. check whether there is a property "newname" in output properties
54  * - if there is, write transformed entry to result with the value
55  * of "newname";
56  * - otherwise write transformed entry to result with the original
57  * Jar entry name
58  *
59  * @author <a HREF="mailto:aloubyansky@hotmail.com">Alex Loubyansky</a>
60  */

61 public class JarTransformer
62 {
63    // Attributes --------------------------------------------------------
64
private static Logger log = Logger.getLogger(JarTransformer.class);
65
66    // Public static methods ---------------------------------------------
67
/**
68     * Applies transformations to xml sources for passed in jar file
69     */

70    public static void transform(File JavaDoc root, Properties JavaDoc globalXslParams)
71       throws Exception JavaDoc
72    {
73       // local xsl params
74
Properties JavaDoc xslParams = new Properties JavaDoc( globalXslParams );
75
76       File JavaDoc metaInf = new File JavaDoc(root, "META-INF");
77       if(!metaInf.exists())
78       {
79          return;
80          //throw new Exception("No META-INF directory found");
81
}
82
83       // set path to ejb-jar.xml in xslParams
84
File JavaDoc ejbjar = new File JavaDoc(metaInf, "ejb-jar.xml");
85       if(ejbjar.exists())
86          xslParams.setProperty("ejb-jar", ejbjar.getAbsolutePath());
87
88       // list only xml files.
89
// Note: returns null only if the path name isn't a directory
90
// or I/O exception occured
91
File JavaDoc[] files = metaInf.listFiles(
92         new FileFilter JavaDoc()
93         {
94            public boolean accept(File JavaDoc file)
95            {
96               if( file.getName().endsWith( ".xml" )
97                  && !file.isDirectory() )
98                  return true;
99               return false;
100            }
101         }
102       );
103
104       log.debug("list XML files: " + java.util.Arrays.asList(files));
105       for(int i = 0; i < files.length; i++)
106       {
107          File JavaDoc file = files[i];
108
109          // construct names for transformation resources
110
String JavaDoc xmlName = file.getName();
111          String JavaDoc xslName = xslParams.getProperty("resources_path")
112                           + xmlName.substring(0, xmlName.length() - 3)
113                           + "xsl";
114          String JavaDoc propsName = xslParams.getProperty("resources_path")
115                             + xmlName.substring(0, xmlName.length() - 4)
116                             + "-output.properties";
117
118          // try to find XSL template and open InputStream on it
119
InputStream JavaDoc templateIs = null;
120          try
121          {
122             templateIs = JarTransformer.class.getClassLoader().
123                getResource(xslName).openStream();
124          }
125          catch( Exception JavaDoc e )
126          {
127             log.debug("xsl template wasn't found for '" + xmlName + "'");
128             continue;
129          }
130
131          log.debug("Attempt to transform '" + xmlName + "' with '" + xslName + "'");
132
133          // try to load output properties
134
Properties JavaDoc outputProps = loadProperties( propsName );
135
136          // transform Jar entry and write transformed data to result
137
InputStream JavaDoc input = null;
138          OutputStream JavaDoc output = null;
139          try
140          {
141             // transformation closes the input stream, so read entry to byte[]
142
input = new FileInputStream JavaDoc(file);
143             byte[] bytes = readBytes(input);
144             input.close();
145             bytes = transformBytes(bytes, templateIs, outputProps, xslParams);
146
147             // Determine the new name for the transformed entry
148
String JavaDoc entryname = null;
149             if(outputProps != null)
150                entryname = outputProps.getProperty("newname");
151             if(entryname == null)
152                entryname = file.getName();
153
154             output = new FileOutputStream JavaDoc(new File JavaDoc(root, entryname));
155             writeBytes( output, bytes );
156
157             log.debug("Entry '" + file.getName() + "' transformed to '" + entryname + "'");
158          }
159          catch(Exception JavaDoc e)
160          {
161             log.debug("Exception while transforming entry '" + file.getName(), e);
162          }
163          finally
164          {
165             if(templateIs != null)
166                try{ templateIs.close(); } catch(Exception JavaDoc e) {}
167             if(input != null)
168                try{ input.close(); } catch(Exception JavaDoc e) {}
169             if(output != null)
170                try{ output.close(); } catch(Exception JavaDoc e) {}
171          }
172       }
173    }
174
175    // Private static methods ------------------------------------------
176
/**
177     * Searches for, loads and returns properties from file
178     * <code>propsName</code>
179     */

180    private static Properties JavaDoc loadProperties( String JavaDoc propsName )
181    {
182       Properties JavaDoc props = new Properties JavaDoc();
183       InputStream JavaDoc propsIs = null;
184       try
185       {
186          propsIs = JarTransformer.class.getClassLoader().
187             getResource(propsName).openStream();
188          props.load(propsIs);
189          log.debug("Loaded properties '" + propsName + "'");
190       }
191       catch(Exception JavaDoc e)
192       {
193          log.debug("Couldn't find properties '" + propsName + "'");
194       }
195       finally
196       {
197          if(propsIs != null)
198             try{ propsIs.close(); } catch(Exception JavaDoc e) {}
199       }
200       return props;
201    }
202
203    /**
204     * Returns byte array that is the result of transformation of
205     * the passed in byte array with xsl template and output properties
206     */

207    private static byte[] transformBytes(byte[] bytes,
208                                         InputStream JavaDoc xslIs,
209                                         Properties JavaDoc outputprops)
210       throws Exception JavaDoc
211    {
212       ByteArrayInputStream JavaDoc bais = new ByteArrayInputStream JavaDoc(bytes);
213       ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc(2048);
214       try
215       {
216          XslTransformer.applyTransformation(bais, baos, xslIs, outputprops);
217       }
218       finally
219       {
220          if(bais != null)
221             try{ bais.close(); } catch(Exception JavaDoc e) {}
222          if(baos != null)
223             try{ baos.close(); } catch(Exception JavaDoc e) {}
224       }
225       return baos.toByteArray();
226    }
227
228    /**
229     * Returns byte array that is the result of transformation of
230     * the passed in byte array with xsl template, output properties
231     * and xsl parameters
232     */

233    private static byte[] transformBytes( byte[] bytes,
234                                          InputStream JavaDoc xslIs,
235                                          Properties JavaDoc outputProps,
236                                          Properties JavaDoc xslParams )
237       throws Exception JavaDoc
238    {
239       ByteArrayInputStream JavaDoc bais = new ByteArrayInputStream JavaDoc(bytes);
240       ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc(2048);
241       try
242       {
243          XslTransformer.applyTransformation(
244             bais, baos, xslIs, outputProps, xslParams );
245       }
246       finally
247       {
248          if(bais != null)
249             try{ bais.close(); } catch(Exception JavaDoc e) {}
250          if(baos != null)
251             try{ baos.close(); } catch(Exception JavaDoc e) {}
252       }
253       return baos.toByteArray();
254    }
255
256    /**
257     * Writes byte array to OutputStream.
258     */

259    private static void writeBytes(OutputStream JavaDoc os, byte[] bytes)
260       throws Exception JavaDoc
261    {
262       os.write(bytes, 0, bytes.length);
263       os.flush();
264    }
265
266    /**
267     * Copies bytes from InputStream to OutputStream.
268     * Returns the number of bytes copied.
269     */

270    private static int copyBytes(InputStream JavaDoc is, OutputStream JavaDoc os)
271       throws Exception JavaDoc
272    {
273       byte[] buffer = readBytes(is);
274       os.write(buffer, 0, buffer.length);
275       os.flush();
276       return buffer.length;
277    }
278
279    /**
280     * Returns byte array read from InputStream
281     */

282    private static byte[] readBytes(InputStream JavaDoc is)
283       throws IOException JavaDoc
284    {
285       byte[] buffer = new byte[ 8192 ];
286       ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc( 2048 );
287       int n;
288       baos.reset();
289       try
290       {
291          while((n = is.read(buffer, 0, buffer.length)) != -1)
292             baos.write(buffer, 0, n);
293          buffer = baos.toByteArray();
294       }
295       finally
296       {
297          if(baos != null)
298             try{ baos.close(); } catch(Exception JavaDoc e) {}
299       }
300       return buffer;
301    }
302 }
303
Popular Tags