KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > oc4j > util > OC4JPluginUtils


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.j2ee.oc4j.util;
21
22 import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
23 import java.io.File JavaDoc;
24 import java.io.FileInputStream JavaDoc;
25 import java.io.FileWriter JavaDoc;
26 import java.io.InputStream JavaDoc;
27 import java.net.MalformedURLException JavaDoc;
28 import java.net.URL JavaDoc;
29 import java.net.URLClassLoader JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import java.util.Collection JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.List JavaDoc;
34 import javax.enterprise.deploy.spi.TargetModuleID JavaDoc;
35 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
36 import javax.xml.xpath.XPath JavaDoc;
37 import javax.xml.xpath.XPathConstants JavaDoc;
38 import javax.xml.xpath.XPathExpression JavaDoc;
39 import javax.xml.xpath.XPathFactory JavaDoc;
40 import org.netbeans.api.db.explorer.DatabaseException;
41 import org.netbeans.api.db.explorer.JDBCDriver;
42 import org.netbeans.api.db.explorer.JDBCDriverManager;
43 import org.netbeans.modules.j2ee.dd.api.web.DDProvider;
44 import org.netbeans.modules.j2ee.dd.api.web.Servlet;
45 import org.netbeans.modules.j2ee.dd.api.web.WebApp;
46 import org.netbeans.modules.j2ee.deployment.plugins.api.InstanceProperties;
47 import org.netbeans.modules.j2ee.oc4j.OC4JDeploymentManager;
48 import org.netbeans.modules.j2ee.oc4j.ide.OC4JErrorManager;
49 import org.netbeans.modules.web.api.webmodule.WebModule;
50 import org.openide.DialogDisplayer;
51 import org.openide.ErrorManager;
52 import org.openide.NotifyDescriptor;
53 import org.openide.filesystems.FileObject;
54 import org.openide.filesystems.FileUtil;
55 import org.w3c.dom.DOMException JavaDoc;
56 import org.w3c.dom.Document JavaDoc;
57 import org.w3c.dom.Element JavaDoc;
58 import org.w3c.dom.Node JavaDoc;
59 import org.w3c.dom.NodeList JavaDoc;
60
61 /**
62  * @author pblaha
63  */

64 public class OC4JPluginUtils {
65     public static final String JavaDoc CONFIG_DIR = File.separator + "j2ee" + File.separator +
66             "home" + File.separator + "config"; // NOI18N
67
public static final String JavaDoc SERVER_XML = CONFIG_DIR + File.separator + "server.xml"; // NOI18N
68
public static final String JavaDoc SYSTEM_JAZN_DATA_XML = CONFIG_DIR + File.separator + "system-jazn-data.xml"; // NOI18N
69

70     //--------------- checking for possible server directory -------------
71
private static Collection JavaDoc <String JavaDoc> fileRequired = new java.util.ArrayList JavaDoc<String JavaDoc>();
72     
73     static {
74         fileRequired.add("bin/oc4j"); // NOI18N
75
fileRequired.add("bin/oc4j.cmd"); // NOI18N
76
fileRequired.add("j2ee/home/config"); // NOI18N
77
fileRequired.add("j2ee/home/config/server.xml"); // NOI18N
78
fileRequired.add("j2ee/home/config/default-web-site.xml"); // NOI18N
79
}
80     
81     public static boolean isGoodOC4JHomeLocation(File JavaDoc candidate){
82         OC4JDebug.log("org.netbeans.modules.j2ee.oc4j.util.OC4JPluginUtils", "Check location for: " + candidate);
83         if (null == candidate ||
84                 !candidate.exists() ||
85                 !candidate.canRead() ||
86                 !candidate.isDirectory() ||
87                 !hasRequiredChildren(candidate, fileRequired))
88             return false;
89         OC4JDebug.log("org.netbeans.modules.j2ee.oc4j.util.OC4JPluginUtils", "Location is OK");
90         return true;
91     }
92     
93     public static boolean isLocalServer(InstanceProperties ip) {
94         String JavaDoc host = ip.getProperty(OC4JPluginProperties.PROPERTY_HOST);
95         
96         if(host != null && host.equals("localhost"))
97             return true;
98         
99         return false;
100     }
101     
102     private static boolean hasRequiredChildren(File JavaDoc candidate, Collection JavaDoc <String JavaDoc> requiredChildren) {
103         if (null == candidate)
104             return false;
105         String JavaDoc[] children = candidate.list();
106         if (null == children)
107             return false;
108         if (null == requiredChildren)
109             return true;
110         Iterator JavaDoc iter = requiredChildren.iterator();
111         while (iter.hasNext()){
112             String JavaDoc next = (String JavaDoc)iter.next();
113             File JavaDoc test = new File JavaDoc(candidate.getPath()+File.separator+next);
114             if (!test.exists())
115                 return false;
116         }
117         return true;
118     }
119     
120     public static int getHttpPort(String JavaDoc oc4jHomeLocal, String JavaDoc webSite) {
121         int httpPort = 8888;
122         InputStream JavaDoc inputStream = null;
123         Document JavaDoc document = null;
124         String JavaDoc webSiteFilePath = "";
125         
126         for (Iterator JavaDoc<String JavaDoc> it = getPathForElement(oc4jHomeLocal, "web-site").iterator(); it.hasNext();) { // NOI18N
127
String JavaDoc webSitePath = it.next();
128             String JavaDoc webSiteName = webSitePath.substring( webSitePath.lastIndexOf(File.separatorChar) + 1, webSitePath.indexOf("-web-site.xml")); // NOI18N
129
if(webSiteName.equals(webSite))
130                 webSiteFilePath = webSitePath;
131         }
132         
133         if(OC4JDebug.isEnabled()) {
134             OC4JDebug.log("org.netbeans.modules.j2ee.oc4j.util.OC4JPluginUtils", webSite);
135         }
136         File JavaDoc webSiteFile = new File JavaDoc(webSiteFilePath);
137         if(OC4JDebug.isEnabled()) {
138             OC4JDebug.log("org.netbeans.modules.j2ee.oc4j.util.OC4JPluginUtils", webSiteFile.getAbsolutePath());
139         }
140         try {
141             inputStream = new FileInputStream JavaDoc(webSiteFile);
142             document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
143             Element JavaDoc rootElement = document.getDocumentElement();
144             httpPort = Integer.parseInt(rootElement.getAttributes().getNamedItem("port").getNodeValue()); // NOI18N
145
} catch(Exception JavaDoc ex) {
146             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
147         }
148         return httpPort;
149     }
150     
151     public static String JavaDoc getHttpPort(String JavaDoc instanceURL) {
152         InstanceProperties ip = InstanceProperties.getInstanceProperties(instanceURL);
153         return ip.getProperty(InstanceProperties.HTTP_PORT_NUMBER);
154     }
155     
156     public static int getAdminPort(String JavaDoc oc4jHomeLocal) {
157         int adminPort = 23791;
158         InputStream JavaDoc inputStream = null;
159         Document JavaDoc document = null;
160         String JavaDoc rmiFilePath = getPathForElement(oc4jHomeLocal, "rmi-config").iterator().next();
161         File JavaDoc rmiFile = new File JavaDoc(rmiFilePath);
162         try {
163             inputStream = new FileInputStream JavaDoc(rmiFile);
164             document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
165             Element JavaDoc rootElement = document.getDocumentElement();
166             adminPort = Integer.parseInt(rootElement.getAttributes().getNamedItem("port").getNodeValue()); // NOI18N
167
} catch(Exception JavaDoc ex) {
168             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
169         }
170         return adminPort;
171     }
172     
173     public static Collection JavaDoc<String JavaDoc> getWebSites(String JavaDoc oc4jHomeLocal) {
174         ArrayList JavaDoc<String JavaDoc> webSiteNames = new ArrayList JavaDoc<String JavaDoc>();
175         for(String JavaDoc webSite : getPathForElement(oc4jHomeLocal, "web-site")) { //NOI18N
176
webSiteNames.add(webSite.substring(webSite.lastIndexOf(File.separatorChar) + 1, webSite.indexOf("-web-site.xml"))); //NOI18N
177
}
178         return webSiteNames;
179     }
180     
181     public static Collection JavaDoc<String JavaDoc> getUsers(String JavaDoc oc4jHomeLocal) {
182         ArrayList JavaDoc<String JavaDoc> users = new ArrayList JavaDoc<String JavaDoc>();
183         File JavaDoc xmlFile = new File JavaDoc(oc4jHomeLocal + File.separator + SYSTEM_JAZN_DATA_XML);
184         
185         try {
186             XPathFactory JavaDoc factory = XPathFactory.newInstance();
187             XPath JavaDoc xpath = factory.newXPath();
188             
189             InputStream JavaDoc inputStream = new FileInputStream JavaDoc(xmlFile);
190             Document JavaDoc document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
191             
192             XPathExpression JavaDoc expr = xpath.compile("//role[name='oc4j-administrators']/members/member/name/text()");
193             
194             NodeList JavaDoc nodes = (NodeList JavaDoc) expr.evaluate(document, XPathConstants.NODESET);
195             
196             for(int i=0;i<nodes.getLength();i++)
197                 users.add(nodes.item(i).getNodeValue());
198         } catch(Exception JavaDoc ex) {
199             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
200         }
201         
202         return users;
203     }
204     
205     public static boolean isUserActivated(String JavaDoc oc4jHomeLocal, String JavaDoc user) {
206         File JavaDoc xmlFile = new File JavaDoc(oc4jHomeLocal + File.separator + SYSTEM_JAZN_DATA_XML);
207         
208         try {
209             XPathFactory JavaDoc factory = XPathFactory.newInstance();
210             XPath JavaDoc xpath = factory.newXPath();
211             
212             InputStream JavaDoc inputStream = new FileInputStream JavaDoc(xmlFile);
213             Document JavaDoc document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
214             
215             XPathExpression JavaDoc expr = xpath.compile("//user[name='"+user+"']");
216             
217             Node JavaDoc node = (Node JavaDoc) expr.evaluate(document, XPathConstants.NODE);
218             
219             if (node.getAttributes().getNamedItem("deactivated") != null)
220                 return false;
221             
222             return true;
223         } catch(Exception JavaDoc ex) {
224             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
225         }
226         
227         return false;
228     }
229     
230     public static boolean activateUser(String JavaDoc oc4jHomeLocal, String JavaDoc user, String JavaDoc password) {
231         File JavaDoc xmlFile = new File JavaDoc(oc4jHomeLocal + File.separator + SYSTEM_JAZN_DATA_XML);
232         
233         try {
234             XPathFactory JavaDoc factory = XPathFactory.newInstance();
235             XPath JavaDoc xpath = factory.newXPath();
236             
237             InputStream JavaDoc inputStream = new FileInputStream JavaDoc(xmlFile);
238             Document JavaDoc document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
239             
240             XPathExpression JavaDoc exprActivate = xpath.compile("//user[name='"+user+"']");
241             XPathExpression JavaDoc exprPassword = xpath.compile("//user[name='"+user+"']/credentials/text()");
242             
243             Node JavaDoc nodeActivate = (Node JavaDoc) exprActivate.evaluate(document, XPathConstants.NODE);
244             Node JavaDoc nodePassword = (Node JavaDoc) exprPassword.evaluate(document, XPathConstants.NODE);
245             
246             if(nodeActivate != null) {
247                 try {
248                     nodeActivate.getAttributes().removeNamedItem("deactivated");
249                 } catch(DOMException JavaDoc e) {
250                     // Nothing to do
251
}
252             }
253             
254             if(nodePassword != null) {
255                 try {
256                     nodePassword.setNodeValue("!"+password);
257                 } catch(DOMException JavaDoc e) {
258                     return false;
259                 }
260             }
261             
262             XMLSerializer serializer = new XMLSerializer();
263             serializer.setOutputCharStream(new FileWriter JavaDoc(xmlFile));
264             serializer.serialize(document);
265             
266             return true;
267         } catch(Exception JavaDoc ex) {
268             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
269         }
270         
271         return false;
272     }
273     
274     public static String JavaDoc requestPassword(String JavaDoc user) {
275         OC4JPasswordInputDialog d = new OC4JPasswordInputDialog(user);
276         
277         if(DialogDisplayer.getDefault().notify(d) == NotifyDescriptor.OK_OPTION) {
278             return d.getPassword();
279         }
280         
281         return null;
282     }
283     
284     static Collection JavaDoc<String JavaDoc> getPathForElement(String JavaDoc oc4jHomeLocal, String JavaDoc element) {
285         InputStream JavaDoc inputStream = null;
286         Document JavaDoc document = null;
287         ArrayList JavaDoc<String JavaDoc> paths = new ArrayList JavaDoc<String JavaDoc>();
288         File JavaDoc xmlFile = new File JavaDoc(oc4jHomeLocal + File.separator + SERVER_XML);
289         try{
290             inputStream = new FileInputStream JavaDoc(xmlFile);
291             document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
292             NodeList JavaDoc elementsList = document.getElementsByTagName(element);
293             if(elementsList.getLength() == 0) {
294                 return paths;
295             } else {
296                 for(int i = 0; i < elementsList.getLength(); i++) {
297                     Node JavaDoc pathAttr = elementsList.item(i).getAttributes().getNamedItem("path"); // NOI18N
298
String JavaDoc path = pathAttr.getNodeValue();
299                     if(path.startsWith("./")) {
300                         paths.add(oc4jHomeLocal + CONFIG_DIR + File.separator + path.substring(2));
301                     } else {
302                         paths.add(path);
303                     }
304                 }
305             }
306         }catch(Exception JavaDoc e){
307             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
308         }
309         return paths;
310     }
311     
312     public static String JavaDoc getName(TargetModuleID JavaDoc module) {
313         String JavaDoc s = module.toString();
314         s = s.substring(s.indexOf("name=")+5);
315         
316         return s.substring(0, (s.indexOf(".") == -1)?(s.indexOf(",")):(s.indexOf(".")));
317     }
318     
319     public static String JavaDoc getServerRoot(String JavaDoc instanceURL) {
320         InstanceProperties ip = InstanceProperties.getInstanceProperties(instanceURL);
321         String JavaDoc serverRoot = ip.getProperty(OC4JPluginProperties.PROPERTY_OC4J_HOME);
322         
323         return serverRoot;
324     }
325     
326     public static String JavaDoc getHostname(String JavaDoc instanceURL) {
327         InstanceProperties ip = InstanceProperties.getInstanceProperties(instanceURL);
328         return ip.getProperty(OC4JPluginProperties.PROPERTY_HOST);
329     }
330     
331     public static void registerOracleJdbcDriver(String JavaDoc serverRoot) {
332         if(serverRoot == null)
333             return;
334         
335         List JavaDoc<URL JavaDoc> list = new ArrayList JavaDoc<URL JavaDoc>();
336         File JavaDoc serverDir = new File JavaDoc(serverRoot);
337         
338         try{
339             for(File JavaDoc file:new File JavaDoc(serverDir, "jdbc/lib").listFiles()) {
340                 if(FileUtil.isArchiveFile(file.toURI().toURL()))
341                     list.add(fileToUrl(file));
342             }
343         } catch(MalformedURLException JavaDoc ex) {
344             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
345         }
346         
347         URL JavaDoc[] urls = list.toArray(new URL JavaDoc[list.size()]);
348         String JavaDoc name = "Oracle";
349         String JavaDoc clazz = "oracle.jdbc.driver.OracleDriver";
350         
351         JDBCDriver driver = JDBCDriver.create(name, name, clazz, urls);
352         
353         if(JDBCDriverManager.getDefault().getDrivers(clazz).length == 0) {
354             try {
355                 JDBCDriverManager.getDefault().addDriver(driver);
356             } catch(DatabaseException e) {
357                 // Nothing to do
358
}
359         }
360     }
361     
362     public static URL JavaDoc fileToUrl(File JavaDoc file) throws MalformedURLException JavaDoc {
363         URL JavaDoc url = file.toURI().toURL();
364         if (FileUtil.isArchiveFile(url)) {
365             url = FileUtil.getArchiveRoot(url);
366         }
367         return url;
368     }
369     
370     public static boolean checkClass(String JavaDoc clazz, OC4JDeploymentManager dm) {
371         // Creating a class loader to check if there is a driver on the server
372
List JavaDoc<URL JavaDoc> l = dm.getProperties().getClasses();
373         URL JavaDoc[] urls = l.toArray(new URL JavaDoc[] {});
374         ClassLoader JavaDoc c = new URLClassLoader JavaDoc(urls);
375         
376         // Driver check
377
try {
378             Class.forName(clazz, true, c);
379         } catch (ClassNotFoundException JavaDoc e) {
380             OC4JErrorManager.getInstance(dm).error(clazz, e, OC4JErrorManager.GENERIC_FAILURE);
381             return false;
382         }
383         
384         return true;
385     }
386     
387     public static boolean isJSFInWebModule(WebModule wm) {
388         // The JavaEE 5 introduce web modules without deployment descriptor. In such wm can not be jsf used.
389
FileObject dd = wm.getDeploymentDescriptor();
390         return (dd != null && getActionServlet(dd) != null);
391     }
392     
393     public static Servlet getActionServlet(FileObject dd) {
394         if (dd == null) {
395             return null;
396         }
397         try {
398             WebApp webApp = DDProvider.getDefault().getDDRoot(dd);
399             
400             // Try to find according the servlet class name. The javax.faces.webapp.FacesServlet is final, so
401
// it can not be extended.
402
return (Servlet) webApp
403                     .findBeanByName("Servlet", "ServletClass", "javax.faces.webapp.FacesServlet"); //NOI18N;
404
} catch (java.io.IOException JavaDoc e) {
405             return null;
406         }
407     }
408 }
Popular Tags