KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > java > j2seproject > applet > AppletSupport


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

19
20 package org.netbeans.modules.java.j2seproject.applet;
21
22 import com.sun.source.tree.CompilationUnitTree;
23 import com.sun.source.tree.Tree;
24 import com.sun.source.util.TreePath;
25 import com.sun.source.util.Trees;
26 import java.io.*;
27 import java.net.*;
28 import java.util.*;
29 import javax.lang.model.element.Modifier;
30 import javax.lang.model.element.TypeElement;
31 import javax.lang.model.element.TypeElement;
32 import javax.lang.model.util.Elements;
33 import javax.lang.model.util.Types;
34 import org.netbeans.api.java.source.CancellableTask;
35 import org.netbeans.api.java.source.CompilationController;
36 import org.netbeans.api.java.source.JavaSource;
37 import org.netbeans.modules.java.j2seproject.J2SEProjectUtil;
38
39 import org.openide.*;
40 import org.openide.modules.SpecificationVersion;
41 import org.openide.filesystems.*;
42 import org.openide.util.*;
43
44 import org.netbeans.api.java.classpath.*;
45 import org.netbeans.spi.java.classpath.support.*;
46 import org.netbeans.api.java.queries.*;
47 import org.netbeans.api.project.*;
48
49 import org.netbeans.api.java.platform.*;
50
51 import org.openide.loaders.*;
52 import org.openide.cookies.*;
53
54 /** Support for execution of applets.
55 *
56 * @author Ales Novak, Martin Grebac
57 */

58 public class AppletSupport {
59
60     // JDK issue #6193279: Appletviewer does not accept encoded URLs
61
private static final SpecificationVersion JDK_15 = new SpecificationVersion("1.5"); // NOI18N
62

63     /** constant for html extension */
64     private static final String JavaDoc HTML_EXT = "html"; // NOI18N
65
/** constant for class extension */
66     private static final String JavaDoc CLASS_EXT = "class"; // NOI18N
67

68     private final static String JavaDoc POLICY_FILE_NAME = "applet";
69     private final static String JavaDoc POLICY_FILE_EXT = "policy";
70         
71     private AppletSupport() {}
72
73     // Used only from unit tests to suppress detection of applet. If value
74
// is different from null it will be returned instead.
75
public static Boolean JavaDoc unitTestingSupport_isApplet = null;
76     
77     public static boolean isApplet(final FileObject file) {
78         if (file == null) {
79             return false;
80         }
81         // support for unit testing
82
if (unitTestingSupport_isApplet != null) {
83             return unitTestingSupport_isApplet.booleanValue();
84         }
85         JavaSource js = JavaSource.forFileObject(file);
86         if (js == null) {
87             return false;
88         }
89         final boolean[] result = new boolean[] {false};
90         try {
91             js.runUserActionTask(new CancellableTask<CompilationController>() {
92                 
93                 public void run(CompilationController control) throws Exception JavaDoc {
94                     if (JavaSource.Phase.ELEMENTS_RESOLVED.compareTo(control.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED))<=0) {
95                         Elements elements = control.getElements();
96                         Trees trees = control.getTrees();
97                         Types types = control.getTypes();
98                         TypeElement applet = elements.getTypeElement("java.applet.Applet"); //NOI18N
99
TypeElement japplet = elements.getTypeElement("javax.swing.JApplet"); //NOI18N
100
CompilationUnitTree cu = control.getCompilationUnit();
101                         List<? extends Tree> topLevels = cu.getTypeDecls();
102                         for (Tree topLevel : topLevels) {
103                             if (topLevel.getKind() == Tree.Kind.CLASS) {
104                                 TypeElement type = (TypeElement) trees.getElement(TreePath.getPath(cu, topLevel));
105                                 if (type != null) {
106                                     Set<Modifier> modifiers = type.getModifiers();
107                                     if (modifiers.contains(Modifier.PUBLIC) &&
108                                         ((applet != null && types.isSubtype(type.asType(), applet.asType()))
109                                         || (japplet != null && types.isSubtype(type.asType(), japplet.asType())))) {
110                                             result[0] = true;
111                                             break;
112                                     }
113                                 }
114                             }
115                         }
116                     }
117                 }
118                 
119                 public void cancel() {}
120             }, true);
121         } catch (IOException ioe) {
122             Exceptions.printStackTrace(ioe);
123         }
124         return result[0];
125     }
126     
127     /**
128     * @return html file with the same name as applet
129     */

130     private static FileObject generateHtml(FileObject appletFile, FileObject buildDir, FileObject classesDir) throws IOException {
131         FileObject htmlFile = buildDir.getFileObject(appletFile.getName(), HTML_EXT);
132         
133         if (htmlFile == null) {
134             htmlFile = buildDir.createData(appletFile.getName(), HTML_EXT);
135         }
136         
137         FileLock lock = htmlFile.lock();
138         PrintWriter writer = null;
139         try {
140             writer = new PrintWriter(htmlFile.getOutputStream(lock));
141             ClassPath cp = ClassPath.getClassPath(appletFile, ClassPath.EXECUTE);
142             ClassPath sp = ClassPath.getClassPath(appletFile, ClassPath.SOURCE);
143             String JavaDoc path = FileUtil.getRelativePath(sp.findOwnerRoot(appletFile), appletFile);
144             path = path.substring(0, path.length()-5);
145             String JavaDoc codebase = FileUtil.getRelativePath(buildDir, classesDir);
146             if (codebase == null) {
147                 codebase = classesDir.getURL().toString();
148             }
149             fillInFile(writer, path + "." + CLASS_EXT, "codebase=\"" + codebase + "\""); // NOI18N
150
} finally {
151             lock.releaseLock();
152             if (writer != null)
153                 writer.close();
154         }
155         return htmlFile;
156     }
157
158     /**
159     * @return html file with the same name as applet
160     */

161     public static FileObject generateSecurityPolicy(FileObject projectDir) {
162
163         FileObject policyFile = projectDir.getFileObject(POLICY_FILE_NAME, POLICY_FILE_EXT);
164         
165         try {
166             if (policyFile == null) {
167                 policyFile = projectDir.createData(POLICY_FILE_NAME, POLICY_FILE_EXT);
168             }
169             FileLock lock = policyFile.lock();
170             PrintWriter writer = null;
171             try {
172                 writer = new PrintWriter(policyFile.getOutputStream(lock));
173                 fillInPolicyFile(writer);
174             } finally {
175                 lock.releaseLock();
176                 if (writer != null)
177                     writer.close();
178             }
179         } catch (IOException ioe) {
180             ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "Problem when generating applet policy file: " + ioe); //NOI18N
181
}
182         return policyFile;
183     }
184     
185     /**
186     * @return URL of the html file with the same name as sibling
187     */

188     public static URL generateHtmlFileURL(FileObject appletFile, FileObject buildDir, FileObject classesDir, String JavaDoc activePlatform) throws FileStateInvalidException {
189         FileObject html = null;
190         IOException ex = null;
191         if ((appletFile == null) || (buildDir == null) || (classesDir == null)) {
192             return null;
193         }
194         try {
195             html = generateHtml(appletFile, buildDir, classesDir);
196             if (html!=null) {
197                 return getHTMLPageURL(html, activePlatform);
198             }
199             else {
200                 return null;
201             }
202         } catch (IOException iex) {
203             return null;
204         }
205     }
206     
207     
208     /**
209      * Creates an URL of html page passed to the appletviewer. It workarounds a JDK 1.5 appletviewer
210      * bug. The appletviewer is not able to handle escaped URLs.
211      * @param htmlFile html page
212      * @param activePlatform identifier of the platform used in the project
213      * @return URL of the html page or null
214      */

215     public static URL getHTMLPageURL (FileObject htmlFile, String JavaDoc activePlatform) {
216         assert htmlFile != null : "htmlFile cannot be null"; //NOI18N
217
// JDK issue #6193279: Appletviewer does not accept encoded URLs
218
JavaPlatform platform = J2SEProjectUtil.getActivePlatform(activePlatform);
219         boolean workAround6193279 = platform != null //In case of nonexisting platform don't use the workaround
220
&& platform.getSpecification().getVersion().compareTo(JDK_15)>=0; //JDK1.5 and higher
221
URL url = null;
222         if (workAround6193279) {
223             File f = FileUtil.toFile(htmlFile);
224             try {
225                 String JavaDoc path = f.getAbsolutePath();
226                 if (File.separatorChar != '/') { //NOI18N
227
path = path.replace(File.separatorChar,'/'); //NOI18N
228
}
229                 url = new URL ("file",null,path);
230             } catch (MalformedURLException e) {
231                 ErrorManager.getDefault().notify(e);
232             }
233         }
234         else {
235             try {
236                 url = htmlFile.getURL();
237             } catch (FileStateInvalidException f) {
238                 ErrorManager.getDefault().notify(f);
239             }
240         }
241         return url;
242     }
243
244     /** fills in file with html source so it is html file with applet
245     * @param file is a file to be filled
246     * @param name is name of the applet
247     */

248     private static void fillInFile(PrintWriter writer, String JavaDoc name, String JavaDoc codebase) {
249         ResourceBundle bundle = NbBundle.getBundle(AppletSupport.class);
250
251         writer.println("<HTML>"); // NOI18N
252
writer.println("<HEAD>"); // NOI18N
253

254         writer.print(" <TITLE>"); // NOI18N
255
writer.print(bundle.getString("GEN_title"));
256         writer.println("</TITLE>"); // NOI18N
257

258         writer.println("</HEAD>"); // NOI18N
259
writer.println("<BODY>\n"); // NOI18N
260

261         writer.print(bundle.getString("GEN_warning"));
262
263         writer.print("<H3><HR WIDTH=\"100%\">"); // NOI18N
264
writer.print(bundle.getString("GEN_header"));
265         writer.println("<HR WIDTH=\"100%\"></H3>\n"); // NOI18N
266

267         writer.println("<P>"); // NOI18N
268
// String codebase = getCodebase (name);
269
if (codebase == null)
270             writer.print("<APPLET code="); // NOI18N
271
else
272             writer.print("<APPLET " + codebase + " code="); // NOI18N
273
writer.print ("\""); // NOI18N
274

275         writer.print(name);
276         writer.print ("\""); // NOI18N
277

278         writer.println(" width=350 height=200></APPLET>"); // NOI18N
279
writer.println("</P>\n"); // NOI18N
280

281         writer.print("<HR WIDTH=\"100%\"><FONT SIZE=-1><I>"); // NOI18N
282
writer.print(bundle.getString("GEN_copy"));
283         writer.println("</I></FONT>"); // NOI18N
284

285         writer.println("</BODY>"); // NOI18N
286
writer.println("</HTML>"); // NOI18N
287
writer.flush();
288     }
289
290
291
292     /** fills in policy file with all permissions granted
293     * @param writer is a file to be filled
294     */

295     private static void fillInPolicyFile(PrintWriter writer) {
296         writer.println("grant {"); // NOI18N
297
writer.println("permission java.security.AllPermission;"); // NOI18N
298
writer.println("};"); // NOI18N
299
writer.flush();
300     }
301 }
302
Popular Tags