KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > tools > files > MimeTypesFromWebAppXmlFile


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12
//
13
//
14
// MimeTypesFromWebAppXmlFile
15
//
16
// NK 10.01.2002
17
//
18
//
19

20 package org.jahia.tools.files;
21
22
23 import java.io.FileInputStream JavaDoc;
24 import java.io.FileNotFoundException JavaDoc;
25 import java.io.FileOutputStream JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.util.Properties JavaDoc;
28 import java.util.Vector JavaDoc;
29
30 import javax.xml.parsers.DocumentBuilder JavaDoc;
31 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
32 import javax.xml.parsers.ParserConfigurationException JavaDoc;
33 import javax.xml.transform.OutputKeys JavaDoc;
34
35 import org.jahia.utils.JahiaConsole;
36 import org.w3c.dom.Document JavaDoc;
37 import org.w3c.dom.Element JavaDoc;
38 import org.w3c.dom.Node JavaDoc;
39 import org.w3c.dom.NodeList JavaDoc;
40
41
42 /**
43  * Load mime types declared in a Web.xml file
44  *
45  * <mime-mapping>
46  * <extension>abs</extension>
47  * <mime-type>audio/x-mpeg</mime-type>
48  * </mime-mapping>
49  * <mime-mapping>
50  * <extension>ai</extension>
51  * <mime-type>application/postscript</mime-type>
52  * </mime-mapping>
53  *
54  * @author Khue ng
55  * @version 1.0
56  */

57 public class MimeTypesFromWebAppXmlFile {
58
59     private static final String JavaDoc CLASS_NAME = MimeTypesFromWebAppXmlFile.class.getName();
60
61     /** The xml Document **/
62     protected Document JavaDoc m_XMLDocument;
63     /** The Full Path to the xml file **/
64     protected String JavaDoc m_DocPath;
65
66     protected org.xml.sax.EntityResolver JavaDoc m_Resolver;
67
68
69     private static final String JavaDoc CANT_READ_FILE_MSG = "Can't read XML file";
70     private static final String JavaDoc ERROR_READING_FILE_MSG = "Error reading file";
71
72     private static final String JavaDoc WEB_APP_TAG = "web-app";
73     private static final String JavaDoc MIME_MAPPING_TAG = "mime-mapping";
74     private static final String JavaDoc EXTENSION_TAG = "extension";
75     private static final String JavaDoc MIME_TYPE_TAG = "mime-type";
76
77     private Properties JavaDoc m_MimeTypes = new Properties JavaDoc();
78
79     //--------------------------------------------------------------------------
80
/**
81      * Handle xml document using default parser behavior
82      *
83      * @param (String) path, the full path to a xml file
84      */

85     public MimeTypesFromWebAppXmlFile (String JavaDoc docPath)
86     throws Exception JavaDoc {
87         m_DocPath = docPath;
88
89         try {
90                 loadFile(m_DocPath);
91         } catch ( Throwable JavaDoc t ){
92               throw new Exception JavaDoc( CLASS_NAME
93                                     + ", Exception while loading to the file"
94                                     + m_DocPath + "\n"
95                                     + t.getMessage() );
96         }
97     }
98
99     //--------------------------------------------------------------------------
100
/**
101      * Handle xml document using a gived parser
102      *
103      * @param (String) path, the full path to a xml file
104      * @param (Parser) parser, the parser to use
105      */

106     public MimeTypesFromWebAppXmlFile (String JavaDoc docPath, org.xml.sax.EntityResolver JavaDoc entityResolver)
107     throws Exception JavaDoc {
108
109         m_Resolver = entityResolver;
110         m_DocPath = docPath;
111
112         try {
113                 loadFile(m_DocPath);
114         } catch ( Throwable JavaDoc t ){
115               throw new Exception JavaDoc( CLASS_NAME
116                                     + ", Exception while loading to the file"
117                                     + m_DocPath + "\n"
118                                     + t.getMessage() );
119         }
120     }
121
122     //--------------------------------------------------------------------------
123
/**
124      * Return a mime type looking at full file name
125      *
126      * @param String the file name
127      * @return String the mime type or "" if not found
128      */

129     public String JavaDoc getMimeTypeFromFilename (String JavaDoc filename){
130
131         if ( (m_MimeTypes == null)
132                 || (filename == null)
133                 || (filename.lastIndexOf(".") == -1) )
134             return "";
135
136         String JavaDoc mimeType = "";
137         String JavaDoc ext = filename.substring( filename.lastIndexOf(".") + 1,
138                                                  filename.length());
139
140         return getMimeTypeFromExt(ext);
141     }
142
143     //--------------------------------------------------------------------------
144
/**
145      * Return a mime type looking at the file extension without "."
146      *
147      * @param String the extension
148      * @return String the mime type or "" if not found
149      */

150     public String JavaDoc getMimeTypeFromExt (String JavaDoc extension){
151
152         if ( (m_MimeTypes == null)
153                 || (extension == null) )
154             return "";
155
156         String JavaDoc mimeType = "";
157
158         mimeType = m_MimeTypes.getProperty(extension.toLowerCase());
159         if ( mimeType == null )
160             mimeType = "";
161
162         return mimeType;
163     }
164
165
166     //--------------------------------------------------------------------------
167
/**
168      * Return the mimeTypes list as a Properties bean
169      *
170      * @return Properties mimeTypes
171      */

172     public Properties JavaDoc getMimeTypes (){
173
174         return (Properties JavaDoc)m_MimeTypes.clone();
175     }
176
177
178     //--------------------------------------------------------------------------
179
/**
180      * Extract data from xml document.
181      */

182     public void extractDocumentData() throws Exception JavaDoc {
183
184         if (m_XMLDocument == null) {
185
186             throw new Exception JavaDoc ( CLASS_NAME + ", web.xml document is null" );
187         }
188
189         if (!m_XMLDocument.hasChildNodes()) {
190
191             throw new Exception JavaDoc ( CLASS_NAME +
192                                         ", Main document node has no children" );
193
194         }
195
196         // get web-app node
197
Element JavaDoc webAppNode;
198         webAppNode = m_XMLDocument.getDocumentElement();
199
200
201         if (!webAppNode.getNodeName().equalsIgnoreCase(WEB_APP_TAG)) {
202
203             throw new Exception JavaDoc( CLASS_NAME +
204                         ", web-app tag is not present as starting tag in file" );
205         }
206
207         // build the mime mapping list
208
Vector JavaDoc nodesList = getChildNodes(webAppNode,MIME_MAPPING_TAG);
209         int size = nodesList.size();
210         if ( size>0 ){
211
212             Node JavaDoc nodeItem = null;
213             String JavaDoc extension = "";
214             String JavaDoc mimeType = "";
215
216             Node JavaDoc currNode = null;
217
218             for ( int i=0 ; i<size ; i++ ){
219                 nodeItem = (Node JavaDoc)nodesList.get(i);
220
221                 currNode = nextChildOfTag(nodeItem,EXTENSION_TAG);
222                 if (currNode != null ){
223                     extension = currNode.getFirstChild().getNodeValue().trim();
224                 }
225
226                 currNode = nextChildOfTag(nodeItem,MIME_TYPE_TAG);
227                 if (currNode != null ){
228                     mimeType = currNode.getFirstChild().getNodeValue().trim();
229                 }
230
231                 if ( extension != null && mimeType != null ){
232                     m_MimeTypes.setProperty(extension.toLowerCase(),mimeType);
233                     //System.out.println(CLASS_NAME+", added mime type :" + extension + "," + mimeType + "\n");
234
}
235             }
236         }
237     }
238
239     //--------------------------------------------------------------------------
240
private void loadFile(String JavaDoc sourceFileName)
241     throws ParserConfigurationException JavaDoc, Exception JavaDoc, IOException JavaDoc, org.xml.sax.SAXException JavaDoc {
242
243         JahiaConsole.println(CLASS_NAME+".loadFile","sourceFileName=" + sourceFileName);
244
245         DocumentBuilderFactory JavaDoc dfactory = DocumentBuilderFactory.newInstance();
246         //dfactory.setValidating(true); // create only parsers that are validating
247

248         DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
249         if ( m_Resolver != null ){
250             docBuilder.setEntityResolver(m_Resolver);
251         }
252         FileInputStream JavaDoc sourceStream = new FileInputStream JavaDoc(sourceFileName);
253         m_XMLDocument = docBuilder.parse(sourceStream);
254         m_XMLDocument.normalize(); // clean up DOM tree a little
255

256         extractDocumentData ();
257     }
258
259     //--------------------------------------------------------------------------
260
private void saveFile(String JavaDoc destinationFileName)
261     throws javax.xml.transform.TransformerConfigurationException JavaDoc, FileNotFoundException JavaDoc,
262            javax.xml.transform.TransformerException JavaDoc
263     {
264
265             m_XMLDocument.normalize(); // cleanup DOM tree a little
266

267             javax.xml.transform.TransformerFactory JavaDoc tfactory = javax.xml.transform.TransformerFactory.newInstance();
268
269             // This creates a transformer that does a simple identity transform,
270
// and thus can be used for all intents and purposes as a serializer.
271
javax.xml.transform.Transformer JavaDoc serializer = tfactory.newTransformer();
272
273             serializer.setOutputProperty(OutputKeys.METHOD, "xml");
274             serializer.setOutputProperty(OutputKeys.INDENT, "yes");
275             FileOutputStream JavaDoc fileStream = new FileOutputStream JavaDoc(destinationFileName);
276
277             serializer.transform(new javax.xml.transform.dom.DOMSource JavaDoc(m_XMLDocument),
278                                  new javax.xml.transform.stream.StreamResult JavaDoc(fileStream));
279
280         try {
281             fileStream.flush();
282             fileStream.close();
283             fileStream = null;
284         } catch ( IOException JavaDoc ioe ) {
285         }
286     }
287
288     //--------------------------------------------------------------------------
289
/**
290      * Get a Vector of child nodes equals with a gived tag
291      *
292      * @param (Node) startNode, the parent node
293      * @param (String) tagName, the Children's tag name
294      * @return (Vector) childs, a Vector of child node
295      * @author NK
296      */

297     private Vector JavaDoc getChildNodes( Node JavaDoc parentNode,
298                                     String JavaDoc tagName
299                                     ) throws Exception JavaDoc {
300
301         Vector JavaDoc childs = new Vector JavaDoc();
302
303         NodeList JavaDoc nodeList = parentNode.getChildNodes();
304
305         if ( nodeList != null ) {
306
307             int size = nodeList.getLength();
308             for ( int i=0; i<size ; i++ ){
309                 Node JavaDoc nodeItem = null;
310                 nodeItem = nodeList.item(i);
311                 /*
312                 JahiaConsole.println(">>", " getChildNodes, current child node = " + nodeItem.getNodeName() );
313                 */

314                 if ( nodeItem.getNodeName().equalsIgnoreCase(tagName) ){
315                     childs.add(nodeItem);
316                 }
317             }
318         }
319
320         return childs;
321     }
322
323     //--------------------------------------------------------------------------
324
/**
325      * nextChildOfTag
326      * Go to the next Child Element Node that is equals
327      * with the gived tag value
328      *
329      * @param (Node) startNode, the parent node
330      * @param (String) tag, the tag name
331      * @author NK
332      */

333     private Node JavaDoc nextChildOfTag( Node JavaDoc startNode,
334                                     String JavaDoc tagName
335                                  ) throws Exception JavaDoc {
336
337         /*
338         JahiaConsole.println(">>", " nextChildOfTag, tag " + tagName + " started ");
339         */

340
341         Vector JavaDoc childs = getChildNodes(startNode,tagName);
342         int size = childs.size();
343         for ( int i=0 ; i<size; i++ ){
344             Node JavaDoc child = (Node JavaDoc)childs.get(i);
345             if (child.getNodeName().equalsIgnoreCase(tagName)){
346                 /*
347                 JahiaConsole.println(">>", " nextChildOfTag, current child = " + child.getNodeName() );
348                 */

349                 return child;
350             }
351         }
352
353         return null;
354     }
355
356
357
358 } // end MimeTypesFromWebAppXmlFile
359
Popular Tags