PageRenderTime 56ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/projects/netbeans-7.3/web.jsf/src/org/netbeans/modules/web/jsf/JSFFrameworkProvider.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 804 lines | 611 code | 60 blank | 133 comment | 209 complexity | 543eedede5fe6cea23365b18e1fabb28 MD5 | raw file
  1. /*
  2. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
  3. *
  4. * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
  5. *
  6. * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
  7. * Other names may be trademarks of their respective owners.
  8. *
  9. * The contents of this file are subject to the terms of either the GNU
  10. * General Public License Version 2 only ("GPL") or the Common
  11. * Development and Distribution License("CDDL") (collectively, the
  12. * "License"). You may not use this file except in compliance with the
  13. * License. You can obtain a copy of the License at
  14. * http://www.netbeans.org/cddl-gplv2.html
  15. * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
  16. * specific language governing permissions and limitations under the
  17. * License. When distributing the software, include this License Header
  18. * Notice in each file and include the License file at
  19. * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
  20. * particular file as subject to the "Classpath" exception as provided
  21. * by Oracle in the GPL Version 2 section of the License file that
  22. * accompanied this code. If applicable, add the following below the
  23. * License Header, with the fields enclosed by brackets [] replaced by
  24. * your own identifying information:
  25. * "Portions Copyrighted [year] [name of copyright owner]"
  26. *
  27. * Contributor(s):
  28. *
  29. * The Original Software is NetBeans. The Initial Developer of the Original
  30. * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
  31. * Microsystems, Inc. All Rights Reserved.
  32. *
  33. * If you wish your version of this file to be governed by only the CDDL
  34. * or only the GPL Version 2, indicate your decision by adding
  35. * "[Contributor] elects to include this software in this distribution
  36. * under the [CDDL or GPL Version 2] license." If you do not indicate a
  37. * single choice of license, a recipient has the option to distribute
  38. * your version of this file under either the CDDL, the GPL Version 2 or
  39. * to extend the choice of license to its licensees as provided above.
  40. * However, if you add GPL Version 2 code and therefore, elected the GPL
  41. * Version 2 license, then the option applies only if the new code is
  42. * made subject to such option by the copyright holder.
  43. */
  44. package org.netbeans.modules.web.jsf;
  45. import java.io.BufferedReader;
  46. import java.io.BufferedWriter;
  47. import java.io.File;
  48. import java.io.IOException;
  49. import java.io.InputStream;
  50. import java.io.InputStreamReader;
  51. import java.io.OutputStreamWriter;
  52. import java.math.BigInteger;
  53. import java.net.URL;
  54. import java.nio.charset.Charset;
  55. import java.util.ArrayList;
  56. import java.util.HashMap;
  57. import java.util.HashSet;
  58. import java.util.List;
  59. import java.util.Set;
  60. import java.util.TreeMap;
  61. import java.util.logging.Level;
  62. import java.util.logging.Logger;
  63. import java.util.prefs.Preferences;
  64. import javax.swing.SwingUtilities;
  65. import org.netbeans.api.j2ee.core.Profile;
  66. import org.netbeans.api.java.classpath.ClassPath;
  67. import org.netbeans.api.java.project.classpath.ProjectClassPathModifier;
  68. import org.netbeans.api.project.FileOwnerQuery;
  69. import org.netbeans.api.project.Project;
  70. import org.netbeans.api.project.ProjectUtils;
  71. import org.netbeans.modules.j2ee.dd.api.web.*;
  72. import org.netbeans.modules.j2ee.deployment.devmodules.api.InstanceRemovedException;
  73. import org.netbeans.modules.web.jsf.api.ConfigurationUtils;
  74. import org.netbeans.modules.web.jsf.wizards.JSFConfigurationPanel;
  75. import org.openide.DialogDescriptor;
  76. import org.openide.filesystems.FileObject;
  77. import org.openide.filesystems.FileSystem;
  78. import org.openide.filesystems.FileUtil;
  79. import org.openide.filesystems.FileLock;
  80. import org.netbeans.api.project.libraries.Library;
  81. import org.netbeans.api.project.libraries.LibraryManager;
  82. import org.netbeans.api.queries.FileEncodingQuery;
  83. import org.netbeans.modules.j2ee.common.Util;
  84. import org.netbeans.modules.j2ee.common.dd.DDHelper;
  85. import org.netbeans.modules.j2ee.common.ui.BrokenServerLibrarySupport;
  86. import org.netbeans.modules.j2ee.dd.api.common.InitParam;
  87. import org.netbeans.modules.j2ee.deployment.common.api.ConfigurationException;
  88. import org.netbeans.modules.j2ee.deployment.common.api.Version;
  89. import org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment;
  90. import org.netbeans.modules.j2ee.deployment.devmodules.spi.J2eeModuleProvider;
  91. import org.netbeans.modules.j2ee.deployment.plugins.api.ServerLibrary;
  92. import org.netbeans.modules.j2ee.deployment.plugins.api.ServerLibraryDependency;
  93. import org.netbeans.modules.web.api.webmodule.ExtenderController;
  94. import org.netbeans.modules.web.spi.webmodule.WebFrameworkProvider;
  95. import org.netbeans.modules.web.api.webmodule.WebModule;
  96. import org.netbeans.modules.web.jsf.api.facesmodel.Application;
  97. import org.netbeans.modules.web.jsf.api.facesmodel.FacesConfig;
  98. import org.netbeans.modules.web.jsf.api.facesmodel.JSFConfigModel;
  99. import org.netbeans.modules.web.jsf.api.facesmodel.ViewHandler;
  100. import org.netbeans.modules.web.jsf.palette.JSFPaletteUtilities;
  101. import org.netbeans.modules.web.jsf.spi.components.JsfComponentCustomizer;
  102. import org.netbeans.modules.web.jsf.spi.components.JsfComponentImplementation;
  103. import org.netbeans.modules.web.project.api.WebPropertyEvaluator;
  104. import org.netbeans.modules.web.spi.webmodule.WebModuleExtender;
  105. import org.openide.DialogDisplayer;
  106. import org.openide.NotifyDescriptor;
  107. import org.openide.loaders.DataObject;
  108. import org.openide.text.DataEditorSupport;
  109. import org.openide.util.Exceptions;
  110. import org.openide.util.NbBundle;
  111. /**
  112. *
  113. * @author Petr Pisl, Po-Ting Wu, Alexey Butenko
  114. */
  115. public class JSFFrameworkProvider extends WebFrameworkProvider {
  116. private static final Logger LOGGER = Logger.getLogger(JSFFrameworkProvider.class.getName());
  117. private static String HANDLER = "com.sun.facelets.FaceletViewHandler"; //NOI18N
  118. private static final String PREFERRED_LANGUAGE="jsf.language"; //NOI18N
  119. private static final String J2EE_SERVER_INSTANCE = "j2ee.server.instance"; //NOI18N
  120. private static String WELCOME_JSF = "welcomeJSF.jsp"; //NOI18N
  121. private static String WELCOME_XHTML = "index.xhtml"; //NOI18N
  122. private static String WELCOME_XHTML_TEMPLATE = "/Templates/JSP_Servlet/JSP.xhtml"; //NOI18N
  123. private static String TEMPLATE_XHTML = "template.xhtml"; //NOI18N
  124. private static String TEMPLATE_XHTML2 = "template-jsf2.xhtml"; //NOI18N
  125. private static String CSS_FOLDER = "css"; //NOI18N
  126. private static String CSS_FOLDER2 = "resources/css"; //NOI18N
  127. private static String DEFAULT_CSS = "default.css"; //NOI18N
  128. private static String FORWARD_JSF = "forwardToJSF.jsp"; //NOI18N
  129. private static String RESOURCE_FOLDER = "/org/netbeans/modules/web/jsf/resources/"; //NOI18N
  130. private static String FL_RESOURCE_FOLDER = "org/netbeans/modules/web/jsf/facelets/resources/templates/"; //NOI18N
  131. private static String DEFAULT_MAPPING = "/faces/*"; //NOI18N
  132. private boolean createWelcome = true;
  133. public void setCreateWelcome(boolean set) {
  134. createWelcome = set;
  135. }
  136. private JSFConfigurationPanel panel;
  137. /** Creates a new instance of JSFFrameworkProvider */
  138. public JSFFrameworkProvider() {
  139. super(
  140. NbBundle.getMessage(JSFFrameworkProvider.class, "JSF_Name"), // NOI18N
  141. NbBundle.getMessage(JSFFrameworkProvider.class, "JSF_Description")); //NOI18N
  142. }
  143. // not named extend() so as to avoid implementing WebFrameworkProvider.extend()
  144. // better to move this to JSFConfigurationPanel
  145. public Set extendImpl(WebModule webModule, TreeMap<String, JsfComponentCustomizer> jsfComponentCustomizers) {
  146. Set result = new HashSet();
  147. Library jsfLibrary = null;
  148. Library jstlLibrary = null;
  149. JSFConfigurationPanel.LibraryType libraryType = panel.getLibraryType();
  150. if (libraryType == JSFConfigurationPanel.LibraryType.NEW) {
  151. // create new jsf library
  152. String libraryName = panel.getNewLibraryName();
  153. File installResource = panel.getInstallResource();
  154. if (installResource != null && libraryName != null) {
  155. try {
  156. JSFUtils.createJSFUserLibrary(installResource, libraryName);
  157. jsfLibrary = LibraryManager.getDefault().getLibrary(libraryName);
  158. } catch (IOException exception) {
  159. LOGGER.log(Level.WARNING, "Exception during extending an web project", exception); //NOI18N
  160. }
  161. }
  162. } else {
  163. if (libraryType == JSFConfigurationPanel.LibraryType.USED) {
  164. //use a selected library
  165. jsfLibrary = panel.getLibrary();
  166. // if the selected library is a default one, add also JSTL library
  167. if (jsfLibrary.getName().equals(JSFUtils.DEFAULT_JSF_1_2_NAME)
  168. || jsfLibrary.getName().equals(JSFUtils.DEFAULT_JSF_2_0_NAME)
  169. || jsfLibrary.getName().equals(JSFUtils.DEFAULT_JSF_1_1_NAME)) {
  170. jstlLibrary = LibraryManager.getDefault().getLibrary(JSFUtils.DEFAULT_JSTL_1_1_NAME);
  171. }
  172. }
  173. }
  174. try {
  175. FileObject fileObject = webModule.getDocumentBase();
  176. FileObject[] javaSources = webModule.getJavaSources();
  177. if (jsfLibrary != null && javaSources.length > 0) {
  178. Library[] libraries;
  179. if (jstlLibrary != null) {
  180. libraries = new Library[]{jsfLibrary, jstlLibrary};
  181. }
  182. else {
  183. libraries = new Library[]{jsfLibrary};
  184. }
  185. // This is a way how to add libraries to the project classpath and
  186. // packed them to the war file by default. classpath/compile_only (for scope provided)
  187. boolean modified = false;
  188. Boolean isMaven = (Boolean)panel.getController().getProperties().getProperty("maven"); //NOI18N
  189. if (isMaven!=null && isMaven.booleanValue()) {
  190. Project prj = FileOwnerQuery.getOwner(webModule.getDocumentBase());
  191. J2eeModuleProvider provider = prj.getLookup().lookup(J2eeModuleProvider.class);
  192. if (provider != null) {
  193. String serverInstanceId = provider.getServerInstanceID();
  194. if ( serverInstanceId == null || "".equals(serverInstanceId) || "DEV-NULL".equals(serverInstanceId)) { //NOI18N
  195. if (!panel.packageJars()) {
  196. //Add to pom with scope provided
  197. ProjectClassPathModifier.addLibraries(libraries, javaSources[0], "classpath/compile_only"); //NOI18N
  198. modified = true;
  199. }
  200. }
  201. }
  202. }
  203. if (!modified) {
  204. ProjectClassPathModifier.addLibraries(libraries, javaSources[0], ClassPath.COMPILE);
  205. }
  206. }
  207. boolean isMyFaces;
  208. if (jsfLibrary != null) {
  209. // find out whether the added library is myfaces jsf implementation
  210. List<URL> content = jsfLibrary.getContent("classpath"); //NOI18N
  211. isMyFaces = Util.containsClass(content, JSFUtils.MYFACES_SPECIFIC_CLASS);
  212. } else {
  213. // find out whether the target server has myfaces jsf implementation on the classpath
  214. ClassPath cp = ClassPath.getClassPath(fileObject, ClassPath.COMPILE);
  215. isMyFaces = cp.findResource(JSFUtils.MYFACES_SPECIFIC_CLASS.replace('.', '/') + ".class") != null; //NOI18N
  216. }
  217. FileObject webInf = webModule.getWebInf();
  218. if (webInf == null) {
  219. webInf = FileUtil.createFolder(webModule.getDocumentBase(), "WEB-INF"); //NOI18N
  220. }
  221. assert webInf != null;
  222. // configure server library
  223. ServerLibrary serverLibrary = panel.getServerLibrary();
  224. if (serverLibrary != null) {
  225. String implementationTitle = serverLibrary.getImplementationTitle();
  226. isMyFaces = implementationTitle != null && implementationTitle.contains("MyFaces"); // NOI18N
  227. Project prj = FileOwnerQuery.getOwner(webInf);
  228. if (prj != null) {
  229. J2eeModuleProvider provider = prj.getLookup().lookup(J2eeModuleProvider.class);
  230. if (provider != null) {
  231. provider.getConfigSupport().configureLibrary(
  232. ServerLibraryDependency.minimalVersion(serverLibrary.getName(),
  233. serverLibrary.getSpecificationVersion(),
  234. serverLibrary.getImplementationVersion()));
  235. Preferences prefs = ProjectUtils.getPreferences(prj, ProjectUtils.class, true);
  236. prefs.put(BrokenServerLibrarySupport.OFFER_LIBRARY_DEPLOYMENT, Boolean.TRUE.toString());
  237. }
  238. }
  239. }
  240. FileSystem fileSystem = webInf.getFileSystem();
  241. fileSystem.runAtomicAction(new CreateFacesConfig(webModule, isMyFaces));
  242. // extending for JSF component libraries
  243. StringBuilder jsfSuitesSB = new StringBuilder();
  244. for (JsfComponentImplementation jsfComponentDescriptor : panel.getEnabledJsfDescriptors()) {
  245. // extend webmodule about the JSF component library
  246. result.addAll(jsfComponentDescriptor.extend(
  247. webModule, jsfComponentCustomizers.get(jsfComponentDescriptor.getName())));
  248. // track JSF suite for USG statistics
  249. jsfSuitesSB.append(jsfComponentDescriptor.getName()).append("|");
  250. }
  251. String statsString = jsfSuitesSB.toString();
  252. if (!statsString.isEmpty()) {
  253. statsString = statsString.substring(0, statsString.length() - 1);
  254. JSFUtils.logUsage(JSFFrameworkProvider.class, "USG_JSF_INCLUDED_SUITE", new Object[]{statsString});
  255. }
  256. FileObject welcomeFile = (panel!=null && panel.isEnableFacelets()) ? webModule.getDocumentBase().getFileObject(WELCOME_XHTML):
  257. webModule.getDocumentBase().getFileObject(WELCOME_JSF);
  258. if (welcomeFile != null) {
  259. result.add(welcomeFile);
  260. }
  261. } catch (IOException exception) {
  262. LOGGER.log(Level.WARNING, "Exception during extending an web project", exception); //NOI18N
  263. } catch (ConfigurationException exception) {
  264. LOGGER.log(Level.WARNING, "Exception during extending an web project", exception); //NOI18N
  265. }
  266. createWelcome = true;
  267. return result;
  268. }
  269. public static String readResource(InputStream is, String encoding) throws IOException {
  270. // read the config from resource first
  271. StringBuffer sbuffer = new StringBuffer();
  272. String lineSep = System.getProperty("line.separator");//NOI18N
  273. BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding));
  274. String line = br.readLine();
  275. while (line != null) {
  276. sbuffer.append(line);
  277. sbuffer.append(lineSep);
  278. line = br.readLine();
  279. }
  280. br.close();
  281. return sbuffer.toString();
  282. }
  283. public java.io.File[] getConfigurationFiles(org.netbeans.modules.web.api.webmodule.WebModule wm) {
  284. // The JavaEE 5 introduce web modules without deployment descriptor. In such wm can not be jsf used.
  285. if (wm != null) {
  286. FileObject dd = wm.getDeploymentDescriptor();
  287. if (dd != null){
  288. FileObject[] filesFO = ConfigurationUtils.getFacesConfigFiles(wm);
  289. File[] files = new File[filesFO.length];
  290. for (int i = 0; i < filesFO.length; i++)
  291. files[i] = FileUtil.toFile(filesFO[i]);
  292. if (files.length > 0)
  293. return files;
  294. }
  295. }
  296. return null;
  297. }
  298. @Override
  299. public WebModuleExtender createWebModuleExtender(WebModule webModule, ExtenderController controller) {
  300. boolean isFrameworkAddition = (webModule == null || !isInWebModule(webModule));
  301. if (webModule != null && webModule.getDocumentBase() != null) {
  302. FileObject docBase = webModule.getDocumentBase();
  303. Project project = FileOwnerQuery.getOwner(docBase);
  304. Preferences preferences = ProjectUtils.getPreferences(project, ProjectUtils.class, true);
  305. if (preferences.get(PREFERRED_LANGUAGE, "").equals("")) { //NOI18N
  306. ClassPath cp = ClassPath.getClassPath(docBase, ClassPath.COMPILE);
  307. boolean faceletsPresent = cp.findResource("com/sun/facelets/Facelet.class") !=null || //NOI18N
  308. cp.findResource("com/sun/faces/facelets/Facelet.class") !=null; //NOI18N
  309. if (faceletsPresent) {
  310. preferences.put(PREFERRED_LANGUAGE, "Facelets"); //NOI18N
  311. }
  312. }
  313. panel = new JSFConfigurationPanel(this, controller, isFrameworkAddition, preferences, webModule);
  314. } else {
  315. if (webModule!=null && webModule.getDocumentBase() == null) {
  316. controller.getProperties().setProperty("NoDocBase", true); //NOI18N
  317. }
  318. panel = new JSFConfigurationPanel(this, controller, isFrameworkAddition);
  319. }
  320. panel.setCreateExamples(createWelcome);
  321. if (!isFrameworkAddition){
  322. // get configuration panel with values from the wm
  323. Servlet servlet = ConfigurationUtils.getFacesServlet(webModule);
  324. if (servlet != null) {
  325. panel.setServletName(servlet.getServletName());
  326. }
  327. String mapping = ConfigurationUtils.getFacesServletMapping(webModule);
  328. if (mapping == null) {
  329. mapping = DEFAULT_MAPPING; //NOI18N
  330. }
  331. panel.setURLPattern(mapping);
  332. FileObject dd = webModule.getDeploymentDescriptor();
  333. panel.setValidateXML(JSFConfigUtilities.validateXML(dd));
  334. panel.setVerifyObjects(JSFConfigUtilities.verifyObjects(dd));
  335. //Facelets
  336. panel.setDebugFacelets(JSFUtils.debugFacelets(dd));
  337. panel.setSkipComments(JSFUtils.skipCommnets(dd));
  338. }
  339. return panel;
  340. }
  341. public boolean isInWebModule(org.netbeans.modules.web.api.webmodule.WebModule webModule) {
  342. // The JavaEE 5 introduce web modules without deployment descriptor. In such wm can not be jsf used.
  343. // FileObject dd = webModule.getDeploymentDescriptor();
  344. // return (dd != null && ConfigurationUtils.getFacesServlet(webModule) != null);
  345. long time = System.currentTimeMillis();
  346. try {
  347. FileObject fo = webModule.getDocumentBase();
  348. if (fo != null) {
  349. return JSFConfigUtilities.hasJsfFramework(fo);
  350. }
  351. return false;
  352. } finally {
  353. LOGGER.log(Level.INFO, "Total time spent="+(System.currentTimeMillis() - time)+" ms");
  354. }
  355. }
  356. public String getServletPath(FileObject file){
  357. String url = null;
  358. if (file == null) return url;
  359. WebModule wm = WebModule.getWebModule(file);
  360. if (wm != null){
  361. url = FileUtil.getRelativePath(wm.getDocumentBase(), file);
  362. if (url == null) {
  363. return null;
  364. }
  365. if (url.charAt(0)!='/')
  366. url = "/" + url;
  367. String mapping = ConfigurationUtils.getFacesServletMapping(wm);
  368. if (mapping != null && !"".equals(mapping)){
  369. if (mapping.endsWith("/*")){
  370. mapping = mapping.substring(0, mapping.length()-2);
  371. url = mapping + url;
  372. }
  373. }
  374. }
  375. return url;
  376. }
  377. public static void createFile(FileObject target, String content, String encoding) throws IOException{
  378. FileLock lock = target.lock();
  379. try {
  380. BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(target.getOutputStream(lock), encoding));
  381. bw.write(content);
  382. bw.close();
  383. } finally {
  384. lock.releaseLock();
  385. }
  386. }
  387. private class CreateFacesConfig implements FileSystem.AtomicAction{
  388. private static final String FACES_SERVLET_CLASS = "javax.faces.webapp.FacesServlet"; //NOI18N
  389. private static final String FACES_SERVLET_NAME = "Faces Servlet"; //NOI18N
  390. private static final String MYFACES_STARTUP_LISTENER_CLASS = "org.apache.myfaces.webapp.StartupServletContextListener";//NOI18N
  391. WebModule webModule;
  392. boolean isMyFaces;
  393. public CreateFacesConfig(WebModule webModule, boolean isMyFaces){
  394. this.webModule = webModule;
  395. this.isMyFaces = isMyFaces;
  396. }
  397. public void run() throws IOException {
  398. // Enter servlet into the deployment descriptor
  399. FileObject dd = webModule.getDeploymentDescriptor();
  400. //we need deployment descriptor, create if null
  401. if(dd==null)
  402. {
  403. dd = DDHelper.createWebXml(webModule.getJ2eeProfile(), webModule.getWebInf());
  404. }
  405. //faces servlet mapping
  406. String facesMapping = panel == null ? DEFAULT_MAPPING : panel.getURLPattern();;//"/*";
  407. boolean isJSF20, isJSF21;
  408. Library jsfLibrary = null;
  409. if (panel.getLibraryType() == JSFConfigurationPanel.LibraryType.USED) {
  410. jsfLibrary = panel.getLibrary();
  411. } else if (panel.getLibraryType() == JSFConfigurationPanel.LibraryType.NEW) {
  412. jsfLibrary = LibraryManager.getDefault().getLibrary(panel.getNewLibraryName());
  413. }
  414. if (jsfLibrary != null) {
  415. List<URL> content = jsfLibrary.getContent("classpath"); //NOI18N
  416. isJSF20 = Util.containsClass(content, JSFUtils.JSF_2_0__API_SPECIFIC_CLASS);
  417. isJSF21 = Util.containsClass(content, JSFUtils.JSF_2_1__API_SPECIFIC_CLASS);
  418. } else {
  419. if (panel.getLibraryType() == JSFConfigurationPanel.LibraryType.SERVER && panel.getServerLibrary() != null) {
  420. isJSF20 = Version.fromJsr277NotationWithFallback("2.0").isBelowOrEqual(
  421. panel.getServerLibrary().getSpecificationVersion());
  422. isJSF21 = Version.fromJsr277NotationWithFallback("2.1").isAboveOrEqual(
  423. panel.getServerLibrary().getSpecificationVersion());
  424. } else {
  425. ClassPath classpath = ClassPath.getClassPath(webModule.getDocumentBase(), ClassPath.COMPILE);
  426. isJSF20 = classpath.findResource(JSFUtils.JSF_2_0__API_SPECIFIC_CLASS.replace('.', '/')+".class")!=null; //NOI18N
  427. isJSF21 = classpath.findResource(JSFUtils.JSF_2_1__API_SPECIFIC_CLASS.replace('.', '/')+".class")!=null; //NOI18N
  428. }
  429. }
  430. WebApp ddRoot = DDProvider.getDefault().getDDRoot(dd);
  431. //Add Faces Servlet and servlet-mapping into web.xml
  432. if (ddRoot != null && ddRoot.getStatus() == WebApp.STATE_VALID) {
  433. boolean shouldAddMappings = shouldAddMappings(webModule);
  434. try{
  435. if (shouldAddMappings || !DEFAULT_MAPPING.equals(facesMapping)) {
  436. boolean servletDefined = false;
  437. Servlet servlet;
  438. if (ConfigurationUtils.getFacesServlet(webModule)!=null) {
  439. servletDefined = true;
  440. }
  441. if (!servletDefined) {
  442. servlet = (Servlet)ddRoot.createBean("Servlet"); //NOI18N
  443. String servletName = (panel == null) ? FACES_SERVLET_NAME : panel.getServletName();
  444. servlet.setServletName(servletName);
  445. servlet.setServletClass(FACES_SERVLET_CLASS);
  446. servlet.setLoadOnStartup(new BigInteger("1"));//NOI18N
  447. ddRoot.addServlet(servlet);
  448. ServletMapping mapping = (ServletMapping)ddRoot.createBean("ServletMapping"); //NOI18N
  449. mapping.setServletName(servletName);//NOI18N
  450. // facesMapping = panel == null ? "faces/*" : panel.getURLPattern();
  451. mapping.setUrlPattern(facesMapping); //NOI18N
  452. ddRoot.addServletMapping(mapping);
  453. }
  454. }
  455. boolean faceletsEnabled = panel.isEnableFacelets();
  456. if (isJSF20 || isJSF21) {
  457. InitParam contextParam = (InitParam) ddRoot.createBean("InitParam"); //NOI18N
  458. contextParam.setParamName(JSFUtils.FACES_PROJECT_STAGE);
  459. contextParam.setParamValue("Development"); //NOI18N
  460. ddRoot.addContextParam(contextParam);
  461. }
  462. if (isMyFaces) {
  463. boolean listenerDefined = false;
  464. Listener listeners[] = ddRoot.getListener();
  465. for (int i = 0; i < listeners.length; i++) {
  466. if (MYFACES_STARTUP_LISTENER_CLASS.equals(listeners[i].getListenerClass().trim())) {
  467. listenerDefined = true;
  468. break;
  469. }
  470. }
  471. if (!listenerDefined) {
  472. Listener facesListener = (Listener) ddRoot.createBean("Listener"); //NOI18N
  473. facesListener.setListenerClass(MYFACES_STARTUP_LISTENER_CLASS);
  474. ddRoot.addListener(facesListener);
  475. }
  476. }
  477. // add welcome file
  478. WelcomeFileList welcomeFiles = ddRoot.getSingleWelcomeFileList();
  479. List<String> welcomeFileList = new ArrayList<String>();
  480. // add the welcome file only if there not any
  481. if (!faceletsEnabled && welcomeFiles == null) {
  482. if (facesMapping.charAt(0) == '/') {
  483. // if the mapping start with '/' (like /faces/*), then the welcome file can be the mapping
  484. if (webModule.getDocumentBase().getFileObject(WELCOME_JSF) != null || createWelcome) {
  485. welcomeFileList.add(ConfigurationUtils.translateURI(facesMapping, WELCOME_JSF));
  486. }
  487. } else {
  488. // if the mapping doesn't start '/' (like *.jsf), then the welcome file has to be
  489. // a helper file, which will foward the request to the right url
  490. welcomeFileList.add(FORWARD_JSF);
  491. //copy forwardToJSF.jsp
  492. if (facesMapping.charAt(0) != '/' && canCreateNewFile(webModule.getDocumentBase(), FORWARD_JSF)) { //NOI18N
  493. String content = readResource(getClass().getResourceAsStream(RESOURCE_FOLDER + FORWARD_JSF), "UTF-8"); //NOI18N
  494. content = content.replace("__FORWARD__", ConfigurationUtils.translateURI(facesMapping, WELCOME_JSF));
  495. Charset encoding = FileEncodingQuery.getDefaultEncoding();
  496. content = content.replaceAll("__ENCODING__", encoding.name());
  497. FileObject target = FileUtil.createData(webModule.getDocumentBase(), FORWARD_JSF);//NOI18N
  498. createFile(target, content, encoding.name()); //NOI18N
  499. DataObject dob = DataObject.find(target);
  500. if (dob != null) {
  501. JSFPaletteUtilities.reformat(dob);
  502. }
  503. }
  504. }
  505. } else if (faceletsEnabled && welcomeFiles == null) {
  506. welcomeFileList.add(ConfigurationUtils.translateURI(facesMapping, WELCOME_XHTML));
  507. }
  508. if (welcomeFiles != null && welcomeFileList.isEmpty()) {
  509. for (String fileName : welcomeFiles.getWelcomeFile()) {
  510. welcomeFileList.add(ConfigurationUtils.translateURI(facesMapping, fileName));
  511. }
  512. welcomeFiles = null;
  513. }
  514. if (welcomeFiles == null && !welcomeFileList.isEmpty()) {
  515. welcomeFiles = (WelcomeFileList) ddRoot.createBean("WelcomeFileList"); //NOI18N
  516. ddRoot.setWelcomeFileList(welcomeFiles);
  517. for (String fileName: welcomeFileList) {
  518. welcomeFiles.addWelcomeFile(fileName);
  519. }
  520. }
  521. ddRoot.write(dd);
  522. } catch (ClassNotFoundException cnfe){
  523. LOGGER.log(Level.WARNING, "Exception in JSFMoveClassPlugin", cnfe); //NOI18N
  524. }
  525. } else {
  526. SwingUtilities.invokeLater(new Runnable() {
  527. @Override
  528. public void run() {
  529. NotifyDescriptor warningDialog = new NotifyDescriptor.Message(
  530. NbBundle.getMessage(JSFFrameworkProvider.class, "WARN_UnknownDeploymentDescriptorText"), //NOI18N
  531. NotifyDescriptor.WARNING_MESSAGE);
  532. DialogDisplayer.getDefault().notify(warningDialog);
  533. }
  534. });
  535. }
  536. // copy faces-config.xml
  537. File fileConfig = new File(FileUtil.toFile(webModule.getWebInf()), "faces-config.xml"); // NOI18N
  538. boolean createFacesConfig = false;
  539. if (!fileConfig.exists()) {
  540. // Fix Issue#105180, new project wizard lets me select both jsf and visual jsf.
  541. // The new faces-config.xml template contains no elements;
  542. // it's better the framework don't replace user's original one if exist.
  543. String facesConfigTemplate = "faces-config.xml"; //NOI18N
  544. if (ddRoot != null) {
  545. Profile profile = webModule.getJ2eeProfile();
  546. if (profile.equals(Profile.JAVA_EE_5) || profile.equals(Profile.JAVA_EE_6_FULL) || profile.equals(Profile.JAVA_EE_6_WEB)) {
  547. if (isJSF21)
  548. facesConfigTemplate = "faces-config_2_1.xml"; //NOI18N
  549. else if (isJSF20)
  550. facesConfigTemplate = "faces-config_2_0.xml"; //NOI18N
  551. else
  552. facesConfigTemplate = "faces-config_1_2.xml"; //NOI18N
  553. }
  554. if (!profile.equals(Profile.JAVA_EE_6_FULL) && !profile.equals(Profile.JAVA_EE_6_WEB) && !isJSF20) {
  555. createFacesConfig = true;
  556. }
  557. }
  558. if (createFacesConfig) {
  559. String content = readResource(getClass().getResourceAsStream(RESOURCE_FOLDER + facesConfigTemplate), "UTF-8"); //NOI18N
  560. FileObject target = FileUtil.createData(webModule.getWebInf(), "faces-config.xml");//NOI18N
  561. createFile(target, content, "UTF-8"); //NOI18N
  562. }
  563. }
  564. //If Facelets enabled need to add view-handler
  565. if (panel.isEnableFacelets()) {
  566. FileObject files[] = ConfigurationUtils.getFacesConfigFiles(webModule);
  567. if (files != null && files.length > 0) {
  568. JSFConfigModel model = ConfigurationUtils.getConfigModel(files[0], true);
  569. FacesConfig jsfConfig = model.getRootComponent();
  570. if (jsfConfig != null){
  571. Application application = null;
  572. boolean newApplication = false;
  573. List<Application> applications = jsfConfig.getApplications();
  574. if (applications != null && applications.size() > 0){
  575. List<ViewHandler> handlers = applications.get(0).getViewHandlers();
  576. boolean alreadyDefined = false;
  577. if (handlers != null){
  578. for (ViewHandler viewHandler : handlers) {
  579. if (HANDLER.equals(viewHandler.getFullyQualifiedClassType().trim())){
  580. alreadyDefined = true;
  581. break;
  582. }
  583. }
  584. }
  585. if (!alreadyDefined){
  586. application = applications.get(0);
  587. }
  588. } else {
  589. application = model.getFactory().createApplication();
  590. newApplication = true;
  591. }
  592. if (application != null){
  593. model.startTransaction();
  594. if (newApplication) {
  595. jsfConfig.addApplication(application);
  596. }
  597. //In JSF2.0 no need to add HANDLER need to change version of faces-config instead
  598. if (!isJSF20 && !isMyFaces) {
  599. ViewHandler viewHandler = model.getFactory().createViewHandler();
  600. viewHandler.setFullyQualifiedClassType(HANDLER);
  601. application.addViewHandler(viewHandler);
  602. }
  603. // // A component library may require a render kit
  604. // if (isJSF20Plus && panel.getJsfComponentDescriptor() != null) {
  605. // String drki = panel.getJsfComponentDescriptor().getDefaultRenderKitId();
  606. // if (drki != null) {
  607. // List<DefaultRenderKitId> drkits = application.getDefaultRenderKitIds();
  608. // boolean alreadyDefined = false;
  609. // if (drkits != null){
  610. // for (DefaultRenderKitId drkit : drkits) {
  611. // if (drki.equals(drkit.getText().trim())){
  612. // alreadyDefined = true;
  613. // break;
  614. // }
  615. // }
  616. // }
  617. // if (!alreadyDefined){
  618. // DefaultRenderKitId newdrki = model.getFactory().createDefaultRenderKitId();
  619. // newdrki.setText(drki);
  620. // application.addDefaultRenderKitId(newdrki);
  621. // }
  622. // }
  623. // }
  624. ClassPath cp = ClassPath.getClassPath(webModule.getDocumentBase(), ClassPath.COMPILE);
  625. // FIXME icefaces on server
  626. if (panel.getLibrary()!=null && panel.getLibrary().getName().indexOf("facelets-icefaces") != -1 //NOI18N
  627. && cp != null && cp.findResource("com/icesoft/faces/facelets/D2DFaceletViewHandler.class") != null){ //NOI18N
  628. ViewHandler iceViewHandler = model.getFactory().createViewHandler();
  629. iceViewHandler.setFullyQualifiedClassType("com.icesoft.faces.facelets.D2DFaceletViewHandler"); //NOI18N
  630. application.addViewHandler(iceViewHandler);
  631. }
  632. try {
  633. model.endTransaction();
  634. model.sync();
  635. } catch (IllegalStateException ex) {
  636. IOException io = new IOException("Cannot update faces-config.xml", ex);
  637. throw Exceptions.attachLocalizedMessage(io,
  638. NbBundle.getMessage(JSFFrameworkProvider.class, "ERR_WRITE_FACES_CONFIG", Exceptions.findLocalizedMessage(ex)));
  639. }
  640. DataEditorSupport editorSupport =
  641. DataObject.find(files[0]).getLookup().lookup(DataEditorSupport.class);
  642. editorSupport.saveDocument();
  643. }
  644. }
  645. }
  646. }
  647. if (panel.isEnableFacelets() && panel.isCreateExamples()) {
  648. InputStream is;
  649. String content;
  650. FileObject target;
  651. Charset encoding = FileEncodingQuery.getDefaultEncoding();
  652. // if (webModule.getDocumentBase().getFileObject(TEMPLATE_XHTML) == null){
  653. // if (isJSF20Plus) {
  654. // is= JSFFrameworkProvider.class.getClassLoader()
  655. // .getResourceAsStream(FL_RESOURCE_FOLDER + TEMPLATE_XHTML2);
  656. // } else {
  657. // is= JSFFrameworkProvider.class.getClassLoader()
  658. // .getResourceAsStream(FL_RESOURCE_FOLDER + TEMPLATE_XHTML);
  659. // }
  660. // content = readResource(is, encoding.name());
  661. // target = FileUtil.createData(webModule.getDocumentBase(), TEMPLATE_XHTML);
  662. // createFile(target, content, encoding.name());
  663. // }
  664. if (webModule.getDocumentBase().getFileObject(WELCOME_XHTML) == null){
  665. target = FileUtil.createData(webModule.getDocumentBase(), WELCOME_XHTML);
  666. FileObject template = FileUtil.getConfigRoot().getFileObject(WELCOME_XHTML_TEMPLATE);
  667. HashMap<String, Object> params = new HashMap<String, Object>();
  668. if (isJSF20 || isJSF21) {
  669. params.put("isJSF20", Boolean.TRUE); //NOI18N
  670. }
  671. JSFPaletteUtilities.expandJSFTemplate(template, params, target);
  672. }
  673. // String defaultCSSFolder = CSS_FOLDER;
  674. // if (isJSF20Plus) {
  675. // defaultCSSFolder = CSS_FOLDER2;
  676. // }
  677. // if (webModule.getDocumentBase().getFileObject(defaultCSSFolder+"/"+DEFAULT_CSS) == null){ //NOI18N
  678. // is = JSFFrameworkProvider.class.getClassLoader().getResourceAsStream(FL_RESOURCE_FOLDER + DEFAULT_CSS);
  679. // content = readResource(is, encoding.name());
  680. // //File.separator replaced by "/" because it is used in createData method
  681. // target = FileUtil.createData(webModule.getDocumentBase(), defaultCSSFolder + "/"+ DEFAULT_CSS); //NOI18N
  682. // createFile(target, content, encoding.name());
  683. // }
  684. }
  685. //copy Welcome.jsp
  686. if (!panel.isEnableFacelets() && createWelcome && canCreateNewFile(webModule.getDocumentBase(), WELCOME_JSF)) {
  687. String content = readResource(getClass().getResourceAsStream(RESOURCE_FOLDER + WELCOME_JSF), "UTF-8"); //NOI18N
  688. Charset encoding = FileEncodingQuery.getDefaultEncoding();
  689. content = content.replaceAll("__ENCODING__", encoding.name());
  690. FileObject target = FileUtil.createData(webModule.getDocumentBase(), WELCOME_JSF);
  691. createFile(target, content, encoding.name());
  692. DataObject dob = DataObject.find(target);
  693. if (dob != null) {
  694. JSFPaletteUtilities.reformat(dob);
  695. }
  696. }
  697. }
  698. private boolean shouldAddMappings(WebModule webModule) {
  699. assert webModule != null;
  700. // Project project = FileOwnerQuery.getOwner(webModule.getDocumentBase());
  701. FileObject docBase = webModule.getDocumentBase();
  702. ClassPath cp = ClassPath.getClassPath(docBase, ClassPath.COMPILE);
  703. boolean isJSF2_0_impl = cp.findResource(JSFUtils.JSF_2_0__IMPL_SPECIFIC_CLASS.replace('.', '/') + ".class") != null; //NOI18N
  704. Project project = FileOwnerQuery.getOwner(docBase);
  705. WebPropertyEvaluator evaluator = project.getLookup().lookup(WebPropertyEvaluator.class);
  706. if (evaluator != null) {
  707. String serverInstanceID = evaluator.evaluator().getProperty(J2EE_SERVER_INSTANCE);
  708. if (isJSF2_0_impl && isGlassFishv3(serverInstanceID) && JSFConfigUtilities.hasJsfFramework(webModule.getDocumentBase())) {
  709. return false;
  710. }
  711. }
  712. return true;
  713. }
  714. private boolean isGlassFishv3(String serverInstanceID) {
  715. if (serverInstanceID == null || "".equals(serverInstanceID)) {
  716. return false;
  717. }
  718. String shortName;
  719. try {
  720. shortName = Deployment.getDefault().getServerInstance(serverInstanceID).getServerID();
  721. if ("gfv3ee6".equals(shortName) || "gfv3".equals(shortName)) {
  722. return true;
  723. }
  724. } catch (InstanceRemovedException ex) {
  725. LOGGER.log(Level.INFO, "Server Instance was removed", ex); //NOI18N
  726. }
  727. return false;
  728. }
  729. private boolean canCreateNewFile(FileObject parent, String name){
  730. File fileToBe = new File(FileUtil.toFile(parent), name);
  731. boolean create = true;
  732. if (fileToBe.exists()){
  733. DialogDescriptor dialog = new DialogDescriptor(
  734. NbBundle.getMessage(JSFFrameworkProvider.class, "MSG_OverwriteFile", fileToBe.getAbsolutePath()),
  735. NbBundle.getMessage(JSFFrameworkProvider.class, "TTL_OverwriteFile"),
  736. true, DialogDescriptor.YES_NO_OPTION, DialogDescriptor.NO_OPTION, null);
  737. java.awt.Dialog d = org.openide.DialogDisplayer.getDefault().createDialog(dialog);
  738. d.setVisible(true);
  739. create = (dialog.getValue() == org.openide.DialogDescriptor.NO_OPTION);
  740. }
  741. return create;
  742. }
  743. }
  744. }