Source Code Cross Referenced for JsfProjectUtils.java in  » IDE-Netbeans » visualweb.api.designer » org » netbeans » modules » visualweb » project » jsf » api » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » IDE Netbeans » visualweb.api.designer » org.netbeans.modules.visualweb.project.jsf.api 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /*
0002:         * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
0003:         *
0004:         * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
0005:         *
0006:         * The contents of this file are subject to the terms of either the GNU
0007:         * General Public License Version 2 only ("GPL") or the Common
0008:         * Development and Distribution License("CDDL") (collectively, the
0009:         * "License"). You may not use this file except in compliance with the
0010:         * License. You can obtain a copy of the License at
0011:         * http://www.netbeans.org/cddl-gplv2.html
0012:         * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
0013:         * specific language governing permissions and limitations under the
0014:         * License.  When distributing the software, include this License Header
0015:         * Notice in each file and include the License file at
0016:         * nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
0017:         * particular file as subject to the "Classpath" exception as provided
0018:         * by Sun in the GPL Version 2 section of the License file that
0019:         * accompanied this code. If applicable, add the following below the
0020:         * License Header, with the fields enclosed by brackets [] replaced by
0021:         * your own identifying information:
0022:         * "Portions Copyrighted [year] [name of copyright owner]"
0023:         *
0024:         * Contributor(s):
0025:         *
0026:         * The Original Software is NetBeans. The Initial Developer of the Original
0027:         * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
0028:         * Microsystems, Inc. All Rights Reserved.
0029:         *
0030:         * If you wish your version of this file to be governed by only the CDDL
0031:         * or only the GPL Version 2, indicate your decision by adding
0032:         * "[Contributor] elects to include this software in this distribution
0033:         * under the [CDDL or GPL Version 2] license." If you do not indicate a
0034:         * single choice of license, a recipient has the option to distribute
0035:         * your version of this file under either the CDDL, the GPL Version 2 or
0036:         * to extend the choice of license to its licensees as provided above.
0037:         * However, if you add GPL Version 2 code and therefore, elected the GPL
0038:         * Version 2 license, then the option applies only if the new code is
0039:         * made subject to such option by the copyright holder.
0040:         */
0041:
0042:        package org.netbeans.modules.visualweb.project.jsf.api;
0043:
0044:        import org.netbeans.modules.visualweb.project.jsf.framework.JSFFrameworkProvider;
0045:        import org.netbeans.modules.visualweb.project.jsf.actions.ImportFileAction;
0046:        import org.netbeans.modules.visualweb.project.jsf.libraries.LibraryDefinition;
0047:        import org.netbeans.modules.visualweb.project.jsf.libraries.J2SELibraryDefinition;
0048:        import org.netbeans.modules.visualweb.project.jsf.libraries.ComponentLibraryDefinition;
0049:        import org.netbeans.modules.visualweb.project.jsf.libraries.JsfProjectLibrary;
0050:        import org.netbeans.modules.visualweb.api.j2ee.common.RequestedEjbResource;
0051:
0052:        import java.io.BufferedReader;
0053:        import java.io.BufferedWriter;
0054:        import java.io.InputStreamReader;
0055:        import java.io.OutputStreamWriter;
0056:        import java.io.BufferedInputStream;
0057:        import java.io.BufferedOutputStream;
0058:        import java.io.File;
0059:        import java.io.IOException;
0060:        import java.io.InputStream;
0061:        import java.io.OutputStream;
0062:        import java.io.ByteArrayInputStream;
0063:        import java.net.MalformedURLException;
0064:        import java.net.URL;
0065:        import java.util.WeakHashMap;
0066:        import java.util.Map;
0067:        import java.util.ArrayList;
0068:        import java.util.List;
0069:        import java.beans.PropertyChangeListener;
0070:        import java.beans.PropertyChangeEvent;
0071:        import java.security.AccessController;
0072:        import java.security.PrivilegedAction;
0073:        import java.awt.EventQueue;
0074:        import java.nio.charset.Charset;
0075:        import javax.swing.JFileChooser;
0076:
0077:        import org.netbeans.api.java.classpath.ClassPath;
0078:        import org.netbeans.api.java.project.JavaProjectConstants;
0079:        import org.netbeans.api.java.project.classpath.ProjectClassPathModifier;
0080:        import org.netbeans.spi.java.queries.SourceLevelQueryImplementation;
0081:        import org.netbeans.api.project.FileOwnerQuery;
0082:        import org.netbeans.api.project.Project;
0083:        import org.netbeans.api.project.ProjectUtils;
0084:        import org.netbeans.api.project.Sources;
0085:        import org.netbeans.api.project.SourceGroup;
0086:        import org.netbeans.api.project.libraries.Library;
0087:        import org.netbeans.spi.project.AuxiliaryConfiguration;
0088:        import org.netbeans.spi.project.support.ant.AntProjectHelper;
0089:        import org.netbeans.spi.project.support.ant.EditableProperties;
0090:        import org.netbeans.spi.project.support.ant.PropertyEvaluator;
0091:        import org.netbeans.api.queries.FileEncodingQuery;
0092:        import org.netbeans.modules.web.api.webmodule.WebModule;
0093:        import org.netbeans.modules.web.api.webmodule.WebFrameworks;
0094:        import org.netbeans.modules.web.spi.webmodule.WebFrameworkProvider;
0095:        import org.netbeans.modules.web.project.api.WebProjectLibrariesModifier;
0096:        import org.netbeans.modules.web.project.api.WebPropertyEvaluator;
0097:        import org.netbeans.modules.web.jsf.api.ConfigurationUtils; // XXX wait for NetBeans API
0098:        //import org.netbeans.modules.project.ui.ProjectTab;
0099:        import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eeModule;
0100:        import org.netbeans.modules.j2ee.dd.api.web.WebApp;
0101:        import org.netbeans.modules.j2ee.dd.api.web.DDProvider;
0102:        import org.netbeans.modules.j2ee.dd.api.web.WelcomeFileList;
0103:        import org.netbeans.modules.j2ee.dd.api.web.Servlet;
0104:        import org.netbeans.modules.j2ee.dd.api.web.ServletMapping;
0105:        import org.netbeans.modules.j2ee.dd.api.common.ResourceRef;
0106:        import org.netbeans.modules.j2ee.dd.api.common.EjbRef;
0107:        import org.netbeans.modules.j2ee.dd.api.common.NameAlreadyUsedException;
0108:        import org.openide.ErrorManager;
0109:        import org.openide.filesystems.FileLock;
0110:        import org.openide.filesystems.FileObject;
0111:        import org.openide.filesystems.FileUtil;
0112:        import org.openide.filesystems.URLMapper;
0113:        import org.openide.loaders.DataObject;
0114:        import org.openide.modules.InstalledFileLocator;
0115:        import org.openide.util.Utilities;
0116:
0117:        import org.openide.xml.XMLUtil;
0118:        import org.w3c.dom.Document;
0119:        import org.w3c.dom.Element;
0120:        import org.w3c.dom.Node;
0121:        import org.w3c.dom.NodeList;
0122:        import org.w3c.dom.Text;
0123:        import org.xml.sax.InputSource;
0124:        import org.xml.sax.EntityResolver;
0125:        import org.xml.sax.SAXException;
0126:        import javax.xml.parsers.DocumentBuilder;
0127:        import javax.xml.parsers.DocumentBuilderFactory;
0128:        import javax.xml.parsers.ParserConfigurationException;
0129:        import org.netbeans.api.project.ProjectManager;
0130:        import org.netbeans.api.project.libraries.LibraryManager;
0131:        import org.netbeans.spi.project.support.ant.ReferenceHelper;
0132:        import org.openide.util.Mutex;
0133:        import org.openide.util.NbBundle;
0134:
0135:        /**
0136:         *
0137:         * @author Po-Ting Wu
0138:         */
0139:        public class JsfProjectUtils {
0140:            public final static String PATH_IN_WAR_LIB = "WEB-INF/lib"; //NOI18N
0141:            public final static String SUN_WEB_XML_PATH = "web/WEB-INF/sun-web.xml"; // NOI18N
0142:
0143:            private final static String RAVE_AUX_NAMESPACE = "http://www.sun.com/creator/ns";
0144:            private final static String RAVE_AUX_NAME = "creator-data";
0145:            private final static String[] CreatorProperties = {
0146:                    JsfProjectConstants.PROP_CURRENT_THEME,
0147:                    JsfProjectConstants.PROP_JSF_PAGEBEAN_PACKAGE,
0148:                    JsfProjectConstants.PROP_JSF_PROJECT_LIBRARIES_DIR,
0149:                    JsfProjectConstants.PROP_START_PAGE };
0150:
0151:            private static final Map<Project, ArrayList> propertyListeners = new WeakHashMap();
0152:
0153:            public static WebModule getWebModule(Project project) {
0154:                WebModule wm = WebModule.getWebModule(project
0155:                        .getProjectDirectory());
0156:
0157:                if (wm != null) {
0158:                    return wm;
0159:                }
0160:
0161:                Sources sources = ProjectUtils.getSources(project);
0162:                SourceGroup[] groups = sources
0163:                        .getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
0164:                for (SourceGroup group : groups) {
0165:                    wm = WebModule.getWebModule(group.getRootFolder());
0166:                    if (wm != null) {
0167:                        return wm;
0168:                    }
0169:                }
0170:
0171:                return null;
0172:            }
0173:
0174:            /**
0175:             * Check for Creator project
0176:             * @param project Project to be checked
0177:             */
0178:            public static boolean isJsfProject(Project project) {
0179:                String version = getProjectVersion(project);
0180:                return version != null && version.length() > 0;
0181:            }
0182:
0183:            public static boolean isJsfFramework(WebFrameworkProvider framework) {
0184:                if (framework == null) {
0185:                    return false;
0186:                }
0187:
0188:                return (framework instanceof  JSFFrameworkProvider);
0189:            }
0190:
0191:            public static void addJsfFrameworkChangeListener(Project project,
0192:                    PropertyChangeListener listener) {
0193:                JSFFrameworkProvider JsfFramework = getJSFFramework();
0194:                if (JsfFramework == null) {
0195:                    return;
0196:                }
0197:                JsfFramework.addPropertyChangeListener(project, listener);
0198:            }
0199:
0200:            public static void removeJsfFrameworkChangeListener(
0201:                    Project project, PropertyChangeListener listener) {
0202:                JSFFrameworkProvider JsfFramework = getJSFFramework();
0203:                if (JsfFramework == null) {
0204:                    return;
0205:                }
0206:                JsfFramework.removePropertyChangeListener(project, listener);
0207:            }
0208:
0209:            private static JSFFrameworkProvider getJSFFramework() {
0210:                List<WebFrameworkProvider> frameworks = WebFrameworks
0211:                        .getFrameworks();
0212:                for (WebFrameworkProvider framework : frameworks) {
0213:                    if (framework instanceof  JSFFrameworkProvider) {
0214:                        return (JSFFrameworkProvider) framework;
0215:                    }
0216:                }
0217:
0218:                return null;
0219:            }
0220:
0221:            public static boolean isWebProject(Project project) {
0222:                if (project == null) {
0223:                    return false;
0224:                }
0225:                WebModule wm = getWebModule(project);
0226:                return wm != null;
0227:            }
0228:
0229:            private static final Map<FileObject, Boolean> JsfProjectDir = new WeakHashMap();
0230:
0231:            public static Boolean isJsfProjectDir(FileObject projDir) {
0232:                return (Boolean) JsfProjectDir.get(projDir);
0233:            }
0234:
0235:            public static void setJsfProjectDir(FileObject projDir, Boolean set) {
0236:                JsfProjectDir.put(projDir, set);
0237:            }
0238:
0239:            public static void setJsfProjectDir(ArrayList<FileObject> projDirs,
0240:                    Boolean set) {
0241:                for (FileObject projDir : projDirs) {
0242:                    JsfProjectDir.put(projDir, set);
0243:                }
0244:            }
0245:
0246:            /**
0247:             * Check for Creator project file. Note: For DataLoader only when 'Project' is not available.
0248:             * @param fo FileObject to be checked
0249:             */
0250:            public static boolean isJsfProjectFile(FileObject fo) {
0251:                ArrayList<FileObject> dirs = new ArrayList();
0252:
0253:                while (fo != null) {
0254:                    if (fo.isFolder()) {
0255:                        Boolean ret = isJsfProjectDir(fo);
0256:                        if (ret != null) {
0257:                            return ret.booleanValue();
0258:                        }
0259:
0260:                        dirs.add(fo);
0261:
0262:                        final FileObject projXml = fo
0263:                                .getFileObject("nbproject/project.xml"); // NOI18N
0264:                        // Found the project root directory and got the project.xml file
0265:                        if (projXml != null) {
0266:                            if (fileContains(projXml, RAVE_AUX_NAMESPACE)) {
0267:                                setJsfProjectDir(dirs, Boolean.TRUE);
0268:                                return true;
0269:                            }
0270:                        }
0271:
0272:                        final FileObject propFile = fo
0273:                                .getFileObject(AntProjectHelper.PROJECT_PROPERTIES_PATH);
0274:                        // Found the project root directory and got the project.properties file
0275:                        if (propFile != null) {
0276:                            // Check Creator property
0277:                            boolean isJsf = fileContains(propFile,
0278:                                    "jsf.pagebean.package"); // NOI18N
0279:                            setJsfProjectDir(dirs, Boolean.valueOf(isJsf));
0280:                            return isJsf;
0281:                        }
0282:                    }
0283:
0284:                    fo = fo.getParent();
0285:                }
0286:
0287:                return false;
0288:            }
0289:
0290:            public static boolean fileContains(FileObject fo, String str) {
0291:                BufferedReader in = null;
0292:                try {
0293:                    try {
0294:                        in = new BufferedReader(new InputStreamReader(fo
0295:                                .getInputStream()));
0296:                        String s;
0297:                        while ((s = in.readLine()) != null) {
0298:                            if (s.indexOf(str) != -1) {
0299:                                return true;
0300:                            }
0301:                        }
0302:                    } finally {
0303:                        if (in != null) {
0304:                            in.close();
0305:                        }
0306:                    }
0307:                } catch (IOException ioe) {
0308:                }
0309:
0310:                return false;
0311:            }
0312:
0313:            public static String getProjectVersion(Project project) {
0314:                return getProjectProperty(project,
0315:                        JsfProjectConstants.PROP_JSF_PROJECT_VERSION);
0316:            }
0317:
0318:            public static void setProjectVersion(Project project, String version) {
0319:                createProjectProperty(project,
0320:                        JsfProjectConstants.PROP_JSF_PROJECT_VERSION, version);
0321:
0322:                setJsfProjectDir(project.getProjectDirectory(), Boolean.TRUE);
0323:            }
0324:
0325:            public static boolean supportProjectProperty(Project project) {
0326:                if (isWebProject(project)) {
0327:                    AuxiliaryConfiguration ac = (AuxiliaryConfiguration) project
0328:                            .getLookup().lookup(AuxiliaryConfiguration.class);
0329:                    if (ac == null) {
0330:                        return false;
0331:                    }
0332:
0333:                    Element auxElement = ac.getConfigurationFragment(
0334:                            RAVE_AUX_NAME, RAVE_AUX_NAMESPACE, true);
0335:                    if (auxElement != null) {
0336:                        return true;
0337:                    }
0338:
0339:                    DocumentBuilderFactory factory = DocumentBuilderFactory
0340:                            .newInstance();
0341:                    try {
0342:                        DocumentBuilder builder = factory.newDocumentBuilder();
0343:                        Document xmlDoc = builder.newDocument();
0344:                        auxElement = xmlDoc.createElementNS(RAVE_AUX_NAMESPACE,
0345:                                RAVE_AUX_NAME);
0346:                    } catch (ParserConfigurationException e) {
0347:                        ErrorManager.getDefault().notify(
0348:                                ErrorManager.INFORMATIONAL, e);
0349:                        return false;
0350:                    }
0351:
0352:                    ac.putConfigurationFragment(auxElement, true);
0353:                    auxElement = ac.getConfigurationFragment(RAVE_AUX_NAME,
0354:                            RAVE_AUX_NAMESPACE, true);
0355:                    if (auxElement != null) {
0356:                        return true;
0357:                    }
0358:                }
0359:
0360:                return false;
0361:            }
0362:
0363:            public static String getProjectProperty(Project project,
0364:                    String propName) {
0365:                if (isWebProject(project)) {
0366:                    AuxiliaryConfiguration ac = (AuxiliaryConfiguration) project
0367:                            .getLookup().lookup(AuxiliaryConfiguration.class);
0368:                    if (ac == null) {
0369:                        return "";
0370:                    }
0371:
0372:                    Element auxElement = ac.getConfigurationFragment(
0373:                            RAVE_AUX_NAME, RAVE_AUX_NAMESPACE, true);
0374:                    if (auxElement == null) { // Creator 2 project
0375:                        return getCreatorProperty(project, propName);
0376:                    }
0377:                    String value = auxElement.getAttribute(propName);
0378:                    if (value == null || value.equals("")) { // Creator 2 project
0379:                        return getCreatorProperty(project, propName);
0380:                    }
0381:                    return value;
0382:                } else
0383:                    return "";
0384:            }
0385:
0386:            private static String getCreatorProperty(final Project project,
0387:                    String propName) {
0388:                EditableProperties props;
0389:                WebPropertyEvaluator wpe = (WebPropertyEvaluator) project
0390:                        .getLookup().lookup(WebPropertyEvaluator.class);
0391:                if (wpe != null) {
0392:                    PropertyEvaluator pe = wpe.evaluator();
0393:                    props = new EditableProperties(pe.getProperties());
0394:                } else {
0395:                    // Can't find anything, try to read the project.properties file directly. Shouldn't be here.
0396:                    try {
0397:                        props = (EditableProperties) ProjectManager.mutex()
0398:                                .readAccess(new Mutex.ExceptionAction() {
0399:                                    public Object run() throws Exception {
0400:                                        EditableProperties ep = new EditableProperties();
0401:                                        FileObject propFile = project
0402:                                                .getProjectDirectory()
0403:                                                .getFileObject(
0404:                                                        AntProjectHelper.PROJECT_PROPERTIES_PATH);
0405:                                        InputStream is = propFile
0406:                                                .getInputStream();
0407:
0408:                                        ep.load(is);
0409:                                        is.close();
0410:
0411:                                        return ep;
0412:                                    }
0413:                                });
0414:                    } catch (Exception e) {
0415:                        return "";
0416:                    }
0417:                }
0418:
0419:                // Store Creator properties into the new format
0420:                String ret = "";
0421:                boolean isCreator = false;
0422:                for (int i = 0; i < CreatorProperties.length; i++) {
0423:                    String val = props.getProperty(CreatorProperties[i]);
0424:                    if (val != null) {
0425:                        isCreator = true;
0426:
0427:                        putProjectProperty(project, CreatorProperties[i], val,
0428:                                "");
0429:
0430:                        if (propName.equals(CreatorProperties[i])) {
0431:                            ret = val;
0432:                        }
0433:                    }
0434:                }
0435:
0436:                // Store version into the new format
0437:                String version = props.getProperty("creator"); // NOI18N
0438:                if (isCreator && version == null) {
0439:                    version = "2.0"; // NOI18N
0440:                }
0441:                if (version != null) {
0442:                    setProjectVersion(project, version);
0443:                    if (propName
0444:                            .equals(JsfProjectConstants.PROP_JSF_PROJECT_VERSION)) { // NOI18N
0445:                        ret = version;
0446:                    }
0447:                }
0448:
0449:                return ret;
0450:            }
0451:
0452:            public static void createProjectProperty(Project project,
0453:                    String propName, String value) {
0454:                putProjectProperty(project, propName, value, ""); // NOI18N
0455:            }
0456:
0457:            public static void putProjectProperty(Project project,
0458:                    String propName, String value) {
0459:                putProjectProperty(project, propName, value,
0460:                        getProjectProperty(project, propName));
0461:            }
0462:
0463:            private static void putProjectProperty(Project project,
0464:                    String propName, String value, String oldval) {
0465:                if (isWebProject(project)) {
0466:                    AuxiliaryConfiguration ac = (AuxiliaryConfiguration) project
0467:                            .getLookup().lookup(AuxiliaryConfiguration.class);
0468:                    if (ac == null) {
0469:                        return;
0470:                    }
0471:
0472:                    Element auxElement = ac.getConfigurationFragment(
0473:                            RAVE_AUX_NAME, RAVE_AUX_NAMESPACE, true);
0474:                    if (auxElement == null) {
0475:                        DocumentBuilderFactory factory = DocumentBuilderFactory
0476:                                .newInstance();
0477:                        try {
0478:                            DocumentBuilder builder = factory
0479:                                    .newDocumentBuilder();
0480:                            Document xmlDoc = builder.newDocument();
0481:                            auxElement = xmlDoc.createElementNS(
0482:                                    RAVE_AUX_NAMESPACE, RAVE_AUX_NAME);
0483:                        } catch (ParserConfigurationException e) {
0484:                            ErrorManager.getDefault().notify(
0485:                                    ErrorManager.INFORMATIONAL, e);
0486:                            return;
0487:                        }
0488:                    }
0489:                    auxElement.setAttribute(propName, value);
0490:                    ac.putConfigurationFragment(auxElement, true);
0491:                }
0492:
0493:                PropertyChangeEvent event = new PropertyChangeEvent(project,
0494:                        propName, oldval, value);
0495:                PropertyChangeListener[] listeners;
0496:                synchronized (propertyListeners) {
0497:                    ArrayList projectListeners = (ArrayList) propertyListeners
0498:                            .get(project);
0499:                    if (projectListeners == null) {
0500:                        return;
0501:                    }
0502:                    listeners = (PropertyChangeListener[]) projectListeners
0503:                            .toArray(new PropertyChangeListener[propertyListeners
0504:                                    .size()]);
0505:                }
0506:                for (int i = 0; i < listeners.length; i++) {
0507:                    PropertyChangeListener listener = listeners[i];
0508:                    if (listener != null) {
0509:                        listener.propertyChange(event);
0510:                    }
0511:                }
0512:            }
0513:
0514:            public static void addProjectPropertyListener(Project project,
0515:                    PropertyChangeListener listener) {
0516:                if (isWebProject(project)) {
0517:                    synchronized (propertyListeners) {
0518:                        ArrayList projectListeners = (ArrayList) propertyListeners
0519:                                .get(project);
0520:                        if (projectListeners == null) {
0521:                            projectListeners = new ArrayList();
0522:                            propertyListeners.put(project, projectListeners);
0523:                        }
0524:                        projectListeners.add(listener);
0525:                    }
0526:                }
0527:            }
0528:
0529:            public static void removeProjectPropertyListener(Project project,
0530:                    PropertyChangeListener listener) {
0531:                if (isWebProject(project)) {
0532:                    synchronized (propertyListeners) {
0533:                        ArrayList projectListeners = (ArrayList) propertyListeners
0534:                                .get(project);
0535:                        if (projectListeners != null) {
0536:                            projectListeners.remove(listener);
0537:                        }
0538:                    }
0539:                }
0540:            }
0541:
0542:            /** Check for start page
0543:             * @param webPage JSP file
0544:             */
0545:            public static boolean isStartPage(FileObject webPage) {
0546:                Project project = FileOwnerQuery.getOwner(webPage);
0547:                if (project == null)
0548:                    return false;
0549:
0550:                FileObject webFolder = getDocumentRoot(project);
0551:                if (webFolder == null)
0552:                    return false;
0553:
0554:                String startPagePath = getProjectProperty(project,
0555:                        JsfProjectConstants.PROP_START_PAGE);
0556:                if (startPagePath == null || startPagePath.length() == 0)
0557:                    return false;
0558:
0559:                FileObject actualStartPage = webFolder
0560:                        .getFileObject(startPagePath);
0561:                return (actualStartPage != null && actualStartPage
0562:                        .equals(webPage));
0563:            }
0564:
0565:            /** Sets the start page for the application
0566:             * @param startPage the path to the JSP or HTML file relative to the document root.
0567:             * @return If successful, returns the path of the new start page relative to the document root, null if unsuccessful.
0568:             */
0569:            public static String setStartPage(FileObject webPage) {
0570:                Project project = FileOwnerQuery.getOwner(webPage);
0571:                if (project == null)
0572:                    return null;
0573:
0574:                FileObject webFolder = getDocumentRoot(project);
0575:                if (webFolder == null)
0576:                    return null;
0577:
0578:                String newStartPage = FileUtil.getRelativePath(webFolder,
0579:                        webPage);
0580:                return setStartPage(project, newStartPage);
0581:            }
0582:
0583:            /**
0584:             * Sets the start page for the application
0585:             * We need to the ability to specify the actual value for the new start page, since refactoring does not guarantee
0586:             * the order in which refactoring elements are processed.  Since the rename of the file object and the setting of the
0587:             * start page are separate refactoring elements, the setting of the start page can occur prior to the rename of the
0588:             * file object.
0589:             * We use the webPage file object to identify the appro
0590:             * @param project the project to set the start page on
0591:             * @param newStartPage the web folder relative path to the new start page
0592:             * @return If successful, returns the path of the new start page relative to the document root, null if unsuccessful.
0593:             */
0594:            public static String setStartPage(Project project,
0595:                    String newStartPage) {
0596:                if (project == null)
0597:                    return null;
0598:
0599:                String oldStartPage = getProjectProperty(project,
0600:                        JsfProjectConstants.PROP_START_PAGE);
0601:                putProjectProperty(project,
0602:                        JsfProjectConstants.PROP_START_PAGE, newStartPage);
0603:
0604:                // Adjust the path to the startpage based on JSF parameters
0605:                WebModule wm = getWebModule(project);
0606:                if (wm != null) {
0607:                    try {
0608:                        FileObject dd = wm.getDeploymentDescriptor();
0609:                        WebApp ddRoot = DDProvider.getDefault().getDDRoot(dd);
0610:                        if (ddRoot != null) {
0611:                            String facesMapping = getFacesURLPattern(ddRoot);
0612:                            if (oldStartPage != null) {
0613:                                removeWelcomeFile(ddRoot, facesMapping,
0614:                                        oldStartPage);
0615:                            }
0616:                            setWelcomeFile(wm, ddRoot, facesMapping,
0617:                                    newStartPage);
0618:                            ddRoot.write(dd);
0619:                        }
0620:                    } catch (IOException e) {
0621:                        ErrorManager.getDefault().notify(
0622:                                ErrorManager.INFORMATIONAL, e);
0623:                    }
0624:                }
0625:
0626:                return newStartPage;
0627:            }
0628:
0629:            /**
0630:             * Get the Faces Servlet URL pattern.
0631:             * @param ddRoot the Web Application
0632:             * @return If successful, returns the URL pattern, null if unsuccessful.
0633:             */
0634:            public static String getFacesURLPattern(WebApp ddRoot) {
0635:                Servlet[] servlets = ddRoot.getServlet();
0636:                ServletMapping[] mapping = ddRoot.getServletMapping();
0637:                if (servlets == null || mapping == null) {
0638:                    return null;
0639:                }
0640:
0641:                for (int i = 0; i < servlets.length; i++) {
0642:                    if (servlets[i].getServletClass().equals(
0643:                            "javax.faces.webapp.FacesServlet")) { // NOI18N
0644:                        String servletName = servlets[i].getServletName();
0645:                        for (int j = 0; j < mapping.length; j++) {
0646:                            if (servletName.equals(mapping[j].getServletName())) {
0647:                                return mapping[j].getUrlPattern();
0648:                            }
0649:                        }
0650:                    }
0651:                }
0652:
0653:                return null;
0654:            }
0655:
0656:            private static String FORWARD_JSF = "forwardToJSF.jsp"; //NOI18N
0657:            private static String RESOURCE_FOLDER = "org/netbeans/modules/web/jsf/resources/"; //NOI18N
0658:
0659:            public static void removeWelcomeFile(WebApp ddRoot,
0660:                    String facesMapping, String pageName) {
0661:                // remove welcome file
0662:                WelcomeFileList welcomeFiles = ddRoot
0663:                        .getSingleWelcomeFileList();
0664:                if (welcomeFiles == null) {
0665:                    return;
0666:                }
0667:
0668:                String welcomePath;
0669:                if (facesMapping.charAt(0) == '/') {
0670:                    // if the mapping start with '/' (like /faces/*), then the welcame file can be the mapping
0671:                    welcomeFiles.removeWelcomeFile(ConfigurationUtils
0672:                            .translateURI(facesMapping, pageName));
0673:                } else {
0674:                    // if the mapping doesn't strat '/' (like *.jsf), then the welcome file has to be
0675:                    // a helper file, which will foward the request to the right url
0676:                    welcomeFiles.removeWelcomeFile(FORWARD_JSF);
0677:                }
0678:            }
0679:
0680:            public static void setWelcomeFile(WebModule webModule,
0681:                    WebApp ddRoot, String facesMapping, String pageName) {
0682:                // add welcome file
0683:                WelcomeFileList welcomeFiles = ddRoot
0684:                        .getSingleWelcomeFileList();
0685:                if (welcomeFiles == null) {
0686:                    try {
0687:                        welcomeFiles = (WelcomeFileList) ddRoot
0688:                                .createBean("WelcomeFileList"); //NOI18N
0689:                        ddRoot.setWelcomeFileList(welcomeFiles);
0690:                    } catch (ClassNotFoundException cnfe) {
0691:                        ErrorManager.getDefault().notify(
0692:                                ErrorManager.INFORMATIONAL, cnfe);
0693:                    }
0694:                }
0695:
0696:                String welcomePath;
0697:                if (facesMapping.charAt(0) == '/') {
0698:                    // if the mapping start with '/' (like /faces/*), then the welcame file can be the mapping
0699:                    welcomePath = ConfigurationUtils.translateURI(facesMapping,
0700:                            pageName);
0701:                } else {
0702:                    // if the mapping doesn't strat '/' (like *.jsf), then the welcome file has to be
0703:                    // a helper file, which will foward the request to the right url
0704:                    welcomePath = FORWARD_JSF;
0705:                    //copy forwardToJSF.jsp
0706:                    if (facesMapping.charAt(0) != '/') {
0707:                        try {
0708:                            String content = readResource(Thread
0709:                                    .currentThread().getContextClassLoader()
0710:                                    .getResourceAsStream(
0711:                                            RESOURCE_FOLDER + FORWARD_JSF),
0712:                                    "UTF-8"); //NOI18N
0713:                            content = content.replace("__FORWARD__",
0714:                                    ConfigurationUtils.translateURI(
0715:                                            facesMapping, pageName));
0716:                            Charset encoding = FileEncodingQuery
0717:                                    .getDefaultEncoding();
0718:                            content = content.replaceAll("__ENCODING__",
0719:                                    encoding.name());
0720:                            FileObject target = FileUtil.createData(webModule
0721:                                    .getDocumentBase(), FORWARD_JSF);//NOI18N
0722:                            createFile(target, content, encoding.name());
0723:                        } catch (IOException ex) {
0724:                            ErrorManager.getDefault().notify(
0725:                                    ErrorManager.INFORMATIONAL, ex);
0726:                        }
0727:                    }
0728:                }
0729:
0730:                if (welcomeFiles.sizeWelcomeFile() == 0) {
0731:                    welcomeFiles.addWelcomeFile(welcomePath);
0732:                } else {
0733:                    ArrayList<String> list = new ArrayList(welcomeFiles
0734:                            .sizeWelcomeFile() + 1);
0735:                    list.add(welcomePath);
0736:                    for (String file : welcomeFiles.getWelcomeFile()) {
0737:                        if (!welcomePath.equals(file)) {
0738:                            list.add(file);
0739:                        }
0740:                    }
0741:                    welcomeFiles.setWelcomeFile(list.toArray(new String[0]));
0742:                }
0743:            }
0744:
0745:            public static String readResource(InputStream is, String encoding)
0746:                    throws IOException {
0747:                // read the config from resource first
0748:                StringBuffer sbuffer = new StringBuffer();
0749:                String lineSep = System.getProperty("line.separator");//NOI18N
0750:                BufferedReader br = new BufferedReader(new InputStreamReader(
0751:                        is, encoding));
0752:                String line = br.readLine();
0753:                while (line != null) {
0754:                    sbuffer.append(line);
0755:                    sbuffer.append(lineSep);
0756:                    line = br.readLine();
0757:                }
0758:                br.close();
0759:                return sbuffer.toString();
0760:            }
0761:
0762:            public static void createFile(FileObject target, String content,
0763:                    String encoding) throws IOException {
0764:                FileLock lock = target.lock();
0765:                try {
0766:                    BufferedWriter bw = new BufferedWriter(
0767:                            new OutputStreamWriter(
0768:                                    target.getOutputStream(lock), encoding));
0769:                    bw.write(content);
0770:                    bw.close();
0771:
0772:                } finally {
0773:                    lock.releaseLock();
0774:                }
0775:            }
0776:
0777:            public static String setDataSourceReference(Project project,
0778:                    String resourceName) {
0779:                String[] propertyNames = new String[] { "ResRefName", // NOI18N
0780:                        "Description", // NOI18N
0781:                        "ResType", // NOI18N
0782:                        "ResAuth" }; // NOI18N
0783:                Object[] propertyValues = new Object[] { resourceName,
0784:                        "Visual Web generated DataSource Reference", // NOI18N
0785:                        "javax.sql.DataSource", // NOI18N
0786:                        "Container" }; // NOI18N
0787:
0788:                return addWebAppBean(project, "ResourceRef", propertyNames,
0789:                        propertyValues, "ResRefName"); // NOI18N
0790:            }
0791:
0792:            public static String setEjbReference(Project project,
0793:                    RequestedEjbResource ejbResource) {
0794:                String[] propertyNames = new String[] { "EjbRefName", // NOI18N
0795:                        "EjbRefType", // NOI18N
0796:                        "Home", // NOI18N
0797:                        "Remote" }; // NOI18N
0798:                Object[] propertyValues = new Object[] {
0799:                        ejbResource.getEjbRefName(),
0800:                        ejbResource.getEjbRefType(), ejbResource.getHome(),
0801:                        ejbResource.getRemote() };
0802:
0803:                return addWebAppBean(project, "EjbRef", propertyNames,
0804:                        propertyValues, "EjbRefName"); // NOI18N
0805:            }
0806:
0807:            public static String addWebAppBean(Project project,
0808:                    String beanName, String[] propertyNames,
0809:                    Object[] propertyValues, String keyProperty) {
0810:                if (project == null)
0811:                    return null;
0812:
0813:                WebModule wm = getWebModule(project);
0814:                String name = (String) propertyValues[0];
0815:                if (wm != null) {
0816:                    try {
0817:                        FileObject dd = wm.getDeploymentDescriptor();
0818:                        WebApp ddRoot = DDProvider.getDefault().getDDRoot(dd);
0819:                        if (ddRoot != null) {
0820:                            if ("ResourceRef".equals(beanName)) {
0821:                                ResourceRef[] rscRefs = ddRoot.getResourceRef();
0822:                                if (rscRefs != null) {
0823:                                    for (int i = 0; i < rscRefs.length; i++) {
0824:                                        if (name.equals(rscRefs[i]
0825:                                                .getResRefName())) {
0826:                                            return null;
0827:                                        }
0828:                                    }
0829:                                }
0830:                            } else if ("EjbRef".equals(beanName)) {
0831:                                EjbRef[] ejbRefs = ddRoot.getEjbRef();
0832:                                if (ejbRefs != null) {
0833:                                    for (int i = 0; i < ejbRefs.length; i++) {
0834:                                        if (name.equals(ejbRefs[i]
0835:                                                .getEjbRefName())) {
0836:                                            return null;
0837:                                        }
0838:                                    }
0839:                                }
0840:                            }
0841:                            ddRoot.addBean(beanName, propertyNames,
0842:                                    propertyValues, keyProperty); // NOI18N
0843:                            ddRoot.write(dd);
0844:                        }
0845:                    } catch (ClassNotFoundException e) {
0846:                        // This should really not happen
0847:                        ErrorManager.getDefault().notify(
0848:                                ErrorManager.INFORMATIONAL, e);
0849:                    } catch (NameAlreadyUsedException e) {
0850:                        ErrorManager.getDefault().notify(
0851:                                ErrorManager.INFORMATIONAL, e);
0852:                    } catch (IOException e) {
0853:                        ErrorManager.getDefault().notify(
0854:                                ErrorManager.INFORMATIONAL, e);
0855:                    }
0856:                }
0857:
0858:                return name;
0859:            }
0860:
0861:            /**
0862:             * Convenience method to obtain the project's source encoding
0863:             * @param project the Project object
0864:             * @return string representation of the project's source encoding
0865:             */
0866:            public static String getSourceEncoding(Project project) {
0867:                // TODO
0868:                return "UTF-8";
0869:            }
0870:
0871:            /**
0872:             * @param project
0873:             * @return
0874:             */
0875:            public static String getDefaultEncoding(Project project) {
0876:                // PROJECTTODO: implement
0877:                return "UTF-8";
0878:            }
0879:
0880:            /**
0881:             * @param project
0882:             * @return
0883:             */
0884:            public static String getDefaultLocale(Project project) {
0885:                // PROJECTTODO: implement
0886:                return "en";
0887:            }
0888:
0889:            public static String getSourceLevel(Project project) {
0890:                if (!isWebProject(project)) {
0891:                    return null;
0892:                }
0893:
0894:                SourceLevelQueryImplementation slq = (SourceLevelQueryImplementation) project
0895:                        .getLookup().lookup(
0896:                                SourceLevelQueryImplementation.class);
0897:                if (slq == null) {
0898:                    return null;
0899:                }
0900:
0901:                FileObject srcRoot = getSourceRoot(project);
0902:                if (srcRoot == null) {
0903:                    return null;
0904:                }
0905:
0906:                return slq.getSourceLevel(srcRoot);
0907:            }
0908:
0909:            public static final String J2EE_1_3 = J2eeModule.J2EE_13;
0910:            public static final String J2EE_1_4 = J2eeModule.J2EE_14;
0911:            public static final String JAVA_EE_5 = J2eeModule.JAVA_EE_5;
0912:
0913:            private static final Map<Project, Boolean> JavaEE5Project = new WeakHashMap();
0914:
0915:            /** J2EE platform version - one of the constants {@link #J2EE_13_LEVEL}, {@link #J2EE_14_LEVEL}.
0916:             * @param project
0917:             * @return J2EE platform version
0918:             */
0919:            public static String getJ2eePlatformVersion(Project project) {
0920:                if (project == null) {
0921:                    return "";
0922:                }
0923:
0924:                WebModule wm = getWebModule(project);
0925:                if (wm == null) {
0926:                    return "";
0927:                }
0928:
0929:                return wm.getJ2eePlatformVersion();
0930:            }
0931:
0932:            public static boolean isJavaEE5Project(Project project) {
0933:                if (project == null) {
0934:                    return false;
0935:                }
0936:
0937:                Boolean ret = (Boolean) JavaEE5Project.get(project);
0938:                if (ret == null) {
0939:                    ret = new Boolean(J2eeModule.JAVA_EE_5
0940:                            .equals(getJ2eePlatformVersion(project)));
0941:                    JavaEE5Project.put(project, ret);
0942:                }
0943:
0944:                return ret.booleanValue();
0945:            }
0946:
0947:            /**
0948:             * Convenience method to obtain the document root folder.
0949:             * @param project the Project object
0950:             * @return the FileObject of the document root folder
0951:             */
0952:            public static FileObject getDocumentRoot(Project project) {
0953:                if (project == null) {
0954:                    return null;
0955:                }
0956:
0957:                WebModule wm = getWebModule(project);
0958:                if (wm == null) {
0959:                    return null;
0960:                }
0961:
0962:                return wm.getDocumentBase();
0963:            }
0964:
0965:            /**
0966:             * Convenience method to obtain the WEB-INF folder.
0967:             * @param project the Project object
0968:             * @return the FileObject of the WEB-INF folder
0969:             */
0970:            public static FileObject getWebInf(Project project) {
0971:                if (project == null) {
0972:                    return null;
0973:                }
0974:
0975:                WebModule wm = getWebModule(project);
0976:                if (wm == null) {
0977:                    return null;
0978:                }
0979:
0980:                return wm.getWebInf();
0981:            }
0982:
0983:            /**
0984:             * Convenience method to obtain the source root folder.
0985:             * @param project the Project object
0986:             * @return the FileObject of the source root folder
0987:             */
0988:            public static FileObject getSourceRoot(Project project) {
0989:                if (project == null) {
0990:                    return null;
0991:                }
0992:
0993:                // Search the ${src.dir} Source Package Folder first, use the first source group if failed.
0994:                Sources src = ProjectUtils.getSources(project);
0995:                SourceGroup[] grp = src
0996:                        .getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
0997:                for (int i = 0; i < grp.length; i++) {
0998:                    if ("${src.dir}".equals(grp[i].getName())) { // NOI18N
0999:                        return grp[i].getRootFolder();
1000:                    }
1001:                }
1002:                if (grp.length != 0) {
1003:                    return grp[0].getRootFolder();
1004:                }
1005:
1006:                return null;
1007:            }
1008:
1009:            /**
1010:             * Returns a directory under the project root where resource files can be added
1011:             * @param project Target project
1012:             * @return FileObject of the resources directory. If it does not exist, it will be created.
1013:             * @throws IOException if the directory cannot be created
1014:             */
1015:            public static FileObject getResourcesDirectory(Project project)
1016:                    throws IOException {
1017:                FileObject docRoot = getDocumentRoot(project);
1018:                if (docRoot == null) {
1019:                    return null;
1020:                }
1021:
1022:                FileObject resourceRoot = docRoot.getFileObject("resources"); // NOI18N
1023:                if (resourceRoot == null) {
1024:                    resourceRoot = FileUtil.createFolder(docRoot, "resources"); // NOI18N
1025:                }
1026:                return resourceRoot;
1027:            }
1028:
1029:            /**
1030:             * Returns a directory under the project root where library jar files can be added as project-private resources
1031:             * @param project Target project
1032:             * @return FileObject of the library directory. If it does not exist, it will be created.
1033:             * @throws IOException if the directory cannot be created
1034:             */
1035:            public static FileObject getProjectLibraryDirectory(Project project)
1036:                    throws IOException {
1037:                FileObject projRoot = project.getProjectDirectory();
1038:                FileObject libRoot = projRoot
1039:                        .getFileObject(JsfProjectConstants.PATH_LIBRARIES);
1040:                if (libRoot == null) {
1041:                    libRoot = FileUtil.createFolder(projRoot,
1042:                            JsfProjectConstants.PATH_LIBRARIES);
1043:                }
1044:                return libRoot;
1045:            }
1046:
1047:            /**
1048:             * Convenience method to obtain the project's navigation file
1049:             * @param project the Project object
1050:             * @return the FileObject of the navigtion file
1051:             */
1052:            public static FileObject getNavigationFile(Project project) {
1053:                FileObject webInf = getWebInf(project);
1054:                if (webInf == null) {
1055:                    return null;
1056:                }
1057:
1058:                return webInf.getFileObject("navigation.xml"); // NOI18N
1059:            }
1060:
1061:            /**
1062:             * Convenience method to obtain the root folder for page beans
1063:             * @param project the Project object
1064:             * @return the FileObject of the page bean root folder
1065:             */
1066:            public static FileObject getPageBeanRoot(Project project) {
1067:                if (project == null)
1068:                    return null;
1069:                if (!isWebProject(project))
1070:                    return null;
1071:                FileObject srcRoot = getSourceRoot(project);
1072:                if (srcRoot == null)
1073:                    return null;
1074:
1075:                String pageBeanPackage = getProjectProperty(project,
1076:                        JsfProjectConstants.PROP_JSF_PAGEBEAN_PACKAGE); // NOI18N
1077:                if (pageBeanPackage == null) {
1078:                    // Dumb fallback attempt to locate the bean root - sniff the package root for anything familiar
1079:                    FileObject[] pkgs = srcRoot.getChildren();
1080:                    // Assume Application/Session/Request beans are in the root bean package
1081:                    for (int i = 0; i < pkgs.length; i++) {
1082:                        if (pkgs[i].isFolder()) {
1083:                            FileObject[] files = pkgs[i].getChildren();
1084:                            for (int j = 0; j < files.length; j++) {
1085:                                if (files[j].getName().startsWith(
1086:                                        "ApplicationBean")) { // NOI18N
1087:                                    putProjectProperty(
1088:                                            project,
1089:                                            JsfProjectConstants.PROP_JSF_PAGEBEAN_PACKAGE,
1090:                                            pkgs[i].getName());
1091:                                    return pkgs[i];
1092:                                }
1093:                            }
1094:                        }
1095:                    }
1096:                    // No attribute defined and couldn't find any packages containing managed beans
1097:                    return null;
1098:                }
1099:
1100:                pageBeanPackage = pageBeanPackage.replace('.', '/');
1101:                FileObject pageBeanFolder = srcRoot
1102:                        .getFileObject(pageBeanPackage);
1103:                if (pageBeanFolder != null) {
1104:                    return pageBeanFolder;
1105:                }
1106:
1107:                try {
1108:                    return FileUtil.createFolder(srcRoot, pageBeanPackage);
1109:                } catch (IOException e) {
1110:                    ErrorManager.getDefault().notify(
1111:                            ErrorManager.INFORMATIONAL, e);
1112:                    return null;
1113:                }
1114:            }
1115:
1116:            /** Gets corresponding java file object for specified jsp file object if exists.
1117:             * @return corresponding java file object or <code>null</code> */
1118:            public static FileObject getJavaForJsp(FileObject jspFileObject) {
1119:                if (jspFileObject == null) {
1120:                    return null;
1121:                }
1122:                Project project = FileOwnerQuery.getOwner(jspFileObject);
1123:                if (project == null)
1124:                    return null;
1125:                String name = getBasePathForJsp(jspFileObject);
1126:                if (name == null) {
1127:                    return null;
1128:                }
1129:                FileObject root = getPageBeanRoot(project);
1130:                if (root == null) {
1131:                    return null;
1132:                }
1133:                name += ".java"; // NOI18N
1134:                FileObject javaFile = root.getFileObject(name);
1135:                return javaFile;
1136:            }
1137:
1138:            // !EAT TODO We will be moving this code back into InSync, but at moment we do not want to have
1139:            // to add a dependency on InSync here, would create a circularity :(
1140:            public static String getBasePathForJava(FileObject javaFile) {
1141:                if (javaFile == null) {
1142:                    return null;
1143:                }
1144:                Project project = FileOwnerQuery.getOwner(javaFile);
1145:                if (project == null) {
1146:                    return null;
1147:                }
1148:                FileObject javaRoot = getPageBeanRoot(project);
1149:                if (javaRoot == null) {
1150:                    return null;
1151:                }
1152:                String javaRootPath = javaRoot.getPath();
1153:                String basePath = javaFile.getParent().getPath();
1154:                if (basePath.startsWith(javaRootPath)) {
1155:                    basePath = basePath.substring(javaRootPath.length());
1156:                } else {
1157:                    javaRoot = getSourceRoot(project);
1158:                    javaRootPath = javaRoot.getPath();
1159:                    if (basePath.startsWith(javaRootPath)) {
1160:                        basePath = basePath.substring(javaRootPath.length());
1161:                    } else {
1162:                        String projectPath = project.getProjectDirectory()
1163:                                .getPath();
1164:                        if (basePath.startsWith(projectPath))
1165:                            basePath = basePath.substring(projectPath.length());
1166:                        else {
1167:                            // !EAT TODO
1168:                            // This case should really be handled, file is outside project tree, what to do ?
1169:                            // We really need to fix this up such that its a function of the project path, but
1170:                            // the "root" of the project element that contains this source file :(
1171:                        }
1172:                    }
1173:                }
1174:                if (basePath.length() > 0) {
1175:                    basePath += "/";
1176:                }
1177:                basePath += javaFile.getName();
1178:                return basePath;
1179:            }
1180:
1181:            /** Gets corresponding jsp file object for specified java file object if exists.
1182:             * @return corresponding jsp file object or <code>null</code> */
1183:            public static FileObject getJspForJava(FileObject javaFileObject) {
1184:                if (javaFileObject == null
1185:                        || !javaFileObject.getExt().equals("java")) { // NOI18N
1186:                    return null;
1187:                }
1188:                Project project = FileOwnerQuery.getOwner(javaFileObject);
1189:                if (project == null) {
1190:                    return null;
1191:                }
1192:                String path = getBasePathForJava(javaFileObject);
1193:                if (path == null) {
1194:                    return null;
1195:                }
1196:                String jspPath = path + ".jsp"; // NOI18N
1197:                FileObject root = getDocumentRoot(project);
1198:                if (root == null) {
1199:                    return null;
1200:                }
1201:                FileObject jspFile = root.getFileObject(jspPath);
1202:                if (jspFile == null) {
1203:                    jspPath = path + ".jspf"; // NOI18N
1204:                    jspFile = root.getFileObject(jspPath);
1205:                }
1206:                return jspFile;
1207:            }
1208:
1209:            // !EAT TODO We will be moving this code back into InSync, but at moment we do not want to have
1210:            // to add a dependency on InSync here, would create a circularity :(
1211:            public static String getBasePathForJsp(FileObject jspFile) {
1212:                if (jspFile == null) {
1213:                    return null;
1214:                }
1215:                Project project = FileOwnerQuery.getOwner(jspFile);
1216:                if (project == null) {
1217:                    return null;
1218:                }
1219:                FileObject webRoot = getDocumentRoot(project);
1220:                if (webRoot == null) {
1221:                    return null;
1222:                }
1223:                String webRootPath = webRoot.getPath();
1224:                String jspPath = jspFile.getParent().getPath();
1225:                if (jspPath.startsWith(webRootPath))
1226:                    jspPath = jspPath.substring(webRootPath.length());
1227:                else {
1228:                    String projectPath = project.getProjectDirectory()
1229:                            .getPath();
1230:                    if (jspPath.startsWith(projectPath))
1231:                        jspPath = jspPath.substring(projectPath.length());
1232:                    else {
1233:                        // !EAT TODO
1234:                        // This case should really be handled, file is outside project tree, what to do ?
1235:                        // We really need to fix this up such that its a function of the project path, but
1236:                        // the "root" of the project element that contains this source file :(
1237:                    }
1238:                }
1239:                if (jspPath.length() > 0) {
1240:                    jspPath += "/"; // NOI18N
1241:                }
1242:                jspPath += jspFile.getName();
1243:                return jspPath;
1244:            }
1245:
1246:            // folders
1247:            /** Gets corresponding java folder for specified jsp file object if exists.
1248:             * @return corresponding java file object or <code>null</code> */
1249:            public static FileObject getJavaFolderForJsp(
1250:                    FileObject jspFileObject) {
1251:                if (jspFileObject == null) {
1252:                    return null;
1253:                }
1254:                Project project = FileOwnerQuery.getOwner(jspFileObject);
1255:                if (project == null)
1256:                    return null;
1257:                String name = getFolderBasePathForJsp(jspFileObject);
1258:                if (name == null) {
1259:                    return null;
1260:                }
1261:                FileObject root = getPageBeanRoot(project);
1262:                FileObject javaFolder = root.getFileObject(name);
1263:                if (javaFolder == null) {
1264:                    try {
1265:                        javaFolder = FileUtil.createFolder(root, name);
1266:                    } catch (IOException ioe) {
1267:                        ErrorManager.getDefault().notify(
1268:                                ErrorManager.INFORMATIONAL, ioe);
1269:                    }
1270:                }
1271:                return javaFolder;
1272:            }
1273:
1274:            private static String getFolderBasePathForJsp(FileObject jspFile) {
1275:                if (jspFile == null) {
1276:                    return null;
1277:                }
1278:                Project project = FileOwnerQuery.getOwner(jspFile);
1279:                if (project == null) {
1280:                    return null;
1281:                }
1282:                FileObject webRoot = getDocumentRoot(project);
1283:                if (webRoot == null) {
1284:                    return null;
1285:                }
1286:                String webRootPath = webRoot.getPath();
1287:                String jspPath = jspFile.getParent().getPath();
1288:                if (jspPath.startsWith(webRootPath)) {
1289:                    jspPath = jspPath.substring(webRootPath.length());
1290:                } else {
1291:                    return null;
1292:                    //            jspPath = ""; // NOI18N
1293:                }
1294:                return jspPath;
1295:            }
1296:
1297:            /** Gets corresponding jsp folder for specified java file object if exists.
1298:             * @return corresponding jsp file object or <code>null</code> */
1299:            public static FileObject getJspFolderForJava(
1300:                    FileObject javaFileObject) {
1301:                if (javaFileObject == null
1302:                        || !javaFileObject.getExt().equals("java")) { // NOI18N
1303:                    return null;
1304:                }
1305:                Project project = FileOwnerQuery.getOwner(javaFileObject);
1306:                if (project == null) {
1307:                    return null;
1308:                }
1309:                String path = getFolderBasePathForJava(javaFileObject);
1310:                if (path == null) {
1311:                    return null;
1312:                }
1313:                FileObject root = getDocumentRoot(project);
1314:                FileObject jspFolder = root.getFileObject(path);
1315:                if (jspFolder == null) {
1316:                    try {
1317:                        jspFolder = FileUtil.createFolder(root, path);
1318:                    } catch (IOException ioe) {
1319:                        ErrorManager.getDefault().notify(
1320:                                ErrorManager.INFORMATIONAL, ioe);
1321:                    }
1322:                }
1323:                return jspFolder;
1324:            }
1325:
1326:            private static String getFolderBasePathForJava(FileObject javaFile) {
1327:                if (javaFile == null) {
1328:                    return null;
1329:                }
1330:                Project project = FileOwnerQuery.getOwner(javaFile);
1331:                if (project == null) {
1332:                    return null;
1333:                }
1334:                FileObject javaRoot = getPageBeanRoot(project);
1335:                if (javaRoot == null) {
1336:                    return null;
1337:                }
1338:                String javaRootPath = javaRoot.getPath();
1339:                String basePath = javaFile.getParent().getPath();
1340:                if (basePath.startsWith(javaRootPath)) {
1341:                    basePath = basePath.substring(javaRootPath.length());
1342:                } else {
1343:                    return null;
1344:                }
1345:                return basePath;
1346:            }
1347:
1348:            // folders
1349:
1350:            public static void importFile(Project project, File file) {
1351:                ImportFileAction.importFile(project, file);
1352:            }
1353:
1354:            // Other potential convenience methods
1355:
1356:            /** Add a new resource to the project
1357:             * @param webForm the webform object that will be referencing this resource.
1358:             *        Used to determine the relative path name to the resource
1359:             * @param resourceURL resource to be added
1360:             * @param copy if true, resource will be copied to the project
1361:             * @return a source path for the resource in the project. If copy is true,
1362:             *         this will be a relative path name to the resource file. If copy
1363:             *         is false, addResource will return resourceURL->toString()
1364:             * @throws IOException if an error occurs when accessing the URL or copying
1365:             *         the resource
1366:             */
1367:            public static String addResource(FileObject webForm,
1368:                    URL resourceURL, boolean copy) throws IOException {
1369:                String linkRef = resourceURL.toString();
1370:                String mimeDir = "resources"; // NOI18N
1371:                if (!copy) // maybe later show some representation of this remote resource in the PM
1372:                    return linkRef;
1373:
1374:                String fileName = new File(resourceURL.getFile()).getName();
1375:
1376:                FileObject formFolderFO = webForm.getParent();
1377:                DataObject formFolderDO = DataObject.find(formFolderFO);
1378:                FileObject resFolderFO = formFolderFO;
1379:                if (mimeDir != null) {
1380:                    resFolderFO = formFolderFO.getFileObject(mimeDir);
1381:                    if (resFolderFO == null)
1382:                        resFolderFO = FileUtil.createFolder(formFolderFO,
1383:                                mimeDir);
1384:                }
1385:
1386:                if (mimeDir != null) {
1387:                    linkRef = mimeDir + "/" + fileName; // NOI18N
1388:                } else {
1389:                    linkRef = fileName;
1390:                }
1391:
1392:                FileObject resourceFO = null;
1393:                resourceFO = resFolderFO.getFileObject(fileName);
1394:                if (resourceFO != null) {
1395:                    File targetFile = FileUtil.toFile(resourceFO);
1396:                    // 5018183 check if source & target file are the same
1397:                    try {
1398:                        URL targetURL = targetFile.toURI().toURL();
1399:                        if (targetURL.equals(resourceURL)) {
1400:                            return linkRef;
1401:                        }
1402:                    } catch (MalformedURLException e) {
1403:                        throw e;
1404:                    }
1405:
1406:                    AddResourceOverwriteDialog d = new AddResourceOverwriteDialog(
1407:                            targetFile);
1408:                    d.showDialog();
1409:                    File newTarget = d.getFile();
1410:                    if (newTarget == null)
1411:                        return null;
1412:                    if (newTarget.exists())
1413:                        return linkRef;
1414:                    fileName = newTarget.getName();
1415:                    if (mimeDir != null) {
1416:                        linkRef = mimeDir + "/" + fileName; // NOI18N
1417:                    } else {
1418:                        linkRef = fileName;
1419:                    }
1420:                }
1421:
1422:                InputStream is = null;
1423:                OutputStream os = null;
1424:                BufferedInputStream in = null;
1425:                BufferedOutputStream out = null;
1426:                FileLock lock = null;
1427:                try {
1428:                    is = resourceURL.openStream();
1429:                    // We already checked whether the file exists above
1430:                    resourceFO = resFolderFO.createData(fileName);
1431:                    lock = resourceFO.lock();
1432:                    os = resourceFO.getOutputStream(lock);
1433:                    in = new BufferedInputStream(is);
1434:                    out = new BufferedOutputStream(os);
1435:                    int c;
1436:                    while ((c = in.read()) != -1)
1437:                        out.write(c);
1438:                } catch (IOException e) {
1439:                    throw e;
1440:                } finally {
1441:                    try {
1442:                        if (lock != null)
1443:                            lock.releaseLock();
1444:                        if (in != null)
1445:                            in.close();
1446:                        if (out != null)
1447:                            out.close();
1448:                    } catch (Exception e) {
1449:                    }
1450:                }
1451:
1452:                if (resourceFO != null) {
1453:                    selectResourceInWindow(resourceFO);
1454:                }
1455:
1456:                return linkRef;
1457:            }
1458:
1459:            public static void selectResourceInWindow(
1460:                    final FileObject resourceFO) {
1461:                // Part of #6346374 Window API may be called only from Event dispatching thread.
1462:                if (EventQueue.isDispatchThread()) {
1463:                    doSelectResourceInWindow(resourceFO);
1464:                } else {
1465:                    EventQueue.invokeLater(new Runnable() {
1466:                        public void run() {
1467:                            doSelectResourceInWindow(resourceFO);
1468:                        }
1469:                    });
1470:                }
1471:            }
1472:
1473:            private static void doSelectResourceInWindow(FileObject resourceFO) {
1474:                // XXX wait for NetBeans API
1475:                // ProjectTab pt = ProjectTab.findDefault(ProjectTab.ID_LOGICAL);
1476:                // pt.selectNodeAsync(resourceFO);
1477:            }
1478:
1479:            /**
1480:             * Obtain the portlet support helper object from the project
1481:             * @param project the Project object
1482:             * @return the portlet support object or null if the project is not
1483:             * capable of supporting portlets
1484:             */
1485:            public static JsfPortletSupport getPortletSupport(Project project) {
1486:                FileObject webInf = getWebInf(project);
1487:                if (webInf == null) {
1488:                    return null;
1489:                }
1490:
1491:                FileObject fo = webInf.getFileObject("portlet.xml"); // NOI18N
1492:                if (fo == null)
1493:                    return null;
1494:                else {
1495:                    // TODO: This really should be a lookup on web/project.  Currently the module dependencies
1496:                    // are incorrect.  The web/project should provide the interface to JsfPortletSupport and hide
1497:                    // the implementation.  The web/project should contain the JsfPortletSupport implementation or
1498:                    // there should be an API/SPI arrangement set up to elliminate the web/project to project/jsfportlet
1499:                    // module dependecy.
1500:                    //
1501:                    // Current hack:  Because this method is likely to be called numerous
1502:                    // times by time-critical modules like "designer", we MUST place the
1503:                    // implementation either in the project/jsfprojectapi or in project/jsfportlet
1504:                    // and create a dependencey between project/jsfprojectapi and project/jsfportlet.
1505:                    // Since the portlet support implementation also needs module portletcontainer interaction,
1506:                    // we will put the implementation in project/jsfportlet to elliminate the need for
1507:                    // a dependency between project/jsfprojectapi and portletcontainer.
1508:                    // In order to elliminate the module dependency between
1509:                    // project/jsfprojectapi and project/jsfportlet, we would need to use the
1510:                    // layer.xml files and the built-in lookup facility to find the interface.  This would
1511:                    // be too time-consuming to do each time this static method was called.  We
1512:                    // can't put a static reference to the implementation since the the user
1513:                    // can have multiple projects open at once.  The portlet suppport for the first project
1514:                    // opened would always be the portlet support given out to all projects.
1515:                    // - David Botterill 5/13/2005
1516:                    return new JsfPortletSupportImpl(project);
1517:                }
1518:
1519:            }
1520:
1521:            public static void updateXml(FileObject prjLoc, String path,
1522:                    String nameSpace, String key, String value)
1523:                    throws IOException {
1524:                try {
1525:                    FileObject projXml = prjLoc.getFileObject(path);
1526:                    if (projXml == null) {
1527:                        return;
1528:                    }
1529:
1530:                    Document doc = XMLUtil.parse(new InputSource(FileUtil
1531:                            .toFile(projXml).toURI().toString()), false, true,
1532:                            null, new EntityResolver() {
1533:                                public InputSource resolveEntity(String pubid,
1534:                                        String sysid) throws SAXException,
1535:                                        IOException {
1536:                                    return new InputSource(
1537:                                            new ByteArrayInputStream(
1538:                                                    new byte[0]));
1539:                                }
1540:                            });
1541:                    NodeList nlist;
1542:                    if (nameSpace != null) {
1543:                        nlist = doc.getElementsByTagNameNS(nameSpace, key);
1544:                    } else {
1545:                        nlist = doc.getElementsByTagName(key);
1546:                    }
1547:                    if (nlist != null) {
1548:                        for (int i = 0; i < nlist.getLength(); i++) {
1549:                            Node n = nlist.item(i);
1550:                            if (n.getNodeType() != Node.ELEMENT_NODE) {
1551:                                continue;
1552:                            }
1553:                            Element e = (Element) n;
1554:
1555:                            replaceText(e, value);
1556:                        }
1557:                        saveXml(doc, prjLoc, path);
1558:                    }
1559:                } catch (Exception e) {
1560:                    throw new IOException(e.toString());
1561:                }
1562:            }
1563:
1564:            /**
1565:             * Extract nested text from an element.
1566:             * Currently does not handle coalescing text nodes, CDATA sections, etc.
1567:             * @param parent a parent element
1568:             * @return the nested text, or null if none was found
1569:             */
1570:            private static void replaceText(Element parent, String name) {
1571:                NodeList l = parent.getChildNodes();
1572:                for (int i = 0; i < l.getLength(); i++) {
1573:                    if (l.item(i).getNodeType() == Node.TEXT_NODE) {
1574:                        Text text = (Text) l.item(i);
1575:                        text.setNodeValue(name);
1576:                        return;
1577:                    }
1578:                }
1579:            }
1580:
1581:            /**
1582:             * Save an XML config file to a named path.
1583:             * If the file does not yet exist, it is created.
1584:             */
1585:            private static void saveXml(Document doc, FileObject dir,
1586:                    String path) throws IOException {
1587:                FileObject xml = FileUtil.createData(dir, path);
1588:                FileLock lock = xml.lock();
1589:                try {
1590:                    OutputStream os = xml.getOutputStream(lock);
1591:                    try {
1592:                        XMLUtil.write(doc, os, "UTF-8"); // NOI18N
1593:                    } finally {
1594:                        os.close();
1595:                    }
1596:                } finally {
1597:                    lock.releaseLock();
1598:                }
1599:            }
1600:
1601:            /**
1602:             * Add an array of library references to a project, qualified for both the design-time classpath or deployed with the application
1603:             * @param project Project to which the library is to be added
1604:             * @param library Library object from the LibraryManager registry
1605:             * @return Returns true if the library reference was successfully added
1606:             * @throws an IOException if there was a problem adding the reference
1607:             */
1608:            public static boolean addLibraryReferences(Project project,
1609:                    Library[] libraries) throws IOException {
1610:                try {
1611:                    return ProjectClassPathModifier.addLibraries(libraries,
1612:                            getSourceRoot(project), ClassPath.COMPILE);
1613:                } catch (IOException e) {
1614:                    // Should continue here, many exceptions happened in NetBeans codes are not fatal.
1615:                }
1616:
1617:                return false;
1618:            }
1619:
1620:            /**
1621:             * Add an array of library references to a project, qualified by the type parameter.
1622:             * @param project Project to which the library is to be added
1623:             * @param library Library object from the LibraryManager registry
1624:             * @param type Determines whether the library is to be added to the design-time classpath or deployed
1625:             * with the application
1626:             * @return Returns true if the library reference was successfully added
1627:             * @throws an IOException if there was a problem adding the reference
1628:             */
1629:            public static boolean addLibraryReferences(Project project,
1630:                    Library[] libraries, String type) throws IOException {
1631:                WebProjectLibrariesModifier wplm = (WebProjectLibrariesModifier) project
1632:                        .getLookup().lookup(WebProjectLibrariesModifier.class);
1633:                if (wplm == null) {
1634:                    // Something is wrong, shouldn't be here.
1635:                    return addLibraryReferences(project, libraries);
1636:                }
1637:
1638:                if (ClassPath.COMPILE.equals(type)) {
1639:                    return wplm.addCompileLibraries(libraries);
1640:                } else if (ClassPath.EXECUTE.equals(type)) {
1641:                    return wplm.addPackageLibraries(libraries, PATH_IN_WAR_LIB);
1642:                }
1643:
1644:                return false;
1645:            }
1646:
1647:            /**
1648:             * Remove an array of library references from a project, qualified for both the design-time classpath or deployed with the application
1649:             * @param project Project from which the library references are to be removed
1650:             * @param library Array of Library objects from the LibraryManager registry
1651:             * @return Returns true if at least one of the library references were successfully removed
1652:             * @throws an IOException if there was a problem removing the reference
1653:             */
1654:            public static boolean removeLibraryReferences(Project project,
1655:                    Library[] libraries) throws IOException {
1656:                try {
1657:                    return ProjectClassPathModifier.removeLibraries(libraries,
1658:                            getSourceRoot(project), ClassPath.COMPILE);
1659:                } catch (IOException e) {
1660:                    // Should continue here, many exceptions happened in NetBeans codes are not fatal.
1661:                }
1662:
1663:                return false;
1664:            }
1665:
1666:            /**
1667:             * Remove an array of library references from a project, qualified by the type parameter.
1668:             * @param project Project from which the library references are to be removed
1669:             * @param library Array of Library objects from the LibraryManager registry
1670:             * @param type Determines whether the library is to be removed from the design-time classpath or deployed
1671:             * with the application
1672:             * @return Returns true if at least one of the library references were successfully removed
1673:             * @throws an IOException if there was a problem removing the reference
1674:             */
1675:            public static boolean removeLibraryReferences(Project project,
1676:                    Library[] libraries, String type) throws IOException {
1677:                WebProjectLibrariesModifier wplm = (WebProjectLibrariesModifier) project
1678:                        .getLookup().lookup(WebProjectLibrariesModifier.class);
1679:                if (wplm == null) {
1680:                    // Something is wrong, shouldn't be here.
1681:                    return removeLibraryReferences(project, libraries);
1682:                }
1683:
1684:                if (ClassPath.COMPILE.equals(type)) {
1685:                    return wplm.removeCompileLibraries(libraries);
1686:                } else if (ClassPath.EXECUTE.equals(type)) {
1687:                    return wplm.removePackageLibraries(libraries,
1688:                            PATH_IN_WAR_LIB);
1689:                }
1690:
1691:                return false;
1692:            }
1693:
1694:            /**
1695:             * Check if a project has a library reference to the named library qualified for both the design-time classpath or deployed with the application
1696:             * @param project Target project
1697:             * @param library Library object
1698:             * @return Returns true if the library is already referenced by the project, false otherwise
1699:             */
1700:            public static boolean hasLibraryReference(Project project,
1701:                    Library library) {
1702:                return hasLibraryReference(project, library, ClassPath.COMPILE);
1703:            }
1704:
1705:            /**
1706:             * Check if a project has a library reference to the named library qualified by the type parameter.
1707:             * @param project Target project
1708:             * @param library Library object
1709:             * @param type Determines whether the library is to be referenced from the design-time classpath or deploy
1710:             * time classpath
1711:             * @return Returns true if the library is already referenced by the project, false otherwise
1712:             */
1713:            public static boolean hasLibraryReference(Project project,
1714:                    Library library, String type) {
1715:                List lst = library.getContent("classpath");
1716:                if (lst.isEmpty()) {
1717:                    return false;
1718:                }
1719:
1720:                URL url = (URL) lst.get(0);
1721:                FileObject obj = URLMapper.findFileObject(url);
1722:                if (obj == null) {
1723:                    return false;
1724:                }
1725:
1726:                // XXX NetBeans API not finished yet
1727:                type = ClassPath.COMPILE;
1728:                ClassPath cp = ClassPath.getClassPath(getSourceRoot(project),
1729:                        type);
1730:                if (cp == null) {
1731:                    return false;
1732:                }
1733:
1734:                return cp.contains(obj);
1735:            }
1736:
1737:            /**
1738:             * Add an root reference to a project qualified for both the design-time classpath or deployed with the application
1739:             * @param project Project to which the root is to be added
1740:             * @param rootFile file object of the root
1741:             * @return Returns true if the root was successfully added
1742:             * @throws an IOException if there was a problem adding the reference
1743:             */
1744:            public static boolean addRootReferences(Project project,
1745:                    URL[] rootFiles) throws IOException {
1746:                try {
1747:                    return ProjectClassPathModifier.addRoots(rootFiles,
1748:                            getSourceRoot(project), ClassPath.COMPILE);
1749:                } catch (IOException e) {
1750:                    // Should continue here, many exceptions happened in NetBeans codes are not fatal.
1751:                }
1752:
1753:                return false;
1754:            }
1755:
1756:            /**
1757:             * Add an root reference to a project qualified by the type parameter.
1758:             * @param project Project to which the root is to be added
1759:             * @param rootFile file object of the root
1760:             * @param type Determines whether the root is to be added to the design-time classpath or deployed
1761:             * with the application
1762:             * @return Returns true if the root was successfully added
1763:             * @throws an IOException if there was a problem adding the reference
1764:             */
1765:            public static boolean addRootReferences(Project project,
1766:                    URL[] rootFiles, String type) throws IOException {
1767:                WebProjectLibrariesModifier wplm = (WebProjectLibrariesModifier) project
1768:                        .getLookup().lookup(WebProjectLibrariesModifier.class);
1769:                if (wplm == null) {
1770:                    // Something is wrong, shouldn't be here.
1771:                    return addRootReferences(project, rootFiles);
1772:                }
1773:
1774:                if (ClassPath.COMPILE.equals(type)) {
1775:                    return wplm.addCompileRoots(rootFiles);
1776:                } else if (ClassPath.EXECUTE.equals(type)) {
1777:                    return wplm.addPackageRoots(rootFiles, PATH_IN_WAR_LIB);
1778:                }
1779:
1780:                return false;
1781:            }
1782:
1783:            /**
1784:             * Remove an array of root references from a project qualified for both the design-time classpath or deployed with the application
1785:             * @param project Project from which the root references is to be removed
1786:             * @param rootFile file object of the root
1787:             * @return Returns true if at least one of the roots was successfully removed
1788:             * @throws an IOException if there was a problem removing the references
1789:             */
1790:            public static boolean removeRootReferences(Project project,
1791:                    URL[] rootFiles) throws IOException {
1792:                try {
1793:                    return ProjectClassPathModifier.removeRoots(rootFiles,
1794:                            getSourceRoot(project), ClassPath.COMPILE);
1795:                } catch (IOException e) {
1796:                    // Should continue here, many exceptions happened in NetBeans codes are not fatal.
1797:                }
1798:
1799:                return false;
1800:            }
1801:
1802:            /**
1803:             * Remove an array of root references from a project qualified by the type parameter.
1804:             * @param project Project from which the root references is to be removed
1805:             * @param rootFile file object of the root
1806:             * @param type Determines whether the root is to be removed from the design-time classpath or deploy
1807:             * time classpath
1808:             * @return Returns true if at least one of the roots was successfully removed
1809:             * @throws an IOException if there was a problem removing the references
1810:             */
1811:            public static boolean removeRootReferences(Project project,
1812:                    URL[] rootFiles, String type) throws IOException {
1813:                WebProjectLibrariesModifier wplm = (WebProjectLibrariesModifier) project
1814:                        .getLookup().lookup(WebProjectLibrariesModifier.class);
1815:                if (wplm == null) {
1816:                    // Something is wrong, shouldn't be here.
1817:                    return removeRootReferences(project, rootFiles);
1818:                }
1819:
1820:                if (ClassPath.COMPILE.equals(type)) {
1821:                    return wplm.removeCompileRoots(rootFiles);
1822:                } else if (ClassPath.EXECUTE.equals(type)) {
1823:                    return wplm.removePackageRoots(rootFiles, PATH_IN_WAR_LIB);
1824:                }
1825:
1826:                return false;
1827:            }
1828:
1829:            /**
1830:             * Check if a project has an root reference to the named root qualified for both the design-time classpath or deployed with the application
1831:             * @param project Target project
1832:             * @param rootFile file object of the root
1833:             * @return Returns true if the root is already referenced by the project, false otherwise
1834:             */
1835:            public static boolean hasRootReference(Project project, URL rootFile) {
1836:                return hasRootReference(project, rootFile, ClassPath.COMPILE);
1837:            }
1838:
1839:            /**
1840:             * Check if a project has an root reference to the named root qualified by the type parameter.
1841:             * @param project Target project
1842:             * @param rootFile file object of the root
1843:             * @param type Determines whether the root is to be referenced from the design-time classpath or deploy
1844:             * time classpath
1845:             * @return Returns true if the root is already referenced by the project, false otherwise
1846:             */
1847:            public static boolean hasRootReference(Project project,
1848:                    URL rootFile, String type) {
1849:                FileObject obj = URLMapper.findFileObject(rootFile);
1850:                if (obj == null) {
1851:                    return false;
1852:                }
1853:
1854:                // XXX NetBeans API not finished yet
1855:                type = ClassPath.COMPILE;
1856:                ClassPath cp = ClassPath.getClassPath(getSourceRoot(project),
1857:                        type);
1858:
1859:                return cp.contains(obj);
1860:            }
1861:
1862:            public static void addLocalizedRoots(Project project,
1863:                    String[] jarName) throws IOException {
1864:                addLocalizedRoots(project, jarName, ClassPath.COMPILE);
1865:            }
1866:
1867:            public static void addLocalizedRoots(Project project,
1868:                    String[] jarName, String type) throws IOException {
1869:                ArrayList jars = new ArrayList(jarName.length);
1870:                for (int i = 0; i < jarName.length; i++) {
1871:                    File f = InstalledFileLocator.getDefault().locate(
1872:                            jarName[i], null, true);
1873:                    if (f != null) {
1874:                        URL root = FileUtil.getArchiveRoot(
1875:                                FileUtil.toFileObject(f)).getURL();
1876:                        if (!hasRootReference(project, root, type)) {
1877:                            jars.add(root);
1878:                        }
1879:                    }
1880:                }
1881:                addRootReferences(project, (URL[]) jars.toArray(new URL[0]),
1882:                        type);
1883:            }
1884:
1885:            public static void addLocalizedRoots(Project project, URL[] roots,
1886:                    String type) throws IOException {
1887:                ArrayList<URL> jars = new ArrayList<URL>(roots.length);
1888:                for (URL root : roots) {
1889:                    if (!hasRootReference(project, root, type)) {
1890:                        jars.add(root);
1891:                    }
1892:                }
1893:                addRootReferences(project, (URL[]) jars.toArray(new URL[0]),
1894:                        type);
1895:            }
1896:
1897:            public static void updateLocalizedRoots(Project project) {
1898:                try {
1899:                    JsfProjectLibrary.updateLocalizedRoots(project);
1900:                } catch (Exception e) {
1901:                    ErrorManager.getDefault().notify(e);
1902:                }
1903:            }
1904:
1905:            public static void addLocalizedTheme(Project project,
1906:                    String themeName) throws IOException {
1907:                URL root = JsfProjectLibrary.getLocalizedThemeRoot(project,
1908:                        themeName);
1909:                if (root != null) {
1910:                    if (!hasRootReference(project, root)) {
1911:                        addRootReferences(project, new URL[] { root });
1912:                    }
1913:                }
1914:            }
1915:
1916:            public static void removeLocalizedTheme(Project project,
1917:                    String themeName) throws IOException {
1918:                URL root = JsfProjectLibrary.getLocalizedThemeRoot(project,
1919:                        themeName);
1920:                if (root != null) {
1921:                    if (hasRootReference(project, root)) {
1922:                        removeRootReferences(project, new URL[] { root });
1923:                    }
1924:                }
1925:            }
1926:
1927:            public static Library createJ2SELibrary(String name,
1928:                    String description, String localizingBundle,
1929:                    List<URL> classPaths, List<URL> sources, List<URL> javadocs)
1930:                    throws IOException {
1931:                return J2SELibraryDefinition.create(name, description,
1932:                        localizingBundle, classPaths, sources, javadocs);
1933:            }
1934:
1935:            public static Library createComponentLibrary(String name,
1936:                    String description, String localizingBundle,
1937:                    List<URL> classPaths, List<URL> sources,
1938:                    List<URL> javadocs, List<URL> designtimes)
1939:                    throws IOException {
1940:                return ComponentLibraryDefinition.create(name, description,
1941:                        localizingBundle, classPaths, sources, javadocs,
1942:                        designtimes);
1943:            }
1944:
1945:            public static void removeLibrary(String name) throws IOException {
1946:                LibraryDefinition.remove(name);
1947:            }
1948:
1949:            public static boolean isDesigntimeLib(String name) {
1950:                return JsfProjectLibrary.isDesigntimeLib(name);
1951:            }
1952:
1953:            public static String getBackwardsKitMesg(boolean addJSF11,
1954:                    boolean addJAXRPC, boolean addRowset) {
1955:                int count = 0;
1956:                String nbms = "";
1957:                if (addJSF11) {
1958:                    count++;
1959:                    nbms = NbBundle.getMessage(JsfProjectUtils.class,
1960:                            "LBL_MissingJSF");
1961:                }
1962:                if (addJAXRPC) {
1963:                    count++;
1964:                    nbms += NbBundle.getMessage(JsfProjectUtils.class,
1965:                            "LBL_MissingJAXRPC");
1966:                }
1967:                if (addRowset) {
1968:                    count++;
1969:                    nbms += NbBundle.getMessage(JsfProjectUtils.class,
1970:                            "LBL_MissingRowset");
1971:                }
1972:
1973:                String RI = NbBundle.getMessage(JsfProjectUtils.class,
1974:                        (count > 1) ? "LBL_MissingMany" : "LBL_MissingOne");
1975:
1976:                return NbBundle.getMessage(JsfProjectUtils.class,
1977:                        "LBL_MissingNBM", RI, nbms);
1978:            }
1979:
1980:            /** Reports whether the given name is a valid Java file name.
1981:             * @param name The Java file name to be checked
1982:             * @return true iff the name parameter is a valid Java file name
1983:             * @todo Use the passed in project context to make sure that the
1984:             *   name would not conflict with existing files (e.g. check
1985:             *   the webforms and backing file folders for name conflicts).
1986:             */
1987:            public static boolean isValidJavaFileName(String name) {
1988:                if (name == null) {
1989:                    return false;
1990:                }
1991:                int n = name.length();
1992:                if (n == 0) {
1993:                    return false;
1994:                }
1995:
1996:                if (!Character.isJavaIdentifierStart(name.charAt(0))) {
1997:                    return false;
1998:                }
1999:
2000:                for (int i = 1; i < n; i++) {
2001:                    char c = name.charAt(i);
2002:                    if (!Character.isJavaIdentifierPart(c)) {
2003:                        return false;
2004:                    }
2005:                }
2006:
2007:                if (!Utilities.isJavaIdentifier(name)) {
2008:                    return false;
2009:                }
2010:
2011:                return true;
2012:            }
2013:
2014:            /** Reports whether the given name is a valid Java package name.
2015:             * @param name The Java package name to be checked
2016:             * @return true iff the name parameter is a valid Java package name
2017:             */
2018:            public static boolean isValidJavaPackageName(String pkgName) {
2019:                if (pkgName == null)
2020:                    return false;
2021:
2022:                String[] pkg = pkgName.split("\\.");
2023:                for (int i = 0; i < pkg.length; i++) {
2024:                    if (!Utilities.isJavaIdentifier(pkg[i])) {
2025:                        return false;
2026:                    }
2027:                }
2028:
2029:                return true;
2030:            }
2031:
2032:            /**
2033:             * Derive an identifier suitable for a java package name or context path
2034:             * @param sourceName Original name from which to derive the name
2035:             * @return An identifier suitable for a java package name or context path
2036:             */
2037:            public static String deriveSafeName(String sourceName) {
2038:                StringBuffer dest = new StringBuffer(sourceName.length());
2039:                int sourceLen = sourceName.length();
2040:                if (sourceLen > 0) {
2041:                    int pos = 0;
2042:                    while (pos < sourceLen) {
2043:                        if (Character.isJavaIdentifierStart(sourceName
2044:                                .charAt(pos))) {
2045:                            dest.append(Character.toLowerCase(sourceName
2046:                                    .charAt(pos)));
2047:                            pos++;
2048:                            break;
2049:                        }
2050:                        pos++;
2051:                    }
2052:
2053:                    for (int i = pos; i < sourceLen; i++) {
2054:                        if (Character
2055:                                .isJavaIdentifierPart(sourceName.charAt(i)))
2056:                            dest.append(Character.toLowerCase(sourceName
2057:                                    .charAt(i)));
2058:                    }
2059:                }
2060:                if (dest.length() == 0
2061:                        || !Utilities.isJavaIdentifier(dest.toString()))
2062:                    return "untitled"; // NOI18N
2063:                else
2064:                    return dest.toString();
2065:            }
2066:
2067:            /**
2068:             *
2069:             * This does a special instantiation of JFileChooser
2070:             * to workaround floppy access bug 5037322.
2071:             * Using privileged code block.
2072:             */
2073:            public static JFileChooser getJFileChooser() {
2074:                return (JFileChooser) AccessController
2075:                        .doPrivileged(new PrivilegedAction() {
2076:                            public Object run() {
2077:                                return new JFileChooser();
2078:                            }
2079:                        });
2080:            }
2081:
2082:            public static JFileChooser getJFileChooser(
2083:                    final String currentDirectoryPath) {
2084:                return (JFileChooser) AccessController
2085:                        .doPrivileged(new PrivilegedAction() {
2086:                            public Object run() {
2087:                                return new JFileChooser(currentDirectoryPath);
2088:                            }
2089:                        });
2090:            }
2091:
2092:            public static JFileChooser getJFileChooser(
2093:                    final File currentDirectory) {
2094:                return (JFileChooser) AccessController
2095:                        .doPrivileged(new PrivilegedAction() {
2096:                            public Object run() {
2097:                                return new JFileChooser(currentDirectory);
2098:                            }
2099:                        });
2100:            }
2101:
2102:            public static LibraryManager getProjectLibraryManager(
2103:                    Project project) {
2104:                LibraryManager lm = ReferenceHelper
2105:                        .getProjectLibraryManager(project);
2106:                if (lm != null) {
2107:                    return lm;
2108:                }
2109:                return LibraryManager.getDefault();
2110:            }
2111:
2112:        }
w__w__w_.j_a_v_a__2__s___._c__om_ | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.