KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > webapp > admin > valve > ValveUtil


1 /*
2  * Copyright 2001-2002,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.webapp.admin.valve;
18
19 import java.net.URLEncoder JavaDoc;
20 import java.util.ArrayList JavaDoc;
21 import java.util.Iterator JavaDoc;
22 import java.util.Locale JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.util.regex.Pattern JavaDoc;
25 import java.util.regex.PatternSyntaxException JavaDoc;
26 import javax.management.Attribute JavaDoc;
27 import javax.management.MBeanServer JavaDoc;
28 import javax.management.MBeanServerFactory JavaDoc;
29 import javax.management.QueryExp JavaDoc;
30 import javax.management.Query JavaDoc;
31 import javax.management.ObjectInstance JavaDoc;
32 import javax.management.ObjectName JavaDoc;
33 import javax.management.JMException JavaDoc;
34 import javax.servlet.ServletException JavaDoc;
35 import javax.servlet.http.HttpServletRequest JavaDoc;
36 import javax.servlet.http.HttpServletResponse JavaDoc;
37 import javax.servlet.http.HttpSession JavaDoc;
38 import org.apache.struts.Globals;
39 import org.apache.struts.action.Action;
40 import org.apache.struts.action.ActionError;
41 import org.apache.struts.action.ActionErrors;
42 import org.apache.struts.action.ActionForm;
43 import org.apache.struts.action.ActionForward;
44 import org.apache.struts.action.ActionMapping;
45 import org.apache.struts.util.MessageResources;
46 import org.apache.webapp.admin.ApplicationServlet;
47 import org.apache.webapp.admin.TomcatTreeBuilder;
48 import org.apache.webapp.admin.TreeControl;
49 import org.apache.webapp.admin.TreeControlNode;
50
51 /**
52  * A utility class that contains methods common across valves.
53  *
54  * @author Manveen Kaur
55  * @version $Revision: 1.14 $ $Date: 2004/10/18 06:37:55 $
56  */

57
58 public final class ValveUtil {
59     
60     
61     // ----------------------------------------------------- Instance Variables
62

63     /**
64      * Signature for the <code>createStandardValve</code> operation.
65      */

66     private static String JavaDoc createStandardValveTypes[] =
67     { "java.lang.String", // parent
68
};
69     
70     
71     // --------------------------------------------------------- Public Methods
72

73     public static String JavaDoc createValve(String JavaDoc parent, String JavaDoc valveType,
74     HttpServletResponse JavaDoc response, HttpServletRequest JavaDoc request,
75     ActionMapping mapping, ApplicationServlet servlet)
76     throws IOException JavaDoc, ServletException JavaDoc {
77         
78         MessageResources resources = (MessageResources)
79             servlet.getServletContext().getAttribute(Globals.MESSAGES_KEY);
80         HttpSession JavaDoc session = request.getSession();
81         
82         MBeanServer JavaDoc mBServer = null;
83         Locale JavaDoc locale = (Locale JavaDoc) session.getAttribute(Globals.LOCALE_KEY);
84         // Acquire a reference to the MBeanServer containing our MBeans
85
try {
86             mBServer = servlet.getServer();
87         } catch (Throwable JavaDoc t) {
88             throw new ServletException JavaDoc
89             ("Cannot acquire MBeanServer reference", t);
90         }
91         
92         String JavaDoc operation = null;
93         String JavaDoc values[] = null;
94         String JavaDoc vObjectName = null;
95         
96         try {
97             
98             String JavaDoc objectName = ValveUtil.getObjectName(parent,
99             TomcatTreeBuilder.VALVE_TYPE);
100                         
101             String JavaDoc parentNodeName = parent;
102             ObjectName JavaDoc pname = new ObjectName JavaDoc(parent);
103             StringBuffer JavaDoc sb = new StringBuffer JavaDoc(pname.getDomain());
104             
105             // For service, create the corresponding Engine mBean
106
// Parent in this case needs to be the container mBean for the service
107
try {
108                 if ("Service".equalsIgnoreCase(pname.getKeyProperty("type"))) {
109                     sb.append(":type=Engine");
110                     parent = sb.toString();
111                 }
112             } catch (Exception JavaDoc e) {
113                 String JavaDoc message = resources.getMessage("error.engineName.bad",
114                 sb.toString());
115                 servlet.log(message);
116                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
117                 return (null);
118             }
119             // Ensure that the requested valve name is unique
120

121             // TBD -- do we need this check?
122
/*
123             ObjectName oname =
124             new ObjectName(objectName);
125             if (mBServer.isRegistered(oname)) {
126                 ActionErrors errors = new ActionErrors();
127                 errors.add("valveName",
128                     new ActionError("error.valveName.exists"));
129                 String message =
130                     resources.getMessage(locale, "error.valveName.exists", sb.toString());
131                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
132                 return (new ActionForward(mapping.getInput()));
133             }
134             */

135             
136             String JavaDoc domain = pname.getDomain();
137             // Look up our MBeanFactory MBean
138
ObjectName JavaDoc fname = TomcatTreeBuilder.getMBeanFactory();
139             
140             // Create a new StandardValve object
141
values = new String JavaDoc[1];
142             values[0] = parent;
143             
144             operation = "create" + valveType;
145             if ("AccessLogValve".equalsIgnoreCase(valveType))
146                 operation = "createAccessLoggerValve";
147                 
148             vObjectName = (String JavaDoc)
149                         mBServer.invoke(fname, operation, values, createStandardValveTypes);
150             
151             // Add the new Valve to our tree control node
152
TreeControl control = (TreeControl)
153             session.getAttribute("treeControlTest");
154             if (control != null) {
155                 TreeControlNode parentNode = control.findNode(parentNodeName);
156                 if (parentNode != null) {
157                     String JavaDoc nodeLabel =
158                     "Valve for " + parentNode.getLabel();
159                     String JavaDoc encodedName =
160                     URLEncoder.encode(vObjectName,TomcatTreeBuilder.URL_ENCODING);
161                     TreeControlNode childNode =
162                     new TreeControlNode(vObjectName,
163                     "Valve.gif",
164                     nodeLabel,
165                     "EditValve.do?select=" + encodedName +
166                     "&nodeLabel=" + URLEncoder.encode(nodeLabel,TomcatTreeBuilder.URL_ENCODING) +
167                     "&parent=" + URLEncoder.encode(parentNodeName,TomcatTreeBuilder.URL_ENCODING),
168                     "content",
169                     true, domain);
170                     parentNode.addChild(childNode);
171                     // FIXME - force a redisplay
172
} else {
173                     servlet.log
174                     ("Cannot find parent node '" + parentNodeName + "'");
175                 }
176             } else {
177                 servlet.log
178                 ("Cannot find TreeControlNode!");
179             }
180             
181         } catch (Exception JavaDoc e) {
182             
183             servlet.log
184             (resources.getMessage(locale, "users.error.invoke",
185             operation), e);
186             response.sendError
187             (HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
188             resources.getMessage(locale, "users.error.invoke",
189             operation));
190             return (null);
191             
192         }
193         
194         // Forward to the success reporting page
195
session.removeAttribute(mapping.getAttribute());
196         return vObjectName;
197     }
198
199     
200     /**
201      * Return an array of regular expression objects initialized from the
202      * specified argument, which must be <code>null</code> or a comma-delimited
203      * list of regular expression patterns.
204      *
205      * @param list The comma-separated list of patterns
206      *
207      * @exception IllegalArgumentException if one of the patterns has
208      * invalid syntax
209      */

210     public static Pattern JavaDoc[] precalculate(String JavaDoc list)
211                                     throws IllegalArgumentException JavaDoc {
212
213         if (list == null)
214             return (new Pattern JavaDoc[0]);
215         list = list.trim();
216         if (list.length() < 1)
217             return (new Pattern JavaDoc[0]);
218         list += ",";
219
220         ArrayList JavaDoc reList = new ArrayList JavaDoc();
221         while (list.length() > 0) {
222             int comma = list.indexOf(',');
223             if (comma < 0)
224                 break;
225             String JavaDoc pattern = list.substring(0, comma).trim();
226             try {
227                 reList.add(Pattern.compile(pattern));
228             } catch (PatternSyntaxException JavaDoc e) {
229                 throw new IllegalArgumentException JavaDoc
230                     ("Syntax error in request filter pattern");
231             }
232             list = list.substring(comma + 1);
233         }
234
235         Pattern JavaDoc reArray[] = new Pattern JavaDoc[reList.size()];
236         return ((Pattern JavaDoc[]) reList.toArray(reArray));
237
238     }
239
240     public static String JavaDoc getObjectName(String JavaDoc parent, String JavaDoc MBeanType)
241     throws Exception JavaDoc{
242         
243         // Form the pattern that gets the logger for this particular
244
// service, host or context.
245
ObjectName JavaDoc poname = new ObjectName JavaDoc(parent);
246         String JavaDoc domain = poname.getDomain();
247         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(domain+MBeanType);
248         String JavaDoc type = poname.getKeyProperty("type");
249         String JavaDoc j2eeType = poname.getKeyProperty("j2eeType");
250         String JavaDoc path = "";
251         String JavaDoc host = "";
252         String JavaDoc name = poname.getKeyProperty("name");
253         if ((name != null) && (name.length() > 0)) {
254             name = name.substring(2);
255             int i = name.indexOf("/");
256             host = name.substring(0,i);
257             path = name.substring(i);
258         }
259         if ("WebModule".equalsIgnoreCase(j2eeType)) { // container is context
260
sb.append(",path="+path);
261             sb.append(",host="+host);
262         }
263         if ("Host".equalsIgnoreCase(type)) { // container is host
264
sb.append(",host=");
265             sb.append(poname.getKeyProperty("host"));
266         }
267         if ("Service".equalsIgnoreCase(type)) { // container is service
268
}
269         return sb.toString();
270     }
271
272 }
273
Popular Tags