KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > webapp > servlet > IFrameContentLoaderServlet


1 /*
2  * Copyright 2004 Blandware (http://www.blandware.com)
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 package com.blandware.atleap.webapp.servlet;
17
18 import com.blandware.atleap.common.Constants;
19 import com.blandware.atleap.common.util.ConvertUtil;
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22 import org.apache.oro.text.regex.MalformedPatternException;
23 import org.apache.oro.text.regex.MatchResult;
24 import org.apache.oro.text.regex.Pattern;
25 import org.apache.oro.text.regex.Perl5Compiler;
26 import org.apache.oro.text.regex.Perl5Matcher;
27 import org.apache.struts.util.RequestUtils;
28
29 import javax.servlet.ServletConfig JavaDoc;
30 import javax.servlet.ServletException JavaDoc;
31 import javax.servlet.http.HttpServlet JavaDoc;
32 import javax.servlet.http.HttpServletRequest JavaDoc;
33 import javax.servlet.http.HttpServletResponse JavaDoc;
34 import java.io.IOException JavaDoc;
35 import java.io.OutputStream JavaDoc;
36
37 /**
38  * <p>Retrieves plain text or HTML content from session by attribute, specified as request parameter <code>var</code> and writes it into response</p>
39  * <p>Content-type can be specified as request parameter <code>type</code>. Valid values for <code>type</code> are <code>text/html</code> (by default) and <code>text/plain</code></p>
40  * <p>Note that this servlet will correctly work with two types of HTML content: well-formed HTML or XHTML (with HTML, HEAD and BODY tags) and
41  * piece of text, which will be wrapped with &lt;body&gt;&lt;/body&gt; and &lt;html&gt;&lt;/html&gt; Also head section will be created with &lt;base /&gt;
42  * and &lt;meta http=equiv="Content-Type" content="text/html; charset=utf-8"/&gt; presented. <code>Href</code> attribute will contain current scheme, host, port and context path.
43  * <p><a HREF="IFrameContentLoaderServlet.java.htm"><i>View Source</i></a></p>
44  *
45  * @author Sergey Zubtcovskii <a HREF="mailto:sergey.zubtcovskii@blandware.com">&lt;sergey.zubtcovskii@blandware.com&gt;</a>
46  * @version $Revision: 1.1 $ $Date: 2005/07/02 18:19:15 $
47  * @web.servlet name="iframeContentLoader" load-on-startup="3"
48  * @web.servlet-mapping url-pattern="/servlet/iframeContentLoader/*"
49  */

50 public class IFrameContentLoaderServlet extends HttpServlet JavaDoc {
51
52
53     /**
54      * Commons Logging instance.
55      */

56     protected transient final Log log = LogFactory.getLog(IFrameContentLoaderServlet.class);
57
58     /**
59      * Initializes the servlet.
60      */

61     public void init(ServletConfig JavaDoc config) throws ServletException JavaDoc {
62         super.init(config);
63     }
64
65     /**
66      * Destroys the servlet.
67      */

68     public void destroy() {
69
70     }
71
72     /**
73      * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
74      *
75      * @param request servlet request
76      * @param response servlet response
77      */

78     protected void processRequest(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
79             throws ServletException JavaDoc, IOException JavaDoc {
80
81         String JavaDoc contentType = request.getParameter("type");
82         if ( !Constants.MIME_TYPE_PLAIN.equals(contentType) && !Constants.MIME_TYPE_HTML.equals(contentType) ) {
83             contentType = Constants.MIME_TYPE_HTML;
84         }
85
86         String JavaDoc var = request.getParameter("var");
87         if ( var != null && var.length() != 0 && request.getSession().getAttribute(var) != null ) {
88             StringBuffer JavaDoc content = new StringBuffer JavaDoc((String JavaDoc) request.getSession().getAttribute(var));
89             request.getSession().removeAttribute(var);
90
91             if ( Constants.MIME_TYPE_HTML.equals(contentType) ) {
92
93                 Perl5Compiler compiler = new Perl5Compiler();
94                 Perl5Matcher matcher = new Perl5Matcher();
95                 Pattern pattern = null;
96
97                 // prepare tags to insert if it will be needed
98
StringBuffer JavaDoc baseHref = RequestUtils.createServerUriStringBuffer(request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath() + "/");
99                 StringBuffer JavaDoc base = new StringBuffer JavaDoc("<base HREF=\"").append(baseHref).append("\" />");
100                 StringBuffer JavaDoc metaCT = new StringBuffer JavaDoc("<meta http-equiv=\"Content-Type\" content=\"").append(contentType).append("; charset=").append(Constants.DEFAULT_ENCODING).append("\" />");
101
102                 int headOpenEndOffset = -1;
103                 String JavaDoc lowerCasedContent = content.toString().toLowerCase();
104
105                 // check HTML tags
106
String JavaDoc htmlOpenRE = "<html[^<>]*>";
107                 pattern = compilePattern(compiler, htmlOpenRE);
108                 if ( matcher.contains(lowerCasedContent, pattern) ) {
109                     // HTML tag is present. We assume, that HEAD tags also present. Search for META and BASE
110
String JavaDoc headOpenRE = "<head[^<>]*>";
111                     pattern = compilePattern(compiler, headOpenRE);
112
113                     if ( matcher.contains(lowerCasedContent, pattern) ) {
114                         // open HEAD tag exists
115
MatchResult result = matcher.getMatch();
116                         headOpenEndOffset = result.endOffset(0);
117
118                         // seach for BASE
119
String JavaDoc baseRE = "<base[^<>]+href=[^<>]+>";
120                         pattern = compilePattern(compiler, baseRE);
121
122                         if ( !matcher.contains(lowerCasedContent, pattern) ) {
123                             // create BASE
124
content.insert(headOpenEndOffset, base);
125                         }
126
127                         // search for META with content-type
128
String JavaDoc metaCTRE = "<meta[^<>]+http-equiv=(\"|\')?content-type(\\1)?[^<>]+>";
129                         pattern = compilePattern(compiler, metaCTRE);
130
131                         if ( !matcher.contains(lowerCasedContent, pattern) ) {
132                             content.insert(headOpenEndOffset, metaCT);
133                         }
134
135                     }
136                 } else {
137                     // HTML open tag does not present
138
content = new StringBuffer JavaDoc("<html>").append("<head>").append(metaCT).append(base)
139                             .append("</head>").append("<body>").append(content).append("</body>").append("</html>");
140                 }
141             }
142             byte[] contentBytes = ConvertUtil.convertToByteArray(content.toString());
143             OutputStream JavaDoc out = response.getOutputStream();
144
145             if ( contentType.indexOf("charset") == -1 ) {
146                 contentType += "; charset=" + Constants.DEFAULT_ENCODING;
147             }
148
149             response.setContentType(contentType);
150             response.setContentLength(contentBytes.length);
151             out.write(contentBytes);
152             out.flush();
153             out.close();
154         }
155     }
156
157     /**
158      * Compiles given regular expression and wraps any exception occured in ServletException
159      *
160      * @param compiler Compiler to use for compiling pattern
161      * @param regex Regular expression to compile
162      * @return Compiled pattern
163      * @throws ServletException if any error occurs during compilation, e.g. pattern is malformed
164      */

165     protected Pattern compilePattern(Perl5Compiler compiler, String JavaDoc regex) throws ServletException JavaDoc {
166         try {
167             Pattern pattern = compiler.compile(regex);
168             return pattern;
169         } catch ( MalformedPatternException e ) {
170             throw new ServletException JavaDoc(e);
171         }
172     }
173
174     /**
175      * Handles the HTTP <code>GET</code> method.
176      *
177      * @param request servlet request
178      * @param response servlet response
179      */

180     protected void doGet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
181             throws ServletException JavaDoc, IOException JavaDoc {
182         processRequest(request, response);
183     }
184
185     /**
186      * Handles the HTTP <code>POST</code> method.
187      *
188      * @param request servlet request
189      * @param response servlet response
190      */

191     protected void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
192             throws ServletException JavaDoc, IOException JavaDoc {
193         processRequest(request, response);
194     }
195
196     /**
197      * Returns a short description of the servlet.
198      */

199     public String JavaDoc getServletInfo() {
200         return "Servlet to load content for iframe";
201     }
202
203 }
Popular Tags