KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > ws > jaxme > webapp > JaxMeServlet


1 /*
2  * Copyright 2003, 2004 The Apache Software Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15
16  */

17 package org.apache.ws.jaxme.webapp;
18
19 import java.io.File JavaDoc;
20 import java.io.FileInputStream JavaDoc;
21 import java.io.FileOutputStream JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.InputStream JavaDoc;
24 import java.net.MalformedURLException JavaDoc;
25 import java.net.URL JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.Map JavaDoc;
28 import java.util.zip.ZipEntry JavaDoc;
29 import java.util.zip.ZipOutputStream JavaDoc;
30
31 import javax.servlet.ServletException JavaDoc;
32 import javax.servlet.http.HttpServletRequest JavaDoc;
33 import javax.servlet.http.HttpServletResponse JavaDoc;
34
35 import org.apache.ws.jaxme.generator.Generator;
36 import org.apache.ws.jaxme.generator.impl.GeneratorImpl;
37 import org.apache.ws.jaxme.generator.sg.impl.JAXBSchemaReader;
38 import org.apache.ws.jaxme.xs.XSParser;
39 import org.xml.sax.EntityResolver JavaDoc;
40 import org.xml.sax.InputSource JavaDoc;
41 import org.xml.sax.SAXException JavaDoc;
42
43
44 /** <p>This class invokes the JaxMe compiler.</p>
45  */

46 public class JaxMeServlet extends BaseServlet {
47     private class StoringEntityResolver implements EntityResolver JavaDoc {
48         private final File JavaDoc schemaDir;
49         private final Map JavaDoc urlMap = new HashMap JavaDoc();
50         public StoringEntityResolver(File JavaDoc pSchemaDir) {
51             schemaDir = pSchemaDir;
52         }
53         
54         public InputSource JavaDoc resolveEntity(String JavaDoc pPublicId, String JavaDoc pSystemId) throws SAXException JavaDoc, IOException JavaDoc {
55             try {
56                 URL JavaDoc url = new URL JavaDoc(pSystemId);
57                 String JavaDoc fileName = (String JavaDoc) urlMap.get(url);
58                 if (fileName != null) {
59                     FileInputStream JavaDoc istream = new FileInputStream JavaDoc(new File JavaDoc(schemaDir, fileName));
60                     InputSource JavaDoc isource = new InputSource JavaDoc(istream);
61                     isource.setSystemId(url.toString());
62                     return isource;
63                 }
64                 
65                 String JavaDoc file = url.getFile();
66                 if (file == null) {
67                     file = "";
68                 } else {
69                     int offset = file.lastIndexOf('/');
70                     if (offset >= 0) {
71                         file = file.substring(offset+1);
72                     }
73                 }
74                 if ("".equals(file)) {
75                     file = "schema.xsd";
76                 }
77                 int offset = file.lastIndexOf('.');
78                 String JavaDoc prefix;
79                 String JavaDoc suffix;
80                 String JavaDoc numAsStr = "";
81                 if (offset > 0 && offset < file.length()) {
82                     prefix = file.substring(0, offset);
83                     suffix = file.substring(offset);
84                 } else {
85                     prefix = file;
86                     suffix = ".xsd";
87                 }
88                 File JavaDoc f;
89                 for (int num = 1; ; ++num) {
90                     f = new File JavaDoc(schemaDir, prefix + numAsStr + suffix);
91                     if (f.exists()) {
92                         numAsStr = "_" + num;
93                     } else {
94                         break;
95                     }
96                 }
97
98                 InputStream JavaDoc istream = url.openStream();
99                 schemaDir.mkdirs();
100                 FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(f);
101                 try {
102                     byte[] buffer = new byte[1024];
103                     for (;;) {
104                         int res = istream.read(buffer);
105                         if (res == -1) {
106                             break;
107                         } else if (res > 0) {
108                             fos.write(buffer, 0, res);
109                         }
110                     }
111                     istream.close();
112                     fos.close();
113                     fos = null;
114                 } finally {
115                     if (fos != null) { try { f.delete(); } catch (Throwable JavaDoc ignore) {} }
116                 }
117
118                 urlMap.put(url, f.getName());
119                 InputSource JavaDoc isource = new InputSource JavaDoc(new FileInputStream JavaDoc(f));
120                 isource.setSystemId(url.toString());
121                 return isource;
122             } catch (Exception JavaDoc e) {
123                 JaxMeServlet.this.log("Failed to resolve URL " + pSystemId, e);
124             }
125             return null;
126         }
127     }
128
129     public File JavaDoc createTempDir() throws IOException JavaDoc, ServletException JavaDoc {
130         File JavaDoc f = File.createTempFile("jaxme", ".tmp", getWorkDir());
131         f.delete();
132         if (!f.mkdir()) {
133             throw new ServletException JavaDoc("Unable to create temporary directory " + f.getAbsolutePath());
134         }
135         return f;
136     }
137
138     public void addContents(ZipOutputStream JavaDoc pZipFile, File JavaDoc pDirectory, String JavaDoc pDirName) throws IOException JavaDoc {
139         File JavaDoc[] files = pDirectory.listFiles();
140         for (int i = 0; i < files.length; i++) {
141             File JavaDoc f = files[i];
142             String JavaDoc name = pDirName.length() == 0 ? f.getName() : pDirName + "/" + f.getName();
143             if (f.isDirectory()) {
144                 addContents(pZipFile, f, name);
145             } else if (f.isFile()) {
146                 FileInputStream JavaDoc istream = new FileInputStream JavaDoc(f);
147                 try {
148                     ZipEntry JavaDoc zipEntry = new ZipEntry JavaDoc(name);
149                     pZipFile.putNextEntry(zipEntry);
150                     byte[] buffer = new byte[1024];
151                     for (;;) {
152                         int res = istream.read(buffer);
153                         if (res == -1) {
154                             break;
155                         } else if (res > 0) {
156                             pZipFile.write(buffer, 0, res);
157                         }
158                     }
159                     pZipFile.closeEntry();
160                     istream.close();
161                     istream = null;
162                 } finally {
163                     if (istream != null) { try { istream.close(); } catch (Throwable JavaDoc ignore) {} }
164                 }
165             }
166         }
167     }
168
169     public void removeDirectory(File JavaDoc pDirectory) throws ServletException JavaDoc {
170         cleanDirectory(pDirectory);
171         pDirectory.delete();
172     }
173
174     protected void doCompile(boolean pValidating, File JavaDoc pTempDir, URL JavaDoc pURL, HttpServletResponse JavaDoc pResponse)
175             throws ServletException JavaDoc, IOException JavaDoc {
176         Generator gen = new GeneratorImpl();
177         gen.setTargetDirectory(new File JavaDoc(pTempDir, "src"));
178         gen.setValidating(pValidating);
179         gen.setSchemaReader(new JAXBSchemaReader());
180         gen.setEntityResolver(new StoringEntityResolver(new File JavaDoc(pTempDir, "schema")));
181         try {
182             gen.generate(pURL);
183         } catch (Exception JavaDoc e) {
184             throw new ServletException JavaDoc(e);
185         }
186         
187         pResponse.setContentType("application/zip");
188         pResponse.setHeader("Content-Disposition", "attachment; filename=\"jaxmeGeneratedSrc.zip\"");
189         ZipOutputStream JavaDoc zipOutputStream = new ZipOutputStream JavaDoc(pResponse.getOutputStream());
190         addContents(zipOutputStream, pTempDir, "");
191         zipOutputStream.close();
192         removeDirectory(pTempDir);
193         pTempDir = null;
194     }
195
196     protected void doValidate(boolean pValidating, File JavaDoc pTempDir, URL JavaDoc pURL, HttpServletResponse JavaDoc pResponse)
197             throws ServletException JavaDoc, IOException JavaDoc {
198         XSParser parser = new XSParser();
199         parser.setValidating(pValidating);
200         InputSource JavaDoc isource = new InputSource JavaDoc(pURL.toString());
201         try {
202             parser.parse(isource);
203         } catch (Exception JavaDoc e) {
204             throw new ServletException JavaDoc(e);
205         }
206     }
207
208     public void doGet(HttpServletRequest JavaDoc pRequest, HttpServletResponse JavaDoc pResponse)
209             throws ServletException JavaDoc, IOException JavaDoc {
210         String JavaDoc s = pRequest.getParameter("url");
211         if (s == null || s.length() == 0) {
212             throw new ServletException JavaDoc("Missing or empty request parameter: " + s);
213         }
214         URL JavaDoc url;
215         try {
216             url = new URL JavaDoc(s);
217         } catch (MalformedURLException JavaDoc e) {
218             throw new ServletException JavaDoc("Malformed URL: " + s);
219         }
220         
221         boolean isValidating = Boolean.valueOf(pRequest.getParameter("isValidating")).booleanValue();
222         File JavaDoc f = createTempDir();
223
224         String JavaDoc what = pRequest.getParameter("what");
225
226         boolean forward = false;
227         try {
228             if ("compile".equals(what)) {
229                 try {
230                     doCompile(isValidating, f, url, pResponse);
231                 } catch (ServletException JavaDoc e) {
232                     pRequest.setAttribute("error", e);
233                     forward = true;
234                 }
235             } else if ("validate".equals(what)) {
236                 doValidate(isValidating, f, url, pResponse);
237                 pRequest.setAttribute("success", Boolean.TRUE);
238                 forward = true;
239             } else {
240                 throw new ServletException JavaDoc("You must choose a proper action: Either 'compile' or 'validate'.");
241             }
242
243             f = null;
244         } finally {
245             if (f != null) { try { removeDirectory(f); } catch (Throwable JavaDoc ignore) {} }
246         }
247
248         if (forward) {
249             pRequest.getRequestDispatcher("index.jsp").forward(pRequest, pResponse);
250         }
251     }
252
253     public void doPost(HttpServletRequest JavaDoc pRequest, HttpServletResponse JavaDoc pResponse)
254             throws ServletException JavaDoc, IOException JavaDoc {
255         // No actual difference between GET and POST ...
256
doGet(pRequest, pResponse);
257     }
258 }
259
Popular Tags