Source Code Cross Referenced for JGraphpadBrowserLauncher.java in  » Graphic-Library » jgraphpad » com » jgraph » browserplugin » 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 » Graphic Library » jgraphpad » com.jgraph.browserplugin 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        package com.jgraph.browserplugin;
002:
003:        import java.io.File;
004:        import java.io.IOException;
005:        import java.lang.reflect.Constructor;
006:        import java.lang.reflect.Field;
007:        import java.lang.reflect.InvocationTargetException;
008:        import java.lang.reflect.Method;
009:        import java.net.URL;
010:
011:        /**
012:         * BrowserLauncher is a class that provides one static method, openURL, which
013:         * opens the default web browser for the current user of the system to the given
014:         * URL. It may support other protocols depending on the system -- mailto, ftp,
015:         * etc. -- but that has not been rigorously tested and is not guaranteed to
016:         * work.
017:         * <p>
018:         * Yes, this is platform-specific code, and yes, it may rely on classes on
019:         * certain platforms that are not part of the standard JDK. What we're trying to
020:         * do, though, is to take something that's frequently desirable but inherently
021:         * platform-specific -- opening a default browser -- and allow programmers (you,
022:         * for example) to do so without worrying about dropping into native code or
023:         * doing anything else similarly evil.
024:         * <p>
025:         * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant
026:         * systems without modification or a need for additional libraries. All classes
027:         * that are required on certain platforms to allow this to run are dynamically
028:         * loaded at runtime via reflection and, if not found, will not cause this to do
029:         * anything other than returning an error when opening the browser.
030:         * <p>
031:         * There are certain system requirements for this class, as it's running through
032:         * Runtime.exec(), which is Java's way of making a native system call.
033:         * Currently, this requires that a Macintosh have a Finder which supports the
034:         * GURL event, which is true for Mac OS 8.0 and 8.1 systems that have the
035:         * Internet Scripting AppleScript dictionary installed in the Scripting
036:         * Additions folder in the Extensions folder (which is installed by default as
037:         * far as I know under Mac OS 8.0 and 8.1), and for all Mac OS 8.5 and later
038:         * systems. On Windows, it only runs under Win32 systems (Windows 95, 98, and NT
039:         * 4.0, as well as later versions of all). On other systems, this drops back
040:         * from the inherently platform-sensitive concept of a default browser and
041:         * simply attempts to launch Netscape via a shell command.
042:         * <p>
043:         * This code is Copyright 1999-2001 by Eric Albert (ejalbert@cs.stanford.edu)
044:         * and may be redistributed or modified in any form without restrictions as long
045:         * as the portion of this comment from this paragraph through the end of the
046:         * comment is not removed. The author requests that he be notified of any
047:         * application, applet, or other binary that makes use of this code, but that's
048:         * more out of curiosity than anything and is not required. This software
049:         * includes no warranty. The author is not repsonsible for any loss of data or
050:         * functionality or any adverse or unexpected effects of using this software.
051:         * <p>
052:         * Credits: <br>
053:         * Steven Spencer, JavaWorld magazine (<a
054:         * href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java Tip
055:         * 66</a>) <br>
056:         * Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea
057:         * Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
058:         * 
059:         * Latest version can be found at: <a
060:         * href="http://sourceforge.net/projects/browserlauncher/">SourceForge</a>.
061:         * 
062:         * @author Eric Albert (<a
063:         *         href="mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
064:         * @version 1.4b1 (Released June 20, 2001)
065:         * 
066:         * 
067:         */
068:
069:        public class JGraphpadBrowserLauncher {
070:
071:            /**
072:             * The Java virtual machine that we are running on. Actually, in most cases
073:             * we only care about the operating system, but some operating systems
074:             * require us to switch on the VM.
075:             */
076:            private static int jvm;
077:
078:            /** The browser for the system */
079:            private static Object browser;
080:
081:            /**
082:             * Caches whether any classes, methods, and fields that are not part of the
083:             * JDK and need to be dynamically loaded at runtime loaded successfully.
084:             * <p>
085:             * Note that if this is <code>false</code>, <code>openURL()</code> will
086:             * always return an IOException.
087:             */
088:            private static boolean loadedWithoutErrors;
089:
090:            /** The com.apple.mrj.MRJFileUtils class */
091:            private static Class mrjFileUtilsClass;
092:
093:            /** The com.apple.mrj.MRJOSType class */
094:            private static Class mrjOSTypeClass;
095:
096:            /** The com.apple.MacOS.AEDesc class */
097:            private static Class aeDescClass;
098:
099:            /** The <init>(int) method of com.apple.MacOS.AETarget */
100:            private static Constructor aeTargetConstructor;
101:
102:            /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
103:            private static Constructor appleEventConstructor;
104:
105:            /** The <init>(String) method of com.apple.MacOS.AEDesc */
106:            private static Constructor aeDescConstructor;
107:
108:            /** The findFolder method of com.apple.mrj.MRJFileUtils */
109:            private static Method findFolder;
110:
111:            /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
112:            private static Method getFileCreator;
113:
114:            /** The getFileType method of com.apple.mrj.MRJFileUtils */
115:            private static Method getFileType;
116:
117:            /** The openURL method of com.apple.mrj.MRJFileUtils */
118:            private static Method openURL;
119:
120:            /** The makeOSType method of com.apple.MacOS.OSUtils */
121:            private static Method makeOSType;
122:
123:            /** The putParameter method of com.apple.MacOS.AppleEvent */
124:            private static Method putParameter;
125:
126:            /** The sendNoReply method of com.apple.MacOS.AppleEvent */
127:            private static Method sendNoReply;
128:
129:            /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
130:            private static Object kSystemFolderType;
131:
132:            /** The keyDirectObject AppleEvent parameter type */
133:            private static Integer keyDirectObject;
134:
135:            /** The kAutoGenerateReturnID AppleEvent code */
136:            private static Integer kAutoGenerateReturnID;
137:
138:            /** The kAnyTransactionID AppleEvent code */
139:            private static Integer kAnyTransactionID;
140:
141:            /** The linkage object required for JDirect 3 on Mac OS X. */
142:            private static Object linkage;
143:
144:            /** The framework to reference on Mac OS X */
145:            // private static final String JDirect_MacOSX =
146:            // "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
147:            /** JVM constant for MRJ 2.0 */
148:            private static final int MRJ_2_0 = 0;
149:
150:            /** JVM constant for MRJ 2.1 or later */
151:            private static final int MRJ_2_1 = 1;
152:
153:            /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
154:            private static final int MRJ_3_0 = 3;
155:
156:            /** JVM constant for MRJ 3.1 */
157:            private static final int MRJ_3_1 = 4;
158:
159:            /** JVM constant for any Windows NT JVM */
160:            private static final int WINDOWS_NT = 5;
161:
162:            /** JVM constant for any Windows 9x JVM */
163:            private static final int WINDOWS_9x = 6;
164:
165:            /** JVM constant for any other platform */
166:            private static final int OTHER = -1;
167:
168:            /**
169:             * The file type of the Finder on a Macintosh. Hardcoding "Finder" would
170:             * keep non-U.S. English systems from working properly.
171:             */
172:            private static final String FINDER_TYPE = "FNDR";
173:
174:            /**
175:             * The creator code of the Finder on a Macintosh, which is needed to send
176:             * AppleEvents to the application.
177:             */
178:            private static final String FINDER_CREATOR = "MACS";
179:
180:            /** The name for the AppleEvent type corresponding to a GetURL event. */
181:            private static final String GURL_EVENT = "GURL";
182:
183:            /**
184:             * The first parameter that needs to be passed into Runtime.exec() to open
185:             * the default web browser on Windows.
186:             */
187:            // private static final String FIRST_WINDOWS_PARAMETER = "/c";
188:            /** The second parameter for Runtime.exec() on Windows. */
189:            // private static final String SECOND_WINDOWS_PARAMETER = "start";
190:            /**
191:             * The third parameter for Runtime.exec() on Windows. This is a "title"
192:             * parameter that the command line expects. Setting this parameter allows
193:             * URLs containing spaces to work.
194:             */
195:            // private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
196:            /**
197:             * The shell parameters for Netscape that opens a given URL in an
198:             * already-open copy of Netscape on many command-line systems.
199:             */
200:            private static final String NETSCAPE_REMOTE_PARAMETER = "-remote";
201:
202:            private static final String NETSCAPE_OPEN_PARAMETER_START = "'openURL(";
203:
204:            private static final String NETSCAPE_OPEN_PARAMETER_END = ")'";
205:
206:            /**
207:             * The message from any exception thrown throughout the initialization
208:             * process.
209:             */
210:            private static String errorMessage;
211:
212:            /**
213:             * An initialization block that determines the operating system and loads
214:             * the necessary runtime data.
215:             */
216:            static {
217:                loadedWithoutErrors = true;
218:                String osName = System.getProperty("os.name");
219:                if (osName.startsWith("Mac OS")) {
220:                    String mrjVersion = System.getProperty("mrj.version");
221:                    String majorMRJVersion = mrjVersion.substring(0, 3);
222:                    try {
223:                        double version = Double.valueOf(majorMRJVersion)
224:                                .doubleValue();
225:                        if (version == 2) {
226:                            jvm = MRJ_2_0;
227:                        } else if (version >= 2.1 && version < 3) {
228:                            // Assume that all 2.x versions of MRJ work the same. MRJ
229:                            // 2.1 actually
230:                            // works via Runtime.exec() and 2.2 supports that but has an
231:                            // openURL() method
232:                            // as well that we currently ignore.
233:                            jvm = MRJ_2_1;
234:                        } else if (version == 3.0) {
235:                            jvm = MRJ_3_0;
236:                        } else if (version >= 3.1) {
237:                            // Assume that all 3.1 and later versions of MRJ work the
238:                            // same.
239:                            jvm = MRJ_3_1;
240:                        } else {
241:                            loadedWithoutErrors = false;
242:                            errorMessage = "Unsupported MRJ version: "
243:                                    + version;
244:                        }
245:                    } catch (NumberFormatException nfe) {
246:                        loadedWithoutErrors = false;
247:                        errorMessage = "Invalid MRJ version: " + mrjVersion;
248:                    }
249:                } else if (osName.startsWith("Windows")) {
250:                    if (osName.indexOf("9") != -1) {
251:                        jvm = WINDOWS_9x;
252:                    } else {
253:                        jvm = WINDOWS_NT;
254:                    }
255:                } else {
256:                    jvm = OTHER;
257:                }
258:
259:                if (loadedWithoutErrors) { // if we haven't hit any errors yet
260:                    loadedWithoutErrors = loadClasses();
261:                }
262:            }
263:
264:            /**
265:             * This class should be never be instantiated; this just ensures so.
266:             */
267:            private JGraphpadBrowserLauncher() {
268:            }
269:
270:            /**
271:             * Called by a static initializer to load any classes, fields, and methods
272:             * required at runtime to locate the user's web browser.
273:             * 
274:             * @return <code>true</code> if all intialization succeeded
275:             *         <code>false</code> if any portion of the initialization failed
276:             */
277:            private static boolean loadClasses() {
278:                switch (jvm) {
279:                case MRJ_2_0:
280:                    try {
281:                        Class aeTargetClass = Class
282:                                .forName("com.apple.MacOS.AETarget");
283:                        Class osUtilsClass = Class
284:                                .forName("com.apple.MacOS.OSUtils");
285:                        Class appleEventClass = Class
286:                                .forName("com.apple.MacOS.AppleEvent");
287:                        Class aeClass = Class.forName("com.apple.MacOS.ae");
288:                        aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
289:
290:                        aeTargetConstructor = aeTargetClass
291:                                .getDeclaredConstructor(new Class[] { int.class });
292:                        appleEventConstructor = appleEventClass
293:                                .getDeclaredConstructor(new Class[] {
294:                                        int.class, int.class, aeTargetClass,
295:                                        int.class, int.class });
296:                        aeDescConstructor = aeDescClass
297:                                .getDeclaredConstructor(new Class[] { String.class });
298:
299:                        makeOSType = osUtilsClass.getDeclaredMethod(
300:                                "makeOSType", new Class[] { String.class });
301:                        putParameter = appleEventClass.getDeclaredMethod(
302:                                "putParameter", new Class[] { int.class,
303:                                        aeDescClass });
304:                        sendNoReply = appleEventClass.getDeclaredMethod(
305:                                "sendNoReply", new Class[] {});
306:
307:                        Field keyDirectObjectField = aeClass
308:                                .getDeclaredField("keyDirectObject");
309:                        keyDirectObject = (Integer) keyDirectObjectField
310:                                .get(null);
311:                        Field autoGenerateReturnIDField = appleEventClass
312:                                .getDeclaredField("kAutoGenerateReturnID");
313:                        kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField
314:                                .get(null);
315:                        Field anyTransactionIDField = appleEventClass
316:                                .getDeclaredField("kAnyTransactionID");
317:                        kAnyTransactionID = (Integer) anyTransactionIDField
318:                                .get(null);
319:                    } catch (ClassNotFoundException cnfe) {
320:                        errorMessage = cnfe.getMessage();
321:                        return false;
322:                    } catch (NoSuchMethodException nsme) {
323:                        errorMessage = nsme.getMessage();
324:                        return false;
325:                    } catch (NoSuchFieldException nsfe) {
326:                        errorMessage = nsfe.getMessage();
327:                        return false;
328:                    } catch (IllegalAccessException iae) {
329:                        errorMessage = iae.getMessage();
330:                        return false;
331:                    }
332:                    break;
333:                case MRJ_2_1:
334:                    try {
335:                        mrjFileUtilsClass = Class
336:                                .forName("com.apple.mrj.MRJFileUtils");
337:                        mrjOSTypeClass = Class
338:                                .forName("com.apple.mrj.MRJOSType");
339:                        Field systemFolderField = mrjFileUtilsClass
340:                                .getDeclaredField("kSystemFolderType");
341:                        kSystemFolderType = systemFolderField.get(null);
342:                        findFolder = mrjFileUtilsClass.getDeclaredMethod(
343:                                "findFolder", new Class[] { mrjOSTypeClass });
344:                        getFileCreator = mrjFileUtilsClass.getDeclaredMethod(
345:                                "getFileCreator", new Class[] { File.class });
346:                        getFileType = mrjFileUtilsClass.getDeclaredMethod(
347:                                "getFileType", new Class[] { File.class });
348:                    } catch (ClassNotFoundException cnfe) {
349:                        errorMessage = cnfe.getMessage();
350:                        return false;
351:                    } catch (NoSuchFieldException nsfe) {
352:                        errorMessage = nsfe.getMessage();
353:                        return false;
354:                    } catch (NoSuchMethodException nsme) {
355:                        errorMessage = nsme.getMessage();
356:                        return false;
357:                    } catch (SecurityException se) {
358:                        errorMessage = se.getMessage();
359:                        return false;
360:                    } catch (IllegalAccessException iae) {
361:                        errorMessage = iae.getMessage();
362:                        return false;
363:                    }
364:                    break;
365:                case MRJ_3_0:
366:                    try {
367:                        Class linker = Class
368:                                .forName("com.apple.mrj.jdirect.Linker");
369:                        Constructor constructor = linker
370:                                .getConstructor(new Class[] { Class.class });
371:                        linkage = constructor
372:                                .newInstance(new Object[] { JGraphpadBrowserLauncher.class });
373:                    } catch (ClassNotFoundException cnfe) {
374:                        errorMessage = cnfe.getMessage();
375:                        return false;
376:                    } catch (NoSuchMethodException nsme) {
377:                        errorMessage = nsme.getMessage();
378:                        return false;
379:                    } catch (InvocationTargetException ite) {
380:                        errorMessage = ite.getMessage();
381:                        return false;
382:                    } catch (InstantiationException ie) {
383:                        errorMessage = ie.getMessage();
384:                        return false;
385:                    } catch (IllegalAccessException iae) {
386:                        errorMessage = iae.getMessage();
387:                        return false;
388:                    }
389:                    break;
390:                case MRJ_3_1:
391:                    try {
392:                        mrjFileUtilsClass = Class
393:                                .forName("com.apple.mrj.MRJFileUtils");
394:                        openURL = mrjFileUtilsClass.getDeclaredMethod(
395:                                "openURL", new Class[] { String.class });
396:                    } catch (ClassNotFoundException cnfe) {
397:                        errorMessage = cnfe.getMessage();
398:                        return false;
399:                    } catch (NoSuchMethodException nsme) {
400:                        errorMessage = nsme.getMessage();
401:                        return false;
402:                    }
403:                    break;
404:                default:
405:                    break;
406:                }
407:                return true;
408:            }
409:
410:            /**
411:             * Attempts to locate the default web browser on the local system. Caches
412:             * results so it only locates the browser once for each use of this class
413:             * per JVM instance.
414:             * 
415:             * @return The browser for the system. Note that this may not be what you
416:             *         would consider to be a standard web browser; instead, it's the
417:             *         application that gets called to open the default web browser. In
418:             *         some cases, this will be a non-String object that provides the
419:             *         means of calling the default browser.
420:             */
421:            private static Object locateBrowser() {
422:                if (browser != null) {
423:                    return browser;
424:                }
425:                switch (jvm) {
426:                case MRJ_2_0:
427:                    try {
428:                        Integer finderCreatorCode = (Integer) makeOSType
429:                                .invoke(null, new Object[] { FINDER_CREATOR });
430:                        Object aeTarget = aeTargetConstructor
431:                                .newInstance(new Object[] { finderCreatorCode });
432:                        Integer gurlType = (Integer) makeOSType.invoke(null,
433:                                new Object[] { GURL_EVENT });
434:                        Object appleEvent = appleEventConstructor
435:                                .newInstance(new Object[] { gurlType, gurlType,
436:                                        aeTarget, kAutoGenerateReturnID,
437:                                        kAnyTransactionID });
438:                        // Don't set browser = appleEvent because then the next time we
439:                        // call
440:                        // locateBrowser(), we'll get the same AppleEvent, to which
441:                        // we'll already have
442:                        // added the relevant parameter. Instead, regenerate the
443:                        // AppleEvent every time.
444:                        // There's probably a way to do this better; if any has any
445:                        // ideas, please let
446:                        // me know.
447:                        return appleEvent;
448:                    } catch (IllegalAccessException iae) {
449:                        browser = null;
450:                        errorMessage = iae.getMessage();
451:                        return browser;
452:                    } catch (InstantiationException ie) {
453:                        browser = null;
454:                        errorMessage = ie.getMessage();
455:                        return browser;
456:                    } catch (InvocationTargetException ite) {
457:                        browser = null;
458:                        errorMessage = ite.getMessage();
459:                        return browser;
460:                    }
461:                case MRJ_2_1:
462:                    File systemFolder;
463:                    try {
464:                        systemFolder = (File) findFolder.invoke(null,
465:                                new Object[] { kSystemFolderType });
466:                    } catch (IllegalArgumentException iare) {
467:                        browser = null;
468:                        errorMessage = iare.getMessage();
469:                        return browser;
470:                    } catch (IllegalAccessException iae) {
471:                        browser = null;
472:                        errorMessage = iae.getMessage();
473:                        return browser;
474:                    } catch (InvocationTargetException ite) {
475:                        browser = null;
476:                        errorMessage = ite.getTargetException().getClass()
477:                                + ": " + ite.getTargetException().getMessage();
478:                        return browser;
479:                    }
480:                    String[] systemFolderFiles = systemFolder.list();
481:                    // Avoid a FilenameFilter because that can't be stopped mid-list
482:                    for (int i = 0; i < systemFolderFiles.length; i++) {
483:                        try {
484:                            File file = new File(systemFolder,
485:                                    systemFolderFiles[i]);
486:                            if (!file.isFile()) {
487:                                continue;
488:                            }
489:                            // We're looking for a file with a creator code of 'MACS'
490:                            // and
491:                            // a type of 'FNDR'. Only requiring the type results in
492:                            // non-Finder
493:                            // applications being picked up on certain Mac OS 9 systems,
494:                            // especially German ones, and sending a GURL event to those
495:                            // applications results in a logout under Multiple Users.
496:                            Object fileType = getFileType.invoke(null,
497:                                    new Object[] { file });
498:                            if (FINDER_TYPE.equals(fileType.toString())) {
499:                                Object fileCreator = getFileCreator.invoke(
500:                                        null, new Object[] { file });
501:                                if (FINDER_CREATOR.equals(fileCreator
502:                                        .toString())) {
503:                                    browser = file.toString(); // Actually the Finder,
504:                                    // but that's OK
505:                                    return browser;
506:                                }
507:                            }
508:                        } catch (IllegalArgumentException iare) {
509:                            errorMessage = iare.getMessage();
510:                            return null;
511:                        } catch (IllegalAccessException iae) {
512:                            browser = null;
513:                            errorMessage = iae.getMessage();
514:                            return browser;
515:                        } catch (InvocationTargetException ite) {
516:                            browser = null;
517:                            errorMessage = ite.getTargetException().getClass()
518:                                    + ": "
519:                                    + ite.getTargetException().getMessage();
520:                            return browser;
521:                        }
522:                    }
523:                    browser = null;
524:                    break;
525:                case MRJ_3_0:
526:                case MRJ_3_1:
527:                    browser = ""; // Return something non-null
528:                    break;
529:                case WINDOWS_NT:
530:                    browser = "cmd.exe";
531:                    break;
532:                case WINDOWS_9x:
533:                    browser = "command.com";
534:                    break;
535:                case OTHER:
536:                default:
537:                    browser = "netscape";
538:                    try {
539:                        if (new File("/usr/bin/mozilla").exists())
540:                            browser = "/usr/bin/mozilla";
541:                    } catch (Exception e) {
542:                        // ignore
543:                    }
544:                    try {
545:                        if (new File("/usr/bin/firefox").exists())
546:                            browser = "/usr/bin/firefox";
547:                    } catch (Exception e) {
548:                        // ignore
549:                    }
550:                    break;
551:                }
552:                return browser;
553:            }
554:
555:            public static void openURL(URL url) throws IOException {
556:                openURL(url.toExternalForm());
557:            }
558:
559:            /**
560:             * Attempts to open the default web browser to the given URL.
561:             * 
562:             * @param url
563:             *            The URL to open
564:             * @throws IOException
565:             *             If the web browser could not be located or does not run
566:             */
567:            public static void openURL(String url) throws IOException {
568:                if (!loadedWithoutErrors) {
569:                    throw new IOException("Exception in finding browser: "
570:                            + errorMessage);
571:                }
572:                Object browser = locateBrowser();
573:                if (browser == null) {
574:                    throw new IOException("Unable to locate browser: "
575:                            + errorMessage);
576:                }
577:
578:                switch (jvm) {
579:                case MRJ_2_0:
580:                    Object aeDesc = null;
581:                    try {
582:                        aeDesc = aeDescConstructor
583:                                .newInstance(new Object[] { url });
584:                        putParameter.invoke(browser, new Object[] {
585:                                keyDirectObject, aeDesc });
586:                        sendNoReply.invoke(browser, new Object[] {});
587:                    } catch (InvocationTargetException ite) {
588:                        throw new IOException(
589:                                "InvocationTargetException while creating AEDesc: "
590:                                        + ite.getMessage());
591:                    } catch (IllegalAccessException iae) {
592:                        throw new IOException(
593:                                "IllegalAccessException while building AppleEvent: "
594:                                        + iae.getMessage());
595:                    } catch (InstantiationException ie) {
596:                        throw new IOException(
597:                                "InstantiationException while creating AEDesc: "
598:                                        + ie.getMessage());
599:                    } finally {
600:                        aeDesc = null; // Encourage it to get disposed if it was
601:                        // created
602:                        browser = null; // Ditto
603:                    }
604:                    break;
605:                case MRJ_2_1:
606:                    Runtime.getRuntime().exec(
607:                            new String[] { (String) browser, url });
608:                    break;
609:                case MRJ_3_0:
610:                    int[] instance = new int[1];
611:                    int result = ICStart(instance, 0);
612:                    if (result == 0) {
613:                        int[] selectionStart = new int[] { 0 };
614:                        byte[] urlBytes = url.getBytes();
615:                        int[] selectionEnd = new int[] { urlBytes.length };
616:                        result = ICLaunchURL(instance[0], new byte[] { 0 },
617:                                urlBytes, urlBytes.length, selectionStart,
618:                                selectionEnd);
619:                        if (result == 0) {
620:                            // Ignore the return value; the URL was launched
621:                            // successfully
622:                            // regardless of what happens here.
623:                            ICStop(instance);
624:                        } else {
625:
626:                            throw new IOException("Unable to launch URL: "
627:                                    + result);
628:                        }
629:                    } else {
630:                        throw new IOException(
631:                                "Unable to create an Internet Config instance: "
632:                                        + result);
633:                    }
634:                    break;
635:                case MRJ_3_1:
636:                    try {
637:                        openURL.invoke(null, new Object[] { url });
638:                    } catch (InvocationTargetException ite) {
639:                        throw new IOException(
640:                                "InvocationTargetException while calling openURL: "
641:                                        + ite.getMessage());
642:                    } catch (IllegalAccessException iae) {
643:                        throw new IOException(
644:                                "IllegalAccessException while calling openURL: "
645:                                        + iae.getMessage());
646:                    }
647:                    break;
648:                case WINDOWS_NT:
649:                case WINDOWS_9x:
650:                    // Add quotes around the URL to allow ampersands and other special
651:                    // characters to work.
652:                    // Process process = Runtime.getRuntime().exec(new String[] {
653:                    // (String) browser,
654:                    // FIRST_WINDOWS_PARAMETER,
655:                    // SECOND_WINDOWS_PARAMETER,
656:                    // THIRD_WINDOWS_PARAMETER,
657:                    // '"' + url + '"' });
658:
659:                    // VW opens browser without first displaying the distracting command
660:                    // window
661:                    // TODO: test quotes, for some reason I recall it does not work in
662:                    // this case
663:                    Process process = Runtime.getRuntime().exec(
664:                            "rundll32 url.dll,FileProtocolHandler " + url);
665:
666:                    // This avoids a memory leak on some versions of Java on Windows.
667:                    // That's hinted at in
668:                    // <http://developer.java.sun.com/developer/qow/archive/68/>.
669:                    try {
670:                        process.waitFor();
671:                        process.exitValue();
672:                    } catch (InterruptedException ie) {
673:                        throw new IOException(
674:                                "InterruptedException while launching browser: "
675:                                        + ie.getMessage());
676:                    }
677:                    break;
678:                case OTHER:
679:                    // Assume that we're on Unix and that Netscape is installed
680:
681:                    // First, attempt to open the URL in a currently running session of
682:                    // Netscape
683:                    process = Runtime.getRuntime().exec(
684:                            new String[] {
685:                                    (String) browser,
686:                                    NETSCAPE_REMOTE_PARAMETER,
687:                                    NETSCAPE_OPEN_PARAMETER_START + url
688:                                            + NETSCAPE_OPEN_PARAMETER_END });
689:                    try {
690:                        int exitCode = process.waitFor();
691:                        if (exitCode != 0) { // if Netscape was not open
692:                            Runtime.getRuntime().exec(
693:                                    new String[] { (String) browser, url });
694:                        }
695:                    } catch (InterruptedException ie) {
696:                        throw new IOException(
697:                                "InterruptedException while launching browser: "
698:                                        + ie.getMessage());
699:                    }
700:                    break;
701:                default:
702:                    // This should never occur, but if it does, we'll try the simplest
703:                    // thing possible
704:                    Runtime.getRuntime().exec(
705:                            new String[] { (String) browser, url });
706:                    break;
707:                }
708:            }
709:
710:            /**
711:             * Methods required for Mac OS X. The presence of native methods does not
712:             * cause any problems on other platforms.
713:             */
714:            private native static int ICStart(int[] instance, int signature);
715:
716:            private native static int ICStop(int[] instance);
717:
718:            private native static int ICLaunchURL(int instance, byte[] hint,
719:                    byte[] data, int len, int[] selectionStart,
720:                    int[] selectionEnd);
721:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.