Source Code Cross Referenced for DatabaseSettingsImporter.java in  » IDE-Netbeans » visualweb.api.designer » org » netbeans » modules » visualweb » dataconnectivity » naming » 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.dataconnectivity.naming 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003:         *
004:         * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005:         *
006:         * The contents of this file are subject to the terms of either the GNU
007:         * General Public License Version 2 only ("GPL") or the Common
008:         * Development and Distribution License("CDDL") (collectively, the
009:         * "License"). You may not use this file except in compliance with the
010:         * License. You can obtain a copy of the License at
011:         * http://www.netbeans.org/cddl-gplv2.html
012:         * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
013:         * specific language governing permissions and limitations under the
014:         * License.  When distributing the software, include this License Header
015:         * Notice in each file and include the License file at
016:         * nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
017:         * particular file as subject to the "Classpath" exception as provided
018:         * by Sun in the GPL Version 2 section of the License file that
019:         * accompanied this code. If applicable, add the following below the
020:         * License Header, with the fields enclosed by brackets [] replaced by
021:         * your own identifying information:
022:         * "Portions Copyrighted [year] [name of copyright owner]"
023:         *
024:         * Contributor(s):
025:         *
026:         * The Original Software is NetBeans. The Initial Developer of the Original
027:         * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
028:         * Microsystems, Inc. All Rights Reserved.
029:         *
030:         * If you wish your version of this file to be governed by only the CDDL
031:         * or only the GPL Version 2, indicate your decision by adding
032:         * "[Contributor] elects to include this software in this distribution
033:         * under the [CDDL or GPL Version 2] license." If you do not indicate a
034:         * single choice of license, a recipient has the option to distribute
035:         * your version of this file under either the CDDL, the GPL Version 2 or
036:         * to extend the choice of license to its licensees as provided above.
037:         * However, if you add GPL Version 2 code and therefore, elected the GPL
038:         * Version 2 license, then the option applies only if the new code is
039:         * made subject to such option by the copyright holder.
040:         */
041:
042:        package org.netbeans.modules.visualweb.dataconnectivity.naming;
043:
044:        import org.netbeans.modules.visualweb.dataconnectivity.utils.*;
045:        import java.io.File;
046:        import java.io.FilenameFilter;
047:        import java.io.IOException;
048:        import java.net.URL;
049:        import java.util.ArrayList;
050:        import java.util.Collections;
051:        import java.util.HashSet;
052:        import java.util.Iterator;
053:        import java.util.LinkedList;
054:        import java.util.List;
055:        import java.util.Locale;
056:        import java.util.ResourceBundle;
057:        import java.util.Set;
058:        import java.util.jar.JarFile;
059:        import javax.crypto.Cipher;
060:        import javax.crypto.SecretKey;
061:        import javax.crypto.spec.SecretKeySpec;
062:        import javax.xml.parsers.ParserConfigurationException;
063:        import javax.xml.parsers.SAXParser;
064:        import javax.xml.parsers.SAXParserFactory;
065:        import org.netbeans.api.db.explorer.ConnectionManager;
066:        import org.netbeans.api.db.explorer.DatabaseConnection;
067:        import org.netbeans.api.db.explorer.DatabaseException;
068:        import org.netbeans.api.db.explorer.JDBCDriver;
069:        import org.netbeans.api.db.explorer.JDBCDriverManager;
070:        import org.netbeans.api.project.Project;
071:        import org.netbeans.modules.j2ee.dd.api.common.NameAlreadyUsedException;
072:        import org.netbeans.modules.j2ee.dd.api.common.ResourceRef;
073:        import org.netbeans.modules.j2ee.dd.api.web.DDProvider;
074:        import org.netbeans.modules.j2ee.dd.api.web.WebApp;
075:        import org.netbeans.modules.visualweb.api.j2ee.common.RequestedJdbcResource;
076:        import org.netbeans.modules.visualweb.api.j2ee.common.RequestedResource;
077:        import org.netbeans.modules.visualweb.dataconnectivity.datasource.DataSourceResolver;
078:        import org.netbeans.modules.visualweb.dataconnectivity.model.DataSourceInfo;
079:        import org.netbeans.modules.web.api.webmodule.WebModule;
080:        import org.openide.ErrorManager;
081:        import org.openide.cookies.SaveCookie;
082:        import org.openide.filesystems.FileObject;
083:        import org.openide.loaders.DataObject;
084:        import org.openide.loaders.DataObjectNotFoundException;
085:        import org.openide.util.Exceptions;
086:        import org.xml.sax.Attributes;
087:        import org.xml.sax.SAXException;
088:        import org.xml.sax.helpers.DefaultHandler;
089:
090:        /**
091:         * DatabaseSettingsImporter imports JDBC drivers and connections from previous Creator/visualweb releases then registers them in DB Explorer
092:         * @author John Baker
093:         */
094:        public class DatabaseSettingsImporter {
095:
096:            private static DatabaseSettingsImporter databaseSettingsImporter;
097:            public static final String ROOT_CTX_TAG = "rootContext"; // NOI18N
098:            public static final String CTX_TAG = "context"; // NOI18N
099:            public static final String OBJ_TAG = "object"; // NOI18N
100:            public static final String ARG_TAG = "arg"; // NOI18N
101:            public static final String NAME_ATTR = "name"; // NOI18N
102:            public static final String CLASS_ATTR = "class"; // NOI18N
103:            public static final String VALUE_ATTR = "value"; // NOI18N
104:            public static final String DRIVER_CLASS_NET = "org.apache.derby.jdbc.ClientDriver"; // NOI18N
105:            private File userCtxFile;
106:            private List<String[]> dataSources;
107:            List<DataSourceInfo> dataSourcesInfo;
108:            private List<File> driversList = new ArrayList<File>();
109:
110:            private static ResourceBundle rb = ResourceBundle
111:                    .getBundle(
112:                            "org.netbeans.modules.visualweb.dataconnectivity.naming.Bundle", // NOI18N
113:                            Locale.getDefault());
114:            private static String[] destPaths = new String[] {
115:                    "migrated" + File.separator + "context.xml",
116:                    "migrated" + File.separator + "2_0" + File.separator
117:                            + "context.xml",
118:                    "migrated" + File.separator + "2_1" + File.separator
119:                            + "context.xml",
120:                    "migrated" + File.separator + "5_5" + File.separator
121:                            + "context.xml",
122:                    "migrated" + File.separator + "5_5_1" + File.separator
123:                            + "context.xml" };
124:
125:            private static final String HACK_WELCOME_FILE = "JSCreator_index.jsp"; // NOI18N
126:
127:            /** Creates a new instance of DatabaseImporter */
128:            private DatabaseSettingsImporter() {
129:                dataSources = Collections
130:                        .synchronizedList(new ArrayList<String[]>());
131:                dataSourcesInfo = new ArrayList<DataSourceInfo>();
132:            }
133:
134:            /**
135:             * this class is a Singleton
136:             * @return
137:             */
138:            public static DatabaseSettingsImporter getInstance() {
139:                if (databaseSettingsImporter == null) {
140:                    databaseSettingsImporter = new DatabaseSettingsImporter();
141:                }
142:                return databaseSettingsImporter;
143:            }
144:
145:            /**
146:             * Obtain JDBC driver jars from previous release then register the drivers
147:             * @param isStartup 
148:             * @return
149:             */
150:            public boolean locateAndRegisterDrivers() {
151:                String driversPath = locateDrivers();
152:                if (driversPath.equals("")) // NOI18N
153:                    return false;
154:
155:                registerDrivers(driversToRegister(driversPath));
156:                return true;
157:            }
158:
159:            private String locateDrivers() {
160:                String driverLocation;
161:
162:                driverLocation = System.getProperty("netbeans.user")
163:                        + File.separator + "jdbc-drivers"; // NOI18N
164:                File driverDir = new File(driverLocation);
165:                if (driverDir == null)
166:                    return ""; // NOI18N
167:                if (driverDir.exists())
168:                    return driverLocation;
169:                else
170:                    return ""; // NOI18N
171:            }
172:
173:            private File[] driversToRegister(String driversPath) {
174:                File driverDir = new File(driversPath);
175:
176:                if (driverDir != null) {
177:                    File[] drivers = driverDir.listFiles(new FilenameFilter() {
178:                        public boolean accept(File dir, String name) {
179:                            return name.endsWith(".jar")
180:                                    || name.endsWith(".zip"); // NOI18N
181:                        }
182:                    });
183:
184:                    return drivers;
185:                } else {
186:                    return null;
187:                }
188:
189:            }
190:
191:            private synchronized JarFile prepareJar(File driverJarFile) {
192:                JarFile jarFile = null;
193:                try {
194:                    jarFile = new JarFile(driverJarFile);
195:                } catch (IOException ex) {
196:                    Exceptions.printStackTrace(ex);
197:                }
198:                return jarFile;
199:            }
200:
201:            private void registerDriver(File driverJar) {
202:                String[] drivers = (String[]) DriverListUtil
203:                        .getDrivers()
204:                        .toArray(new String[DriverListUtil.getDrivers().size()]);
205:
206:                try {
207:                    JarFile jf = prepareJar(driverJar);
208:                    if (jf != null) {
209:                        String drv;
210:                        Set drvs = DriverListUtil.getDrivers();
211:                        Iterator it = drvs.iterator();
212:                        while (it.hasNext()) {
213:                            drv = (String) it.next();
214:                            if (jf.getEntry(drv.replace('.', '/') + ".class") != null) {
215:                                //NOI18N
216:                                String driverName = DriverListUtil.getName(drv);
217:                                if (DataSourceResolver.getInstance()
218:                                        .findMatchingDriver(
219:                                                DriverListUtil
220:                                                        .getDriver(driverName)) != null) {
221:                                    break;
222:                                }
223:                                JDBCDriver driver = JDBCDriver
224:                                        .create(driverName, driverName, drv,
225:                                                new URL[] { driverJar.toURI()
226:                                                        .toURL() });
227:                                try {
228:                                    JDBCDriverManager.getDefault().addDriver(
229:                                            driver);
230:                                } catch (DatabaseException e) {
231:                                    ErrorManager.getDefault().notify(e);
232:                                }
233:                            }
234:                        }
235:                        jf.close();
236:                    }
237:
238:                } catch (IOException ioe) {
239:                    ErrorManager.getDefault().notify(ioe);
240:                }
241:            }
242:
243:            private void registerDrivers(File[] driverFiles) {
244:                for (File drv : driverFiles) {
245:                    if (!driversList.contains(drv)) {
246:                        registerDriver(drv);
247:                        driversList.add(drv);
248:                    }
249:                }
250:            }
251:
252:            /**
253:             * Obtain connection info from previous release's context.xml then register connections
254:             * @param isStartup flag indicates that settings were migrated at startup or not
255:             * @return
256:             */
257:            public boolean locateAndRegisterConnections(boolean isStartup) {
258:                File contextFile;
259:                Set<File> contextFiles = new HashSet<File>();
260:
261:                if (isStartup) {
262:                    destPaths = new String[] {
263:                            "2_0" + File.separator + "context.xml",
264:                            "2_1" + File.separator + "context.xml",
265:                            "5_5" + File.separator + "context.xml",
266:                            "5_5_1" + File.separator + "context.xml" };
267:                    contextFile = retrieveMigratedSettingsAtStartup();
268:                    if (contextFile != null) {
269:                        registerConnections(contextFile);
270:                    }
271:                } else {
272:                    for (int i = 0; i < destPaths.length; i++) {
273:                        File ctxtFile = new File(System
274:                                .getProperty("netbeans.user")
275:                                + File.separator
276:                                + "config"
277:                                + File.separator
278:                                + destPaths[i]);
279:                        if (ctxtFile.exists()) {
280:                            contextFiles.add(ctxtFile);
281:                        }
282:                    }
283:
284:                    registerConnections(contextFiles);
285:                }
286:
287:                return true;
288:            }
289:
290:            public File retrieveMigratedSettingsAtStartup() {
291:                File contextReleaseRoot = new File(System
292:                        .getProperty("netbeans.user")
293:                        + File.separator + "config" + File.separator); // NOI18N        
294:                File[] configDirs = null;
295:
296:                configDirs = contextReleaseRoot.listFiles();
297:                File contextFile = null;
298:                for (int i = 0; i < configDirs.length; i++) {
299:                    File[] contextReleaseDirFiles = configDirs[i].listFiles();
300:
301:                    if (contextReleaseDirFiles == null) {
302:                        return null;
303:                    }
304:                    for (File releaseDir : contextReleaseDirFiles) {
305:                        String fileName = releaseDir.getName();
306:                        if (fileName.equals("context.xml")) {
307:                            contextFile = contextReleaseDirFiles[i];
308:                            break;
309:                        }
310:                    }
311:                }
312:
313:                return contextFile;
314:            }
315:
316:            public Set<File> locateMigratedSettings() {
317:                File contextReleaseRoot = new File(System
318:                        .getProperty("netbeans.user")); // NOI18N
319:                File[] contextFileDirs = null;
320:                Set<File> contextReleaseDirFiles = new HashSet<File>();
321:                File migratedDir = new File(contextReleaseRoot
322:                        .getAbsolutePath()
323:                        + File.separator + "migrated");
324:
325:                if (migratedDir == null || !migratedDir.exists()
326:                        || !migratedDir.isDirectory()) {
327:                    return null;
328:                }
329:
330:                contextFileDirs = migratedDir.listFiles();
331:                for (File releaseDir : contextFileDirs) {
332:                    contextReleaseDirFiles.add(releaseDir);
333:                }
334:
335:                return contextReleaseDirFiles;
336:            }
337:
338:            private void registerConnections(File contextFile) {
339:                dataSourcesInfo = createDataSourceInfoFromCtx(contextFile);
340:
341:                if (dataSourcesInfo != null) {
342:                    try {
343:                        Iterator it = dataSourcesInfo.iterator();
344:                        DataSourceInfo dsInfo = null;
345:                        DatabaseConnection dbconn = null;
346:                        JDBCDriver drvs = null;
347:                        JDBCDriver[] drvsArray = null;
348:
349:                        // From each Data Source, add a connection to DB Explorer
350:                        while (it.hasNext()) {
351:                            dsInfo = ((DataSourceInfo) it.next());
352:                            String username = dsInfo.getUsername();
353:                            String password = dsInfo.getPassword();
354:
355:                            // To register a Derby connection, no need to check to see if Java DB driver had been registered
356:                            if (dsInfo.getDriverClassName().equals(
357:                                    DRIVER_CLASS_NET)) {
358:                                if (!dsInfo.getName().equals("Travel")
359:                                        && !dsInfo.getName().equals("VIR")
360:                                        && !dsInfo.getName().equals(
361:                                                "JumpStartCycles")) { //NOI18N
362:                                    drvsArray = JDBCDriverManager.getDefault()
363:                                            .getDrivers(DRIVER_CLASS_NET);
364:                                    dbconn = DatabaseConnection.create(
365:                                            drvsArray[0], dsInfo.getUrl(),
366:                                            username, username.toUpperCase(),
367:                                            password, true);
368:                                    ConnectionManager.getDefault()
369:                                            .addConnection(dbconn);
370:                                }
371:                            } else {
372:                                drvs = DataSourceResolver.getInstance()
373:                                        .findMatchingDriver(
374:                                                dsInfo.getDriverClassName());
375:                                if (drvs != null) {
376:                                    dbconn = DatabaseConnection.create(drvs,
377:                                            dsInfo.getUrl(), username, username
378:                                                    .toUpperCase(), password,
379:                                            true);
380:                                    ConnectionManager.getDefault()
381:                                            .addConnection(dbconn);
382:                                }
383:                            }
384:                        }
385:                    } catch (DatabaseException de) {
386:                        ErrorManager.getDefault().notify(
387:                                ErrorManager.INFORMATIONAL, de);
388:                    }
389:                }
390:            }
391:
392:            private void registerConnections(Set<File> contextFiles) {
393:                if (contextFiles == null) {
394:                    return;
395:                }
396:
397:                Iterator it = contextFiles.iterator();
398:                while (it.hasNext()) {
399:                    dataSourcesInfo = createDataSourceInfoFromCtx((File) it
400:                            .next());
401:
402:                    try {
403:                        Iterator itDataSource = dataSourcesInfo.iterator();
404:                        DataSourceInfo dsInfo = null;
405:                        boolean isDriverJavaDB = false;
406:                        DatabaseConnection dbconn = null;
407:                        JDBCDriver drvs = null;
408:                        JDBCDriver[] drvsArray = null;
409:
410:                        // From each Data Source, add a connection to DB Explorer
411:                        while (itDataSource.hasNext()) {
412:                            dsInfo = ((DataSourceInfo) itDataSource.next());
413:                            String username = dsInfo.getUsername();
414:                            String password = dsInfo.getPassword();
415:                            isDriverJavaDB = dsInfo.getDriverClassName()
416:                                    .equals(DRIVER_CLASS_NET);
417:
418:                            // To register a Derby connection, no need to check to see if Java DB driver had been registered
419:                            if (dsInfo.getDriverClassName().equals(
420:                                    DRIVER_CLASS_NET)) {
421:                                if (!dsInfo.getName().equals("Travel")
422:                                        && !dsInfo.getName().equals("VIR")
423:                                        && !dsInfo.getName().equals(
424:                                                "JumpStartCycles")) { //NOI18N
425:                                    drvsArray = JDBCDriverManager.getDefault()
426:                                            .getDrivers(DRIVER_CLASS_NET);
427:                                    dbconn = DatabaseConnection.create(
428:                                            drvsArray[0], dsInfo.getUrl(),
429:                                            username, username.toUpperCase(),
430:                                            password, true);
431:                                    ConnectionManager.getDefault()
432:                                            .addConnection(dbconn);
433:                                }
434:                            } else {
435:                                drvs = DataSourceResolver.getInstance()
436:                                        .findMatchingDriver(
437:                                                dsInfo.getDriverClassName());
438:                                if (drvs != null) {
439:                                    dbconn = DatabaseConnection.create(drvs,
440:                                            dsInfo.getUrl(), username, username
441:                                                    .toUpperCase(), password,
442:                                            true);
443:                                    ConnectionManager.getDefault()
444:                                            .addConnection(dbconn);
445:                                } else if (dsInfo.getDriverClassName().equals(
446:                                        "oracle.jdbc.driver.OracleDriver")) { //NOI18N
447:                                    drvs = DataSourceResolver.getInstance()
448:                                            .findMatchingDriver(
449:                                                    "oracle.jdbc.OracleDriver"); //NOI18N
450:                                    dbconn = DatabaseConnection.create(drvs,
451:                                            dsInfo.getUrl(), username, username
452:                                                    .toUpperCase(), password,
453:                                            true);
454:                                    ConnectionManager.getDefault()
455:                                            .addConnection(dbconn);
456:                                }
457:                            }
458:                        }
459:                    } catch (DatabaseException de) {
460:                        ErrorManager.getDefault().notify(
461:                                ErrorManager.INFORMATIONAL, de);
462:                    }
463:                }
464:            }
465:
466:            static private SecretKey secretKey = null;
467:
468:            static final private char[] secretKeyHex = { 'D', '6', '0', '7',
469:                    '5', 'E', '2', '9', '8', 'A', '4', '9', '6', '2', '5', '1' };
470:
471:            private static SecretKey getSecretKey() {
472:                if (secretKey == null) {
473:                    byte[] encodedKey = new byte[secretKeyHex.length / 2];
474:                    for (int i = 0; i < encodedKey.length; i++) {
475:                        encodedKey[i] = hexToByte(secretKeyHex[i * 2],
476:                                secretKeyHex[i * 2 + 1]);
477:                    }
478:                    secretKey = new SecretKeySpec(encodedKey, "DES"); // NOI18N
479:                }
480:
481:                return secretKey;
482:            }
483:
484:            private static final String hexString = "0123456789ABCDEF"; // NOI18N
485:
486:            private static byte hexToByte(char char1, char char2) {
487:                return (byte) ((hexString.indexOf(char1) << 4) + hexString
488:                        .indexOf(char2));
489:            }
490:
491:            private String decryptPassword(String password) {
492:
493:                if (password == null) {
494:                    return null;
495:                }
496:
497:                try {
498:                    char[] hexChars = password.toCharArray();
499:
500:                    byte[] encryptedBytes = new byte[hexChars.length / 2];
501:                    for (int i = 0; i < encryptedBytes.length; i++) {
502:                        encryptedBytes[i] = hexToByte(hexChars[i * 2],
503:                                hexChars[i * 2 + 1]);
504:                    }
505:                    Cipher cipher = Cipher.getInstance("DES"); // NOI18N
506:                    cipher.init(Cipher.DECRYPT_MODE, getSecretKey());
507:                    byte[] passwordBytes = cipher.doFinal(encryptedBytes);
508:                    return new String(passwordBytes);
509:                } catch (Exception e) {
510:                    ErrorManager.getDefault().notify(
511:                            ErrorManager.INFORMATIONAL, e);
512:                    return "";
513:                }
514:            }
515:
516:            private DataSourceInfo createDataSourceInfo(String[] dataSource) {
517:                String dsName = dataSource[0];
518:                String driverClassName = dataSource[1];
519:                String driverUrl = dataSource[2];
520:                String username = dataSource[3];
521:                String password = dataSource[4];
522:
523:                // create data source info
524:                password = decryptPassword(password);
525:
526:                if (driverClassName.equals(DRIVER_CLASS_NET)) { // NOI18N
527:                    int oldPortLoc = driverUrl.indexOf(":21527"); // NOI18N
528:                    if (oldPortLoc != -1) { // NOI18N
529:                        String beginURL = driverUrl.substring(0, oldPortLoc);
530:                        String endURL = driverUrl.substring(driverUrl
531:                                .lastIndexOf(":21527") + 6, driverUrl.length()); // NOI18N
532:                        driverUrl = beginURL + ":1527" + endURL; // NOI18N
533:                    }
534:                }
535:                return new DataSourceInfo(dsName, driverClassName, driverUrl,
536:                        "", username, password);
537:            }
538:
539:            private ArrayList<DataSourceInfo> createDataSourceInfoFromCtx(
540:                    File contextFile) {
541:                ArrayList<DataSourceInfo> dsInfo = new ArrayList<DataSourceInfo>();
542:
543:                try {
544:                    userCtxFile = contextFile;
545:                    parseContextFile();
546:                } catch (ParserConfigurationException ex) {
547:                    Exceptions.printStackTrace(ex);
548:                } catch (SAXException ex) {
549:                    Exceptions.printStackTrace(ex);
550:                } catch (IOException ex) {
551:                    Exceptions.printStackTrace(ex);
552:                }
553:
554:                // extract data source info from each datasource ArrayList
555:
556:                String[] dataSource = new String[5];
557:
558:                synchronized (dataSources) {
559:                    Iterator itDss = dataSources.iterator();
560:                    while (itDss.hasNext()) {
561:                        dataSource = (String[]) itDss.next();
562:                        dsInfo.add(createDataSourceInfo(dataSource));
563:                    }
564:                }
565:
566:                return dsInfo;
567:            }
568:
569:            private void storeArgs(ArrayList args) {
570:                String[] dsItems = new String[5];
571:
572:                Iterator it = args.iterator();
573:                int i = 0;
574:                int cnt = 0;
575:                while (it.hasNext()) {
576:                    // exclude unneeded items of data source
577:                    if ((cnt == 1) || (cnt == 2) || (cnt == 3) || (cnt == 6))
578:                        it.next();
579:                    else
580:                        dsItems[i++] = (String) it.next();
581:
582:                    cnt++;
583:                }
584:
585:                dataSources.add(dsItems);
586:            }
587:
588:            private synchronized void parseContextFile()
589:                    throws ParserConfigurationException, SAXException,
590:                    IllegalArgumentException, IOException {
591:                SAXParserFactory factory = SAXParserFactory.newInstance();
592:                factory.setNamespaceAware(true);
593:                factory.setValidating(false);
594:                SAXParser parser = factory.newSAXParser();
595:                final ArrayList storArgs = new ArrayList();
596:
597:                parser.parse(userCtxFile, new DefaultHandler() {
598:                    private String objectName;
599:                    private String className;
600:                    private int tagCount = 0;
601:                    ArrayList<String> args = new ArrayList<String>();
602:
603:                    public void startElement(String uri, String localName,
604:                            String qName, Attributes attributes)
605:                            throws SAXException {
606:
607:                        if (qName.equals(OBJ_TAG)) {
608:                            objectName = attributes.getValue(NAME_ATTR);
609:
610:                            if (objectName != null) {
611:                                if (!args.isEmpty()) {
612:                                    storeArgs(args);
613:                                }
614:
615:                                args.clear();
616:                                args.add(objectName);
617:                            }
618:
619:                        } else if (qName.equals("arg")) { // NOI18N
620:                            String valueValue = attributes.getValue(VALUE_ATTR);
621:                            args.add(valueValue);
622:                        }
623:                    }
624:
625:                    public void endDocument() {
626:                        if (!args.isEmpty()) {
627:                            storeArgs(args);
628:                        }
629:                    }
630:                });
631:            }
632:
633:            public List<DataSourceInfo> getDataSourcesInfo() {
634:                return dataSourcesInfo;
635:            }
636:
637:            private WebApp getWebApp(FileObject f) {
638:                WebApp webApp = null;
639:
640:                if (f != null) {
641:                    // Make sure, we see any user/editor changes.
642:                    try {
643:                        DataObject deployDescDO = DataObject.find(f);
644:                        SaveCookie saveCookie = (SaveCookie) deployDescDO
645:                                .getCookie(SaveCookie.class);
646:
647:                        if (saveCookie != null) {
648:                            try {
649:                                saveCookie.save();
650:                            } catch (IOException e) {
651:                                ErrorManager.getDefault().notify(
652:                                        ErrorManager.INFORMATIONAL, e);
653:                            }
654:                        }
655:                    } catch (DataObjectNotFoundException e) {
656:                        ErrorManager.getDefault().notify(
657:                                ErrorManager.INFORMATIONAL, e);
658:                    }
659:
660:                    try {
661:                        webApp = DDProvider.getDefault().getDDRoot(f);
662:                    } catch (Exception e) {
663:                        // Ok do nothing for now.
664:                        ErrorManager.getDefault().notify(
665:                                ErrorManager.INFORMATIONAL, e);
666:                    }
667:                }
668:
669:                return webApp;
670:            }
671:
672:            /**
673:             * updateWebXml updates the resource reference with the datasources used in the project
674:             * @param project
675:             * @param ress
676:             *
677:             */
678:            public void updateWebXml(Project project,
679:                    List<RequestedResource> ress) {
680:                WebModule wmod = WebModule.getWebModule(project
681:                        .getProjectDirectory());
682:                FileObject deployDescFO = wmod.getDeploymentDescriptor();
683:                WebApp webApp = getWebApp(deployDescFO);
684:                boolean needWrite = false;
685:
686:                ResourceRef[] rscRefs = webApp.getResourceRef();
687:                List<RequestedResource> reqList = new LinkedList<RequestedResource>();
688:                Iterator itRess = ress.iterator();
689:                while (itRess.hasNext()) {
690:                    reqList.add((RequestedResource) itRess.next());
691:                }
692:
693:                // Resource Refs
694:                if (rscRefs == null) {
695:                    rscRefs = new ResourceRef[0];
696:                } // end of if (refs == null)
697:
698:                for (int i = 0; i < rscRefs.length; i++) {
699:                    boolean found = false;
700:                    Iterator it = reqList.iterator();
701:
702:                    while (it.hasNext()) {
703:                        RequestedResource r = (RequestedResource) it.next();
704:
705:                        if (rscRefs[i].getResRefName().equals(
706:                                r.getResourceName())) {
707:                            found = true;
708:                            it.remove();
709:
710:                            break;
711:                        } // end of if (refs[i].getResRefName().
712:                        //    equals(r.getResourceName()))
713:                    } // end of while (it.hasNext())
714:                } // end of for (int i = 0; i < refs.length; i++)
715:
716:                // Add the refs to the deployment descriptor
717:                Iterator it = reqList.iterator();
718:                while (it.hasNext()) {
719:                    RequestedResource r = (RequestedResource) it.next();
720:
721:                    if (r instanceof  RequestedJdbcResource) {
722:                        RequestedJdbcResource jr = (RequestedJdbcResource) r;
723:
724:                        try {
725:                            webApp
726:                                    .addBean(
727:                                            "ResourceRef", // NOI18N
728:                                            new String[] { "ResRefName", // NOI18N
729:                                                    "Description", // NOI18N
730:                                                    "ResType", // NOI18N
731:                                                    "ResAuth" }, // NOI18N
732:                                            new Object[] {
733:                                                    jr.getResourceName(),
734:                                                    "Visual Web generated DataSource Reference", // NOI18N
735:                                                    "javax.sql.DataSource", // NOI18N
736:                                                    "Container" }, // NOI18N
737:                                            "ResRefName"); // NOI18N
738:                        } catch (ClassNotFoundException e) {
739:                            // This should really not happen
740:                            ErrorManager.getDefault().notify(
741:                                    ErrorManager.INFORMATIONAL, e);
742:                        } // end of try-catch
743:                        catch (NameAlreadyUsedException ne) {
744:                            // Why did the code above not find it?
745:                            ErrorManager.getDefault().notify(
746:                                    ErrorManager.INFORMATIONAL, ne);
747:                        } // end of catch
748:
749:                        needWrite = true;
750:                    } // end of if (r instanceof RequestedJdbcResource)
751:                } // end of while (it.hasNext())
752:
753:                if (needWrite) {
754:                    try {
755:                        webApp.write(deployDescFO);
756:                    } catch (IOException e) {
757:                        // Do nothing for now.
758:                        e.printStackTrace();
759:                    }
760:                }
761:            }
762:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.