KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > web > freeform > WebFreeFormActionProvider


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.web.freeform;
21
22 import java.io.BufferedOutputStream JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.io.OutputStream JavaDoc;
26 import java.util.Iterator JavaDoc;
27 import javax.swing.JButton JavaDoc;
28 import javax.xml.parsers.ParserConfigurationException JavaDoc;
29 import javax.xml.parsers.SAXParser JavaDoc;
30 import javax.xml.parsers.SAXParserFactory JavaDoc;
31 import org.netbeans.api.java.project.JavaProjectConstants;
32 import org.netbeans.api.project.Project;
33 import org.netbeans.api.project.ProjectInformation;
34 import org.netbeans.api.project.ProjectManager;
35 import org.netbeans.api.project.ProjectUtils;
36 import org.netbeans.modules.ant.freeform.spi.support.Util;
37 import org.netbeans.modules.web.api.webmodule.WebProjectConstants;
38 import org.netbeans.spi.project.ActionProvider;
39 import org.netbeans.spi.project.AuxiliaryConfiguration;
40 import org.netbeans.spi.project.support.ant.AntProjectHelper;
41 import org.netbeans.spi.project.support.ant.EditableProperties;
42 import org.openide.DialogDisplayer;
43 import org.openide.ErrorManager;
44 import org.openide.NotifyDescriptor;
45 import org.openide.cookies.EditCookie;
46 import org.openide.cookies.LineCookie;
47 import org.openide.filesystems.FileLock;
48 import org.openide.filesystems.FileObject;
49 import org.openide.filesystems.FileUtil;
50 import org.openide.loaders.DataObject;
51 import org.openide.loaders.DataObjectNotFoundException;
52 import org.openide.text.Line;
53 import org.openide.util.NbBundle;
54 import org.openide.xml.XMLUtil;
55 import org.w3c.dom.Comment JavaDoc;
56 import org.w3c.dom.Document JavaDoc;
57 import org.w3c.dom.Element JavaDoc;
58 import org.xml.sax.Attributes JavaDoc;
59 import org.xml.sax.InputSource JavaDoc;
60 import org.xml.sax.Locator JavaDoc;
61 import org.xml.sax.SAXException JavaDoc;
62 import org.xml.sax.helpers.DefaultHandler JavaDoc;
63
64 /**
65  * Handles providing implementations of some Web-oriented IDE-specific actions.
66  *
67  * @author Libor Kotouc
68  */

69 public class WebFreeFormActionProvider implements ActionProvider {
70     
71     /**
72      * Script to hold file-sensitive generated targets like compile.single.
73      * (Or for generated targets for debug which cannot reuse any existing target body.)
74      * These pick up at least project.dir from project.xml and the entire
75      * target body is fixed by the IDE, except for some strings determined
76      * by information from project.xml like the classpath. The basedir
77      * is set to the project directory so that properties match their
78      * semantics in project.xml.
79      */

80     static final String JavaDoc FILE_SCRIPT_PATH = "nbproject/ide-file-targets.xml"; // NOI18N
81

82     /**
83      * Script to hold non-file-sensitive generated targets like debug.
84      * These import the original build script and share its basedir, so that
85      * properties match the semantics of build.xml.
86      */

87     static final String JavaDoc GENERAL_SCRIPT_PATH = "nbproject/ide-targets.xml"; // NOI18N
88

89     private static final String JavaDoc LOAD_PROPS_TARGET = "-load-props"; // NOI18N
90
private static final String JavaDoc CHECK_PROPS_TARGET = "-check-props"; // NOI18N
91
private static final String JavaDoc INIT_TARGET = "-init"; // NOI18N
92
private static final String JavaDoc DEBUG_TARGET = "debug-nb"; // NOI18N
93
private static final String JavaDoc DISPLAY_BROWSER = "debug-display-browser"; // NOI18N
94

95     private static final String JavaDoc[] DEBUG_PROPERTIES = new String JavaDoc[] {
96         WebFreeformProperties.JPDA_SESSION_NAME,
97         WebFreeformProperties.JPDA_HOST,
98         WebFreeformProperties.JPDA_ADDRESS,
99         WebFreeformProperties.JPDA_TRANSPORT,
100         WebFreeformProperties.DEBUG_SOURCEPATH,
101         WebFreeformProperties.CLIENT_URL
102     };
103             
104     private static final String JavaDoc DEBUG_PROPERTIES_TEMPLATE = "/org/netbeans/modules/web/freeform/resources/debug-properties.template"; // NOI18N
105

106     private final Project project;
107     private final AntProjectHelper helper;
108     private final AuxiliaryConfiguration aux;
109
110     private static final String JavaDoc[] SUPPORTED_ACTIONS = {
111         ActionProvider.COMMAND_DEBUG,
112     };
113     
114     /** Creates a new instance of WebFreeFormActionProvider */
115     public WebFreeFormActionProvider(Project aProject, AntProjectHelper aHelper, AuxiliaryConfiguration aAux) {
116         project = aProject;
117         helper = aHelper;
118         aux = aAux;
119     }
120
121     public boolean isActionEnabled(String JavaDoc command, org.openide.util.Lookup context) throws IllegalArgumentException JavaDoc {
122         boolean enabled = false;
123         if (command.equals(ActionProvider.COMMAND_DEBUG))
124             enabled = true;
125         return enabled;
126     }
127
128     public void invokeAction(String JavaDoc command, org.openide.util.Lookup context) throws IllegalArgumentException JavaDoc {
129         try {
130             try {
131                 if (command.equals(ActionProvider.COMMAND_DEBUG))
132                     handleDebug();
133                 } catch (SAXException JavaDoc e) {
134                     throw (IOException JavaDoc) new IOException JavaDoc(e.toString()).initCause(e);
135                 }
136         } catch (IOException JavaDoc e) {
137             ErrorManager.getDefault().notify(e);
138         }
139     }
140
141     public String JavaDoc[] getSupportedActions() {
142         return SUPPORTED_ACTIONS;
143     }
144     
145     private void handleDebug() throws IOException JavaDoc, SAXException JavaDoc {
146         //allow user to confirm target generation
147
if (!alert(NbBundle.getMessage(WebFreeFormActionProvider.class, "ACTION_debug"), GENERAL_SCRIPT_PATH))
148             return;
149         
150         //let's generate a debug target
151
String JavaDoc propertiesFile = writeDebugProperties();
152         
153         //read script document
154
Document JavaDoc script = readCustomScript(GENERAL_SCRIPT_PATH);
155         if (script == null) //script doesn't exist
156
script = createCustomScript();
157
158         //append comments and target
159
writeComments(script);
160         writeTargets(script, propertiesFile);
161         
162         //save script
163
writeCustomScript(script, GENERAL_SCRIPT_PATH);
164         
165         //write changes to project.xml
166
addBinding(ActionProvider.COMMAND_DEBUG, GENERAL_SCRIPT_PATH, DEBUG_TARGET, null, null, null, null, null);
167         
168         //show the result
169
jumpToBinding(ActionProvider.COMMAND_DEBUG);
170         jumpToBuildScript(GENERAL_SCRIPT_PATH, DEBUG_TARGET);
171         openFile(propertiesFile);
172     }
173     
174     /**
175      * Display an alert asking the user whether to really generate a target.
176      * @param commandDisplayName the display name of the action to be bound
177      * @param scriptPath the path that to the script that will be generated or written to
178      * @return true if IDE should proceed
179      */

180     private boolean alert(String JavaDoc commandDisplayName, String JavaDoc scriptPath) {
181         String JavaDoc projectDisplayName = ProjectUtils.getInformation(project).getDisplayName();
182         String JavaDoc title = NbBundle.getMessage(WebFreeFormActionProvider.class, "TITLE_generate_target_dialog", commandDisplayName, projectDisplayName);
183         String JavaDoc body = NbBundle.getMessage(WebFreeFormActionProvider.class, "TEXT_generate_target_dialog", commandDisplayName, scriptPath);
184         NotifyDescriptor d = new NotifyDescriptor.Message(body, NotifyDescriptor.QUESTION_MESSAGE);
185         d.setTitle(title);
186         d.setOptionType(NotifyDescriptor.OK_CANCEL_OPTION);
187         JButton JavaDoc generate = new JButton JavaDoc(NbBundle.getMessage(WebFreeFormActionProvider.class, "LBL_generate"));
188         generate.setDefaultCapable(true);
189         d.setOptions(new Object JavaDoc[] {generate, NotifyDescriptor.CANCEL_OPTION});
190         return DialogDisplayer.getDefault().notify(d) == generate;
191     }
192
193     /**
194      * Reads a generated script if it exists, else create a skeleton.
195      * @param scriptPath e.g. {@link #FILE_SCRIPT_PATH} or {@link #GENERAL_SCRIPT_PATH}
196      * @return script document.
197      */

198     Document JavaDoc readCustomScript(String JavaDoc scriptPath) throws IOException JavaDoc, SAXException JavaDoc {
199
200         Document JavaDoc script = null;
201         FileObject scriptFile = helper.getProjectDirectory().getFileObject(scriptPath);
202         if (scriptFile != null) {
203             InputStream JavaDoc is = scriptFile.getInputStream();
204             try {
205                 script = XMLUtil.parse(new InputSource JavaDoc(is), false, true, null, null);
206             } finally {
207                 is.close();
208             }
209         }
210         
211         return script;
212     }
213     
214     /**
215      * Creates custom script.
216      * @return script document.
217      */

218     Document JavaDoc createCustomScript() {
219         //create document, set root and its attributes
220
Document JavaDoc script = XMLUtil.createDocument("project", null, null, null); // NOI18N
221
Element JavaDoc scriptRoot = script.getDocumentElement();
222         scriptRoot.setAttribute("basedir", /* ".." times count('/', FILE_SCRIPT_PATH) */".."); // NOI18N
223
String JavaDoc projname = ProjectUtils.getInformation(project).getDisplayName();
224         scriptRoot.setAttribute("name", NbBundle.getMessage(WebFreeFormActionProvider.class, "LBL_generated_script_name", projname));
225
226         //copy properties from project.xml to the script
227
copyProperties(Util.getPrimaryConfigurationData(helper), scriptRoot);
228         
229         return script;
230     }
231
232     /**
233      * Copies all properties defined in project.xml to Ant syntax.
234      * Used for generated targets which essentially copy Ant fragments from project.xml
235      * (rather than the user's build.xml).
236      * @param config XML of an Ant project (document element)
237      * @param script target custom script
238      */

239     private void copyProperties(Element JavaDoc config, Element JavaDoc script) {
240         // Look for <properties> in project.xml and make corresponding definitions in the Ant script.
241
// See corresponding schema.
242

243         Element JavaDoc data = Util.getPrimaryConfigurationData(helper);
244         Element JavaDoc properties = Util.findElement(data, "properties", Util.NAMESPACE); // NOI18N
245
if (properties != null) {
246             Iterator JavaDoc/*<Element>*/ propertiesIt = Util.findSubElements(properties).iterator();
247             while (propertiesIt.hasNext()) {
248                 Element JavaDoc el = (Element JavaDoc) propertiesIt.next();
249                 Element JavaDoc nue = script.getOwnerDocument().createElement("property"); // NOI18N
250
if (el.getLocalName().equals("property")) { // NOI18N
251
String JavaDoc name = el.getAttribute("name"); // NOI18N
252
assert name != null;
253                     String JavaDoc text = Util.findText(el);
254                     assert text != null;
255                     nue.setAttribute("name", name); // NOI18N
256
nue.setAttribute("value", text); // NOI18N
257
} else if (el.getLocalName().equals("property-file")) { // NOI18N
258
String JavaDoc text = Util.findText(el);
259                     assert text != null;
260                     nue.setAttribute("file", text); // NOI18N
261
} else {
262                     assert false : el;
263                 }
264                 script.appendChild(nue);
265             }
266         }
267     }
268
269     /**
270      * Appends the comments to script.
271      * @param script Script to write to.
272      */

273     private void writeComments(Document JavaDoc script) {
274         Comment JavaDoc comm4Edit = script.createComment(" " + NbBundle.getMessage(WebFreeFormActionProvider.class, "COMMENT_edit_target") + " "); // NOI18N
275
Comment JavaDoc comm4Info = script.createComment(" " + NbBundle.getMessage(WebFreeFormActionProvider.class, "COMMENT_more_info_debug") + " "); // NOI18N
276

277         Element JavaDoc scriptRoot = script.getDocumentElement();
278         scriptRoot.appendChild(comm4Edit);
279         scriptRoot.appendChild(comm4Info);
280     }
281     
282     /**
283      * Appends necessary targets to script.
284      * @param script Script to write to.
285      */

286     private void writeTargets(Document JavaDoc script, String JavaDoc propertiesFile) {
287         createLoadPropertiesTarget(script, propertiesFile);
288         createCheckPropertiesTarget(script);
289         createInitTarget(script);
290         createDebugTarget(script);
291         createDisplayBrowserTarget(script);
292     }
293
294     /**
295      * Creates target:
296      * <target name="-load-props">
297      * <property file="nbproject/project.properties"/>
298      * </target>
299      * @param script Script to write to.
300      */

301     private void createLoadPropertiesTarget(Document JavaDoc script, String JavaDoc propertiesFile) {
302         Element JavaDoc target = script.createElement("target"); // NOI18N
303
target.setAttribute("name", LOAD_PROPS_TARGET); // NOI18N
304
Element JavaDoc property = script.createElement("property"); // NOI18N
305
property.setAttribute("file", propertiesFile);// NOI18N
306
target.appendChild(property);
307         script.getDocumentElement().appendChild(target);
308     }
309     
310     /**
311      * Creates target:
312      * <target name="-check-props">
313      * <fail unless="jpda.session.name"/>
314      * <fail unless="jpda.host"/>
315      * <fail unless="jpda.address"/>
316      * <fail unless="jpda.transport"/>
317      * <fail unless="debug.sourcepath"/>
318      * <fail unless="client.url"/>
319      * </target>
320      * @param script Script to write to.
321      */

322     private void createCheckPropertiesTarget(Document JavaDoc script) {
323         Element JavaDoc target = script.createElement("target"); // NOI18N
324
target.setAttribute("name", CHECK_PROPS_TARGET); // NOI18N
325
Element JavaDoc fail;
326         for (int i = 0; i < DEBUG_PROPERTIES.length; i++) {
327             fail = script.createElement("fail"); // NOI18N
328
fail.setAttribute("unless", DEBUG_PROPERTIES[i]); // NOI18N
329
target.appendChild(fail);
330         }
331         
332         script.getDocumentElement().appendChild(target);
333     }
334     
335     /**
336      * Creates target:
337      * <target name="-init" depends="-load-props, -check-props"/>
338      * @param script Script to write to.
339      */

340     private void createInitTarget(Document JavaDoc script) {
341         Element JavaDoc target = script.createElement("target"); // NOI18N
342
target.setAttribute("name", INIT_TARGET); // NOI18N
343
target.setAttribute("depends", LOAD_PROPS_TARGET + ", " + CHECK_PROPS_TARGET); // NOI18N
344
script.getDocumentElement().appendChild(target);
345     }
346     
347     /**
348      * Creates target:
349      * <target name="debug-nb" depends="-init" if="netbeans.home">
350      * <nbjpdaconnect name="${session.name}" host="${jpda.host}" address="${jpda.address}" transport="${jpda.transport}">
351      * <sourcepath>
352      * <path path="${debug.sourcepath}"/>
353      * </sourcepath>
354      * </nbjpdaconnect>
355      * <antcall target="debug-display-browser"/>
356      * </target>
357      * @param script Script to write to.
358      */

359     private void createDebugTarget(Document JavaDoc script) {
360         Element JavaDoc target = script.createElement("target");
361         target.setAttribute("name", DEBUG_TARGET); // NOI18N
362
target.setAttribute("depends", INIT_TARGET); // NOI18N
363
target.setAttribute("if", "netbeans.home"); // NOI18N
364
Element JavaDoc nbjpdaconnect = script.createElement("nbjpdaconnect"); // NOI18N
365
nbjpdaconnect.setAttribute("name", "${" + WebFreeformProperties.JPDA_SESSION_NAME + "}"); // NOI18N
366
nbjpdaconnect.setAttribute("host", "${" + WebFreeformProperties.JPDA_HOST + "}"); // NOI18N
367
nbjpdaconnect.setAttribute("address", "${" + WebFreeformProperties.JPDA_ADDRESS + "}"); // NOI18N
368
nbjpdaconnect.setAttribute("transport", "${" + WebFreeformProperties.JPDA_TRANSPORT + "}"); // NOI18N
369
Element JavaDoc sourcepath = script.createElement("sourcepath"); // NOI18N
370
Element JavaDoc path = script.createElement("path"); // NOI18N
371
path.setAttribute("path", "${debug.sourcepath}"); // NOI18N
372
sourcepath.appendChild(path);
373         nbjpdaconnect.appendChild(sourcepath);
374         target.appendChild(nbjpdaconnect);
375         Element JavaDoc antcall = script.createElement("antcall"); // NOI18N
376
antcall.setAttribute("target", DISPLAY_BROWSER); // NOI18N
377
target.appendChild(antcall);
378         
379         script.getDocumentElement().appendChild(target);
380     }
381
382     /**
383      * Creates target:
384      * <target name="debug-display-browser">
385      * <nbbrowse url="${client.url}"/>
386      * </target>
387      * @param script Script to write to.
388      */

389     private void createDisplayBrowserTarget(Document JavaDoc script) {
390         Element JavaDoc target = script.createElement("target"); // NOI18N
391
target.setAttribute("name", DISPLAY_BROWSER); // NOI18N
392
Element JavaDoc nbbrowse = script.createElement("nbbrowse"); // NOI18N
393
nbbrowse.setAttribute("url", "${client.url}"); // NOI18N
394
target.appendChild(nbbrowse);
395         
396         script.getDocumentElement().appendChild(target);
397     }
398
399     /**
400      * Write a script with a new or modified document.
401      * @param script Document written to the script path.
402      * @param scriptPath e.g. {@link #FILE_SCRIPT_PATH} or {@link #GENERAL_SCRIPT_PATH}
403      */

404     void writeCustomScript(Document JavaDoc script, String JavaDoc scriptPath) throws IOException JavaDoc {
405         FileObject scriptFile = helper.getProjectDirectory().getFileObject(scriptPath);
406         if (scriptFile == null) {
407             scriptFile = FileUtil.createData(helper.getProjectDirectory(), scriptPath);
408         }
409         FileLock lock = scriptFile.lock();
410         try {
411             OutputStream JavaDoc os = scriptFile.getOutputStream(lock);
412             try {
413                 XMLUtil.write(script, os, "UTF-8"); // NOI18N
414
} finally {
415                 os.close();
416             }
417         } finally {
418             lock.releaseLock();
419         }
420     }
421
422     /**
423      * Add an action binding to project.xml.
424      * If there is no required context, the action is also added to the context menu of the project node.
425      * @param command the command name
426      * @param scriptPath the path to the generated script
427      * @param target the name of the target (in scriptPath)
428      * @param propertyName a property name to hold the selection (or null for no context, in which case remainder should be null)
429      * @param dir the raw text to use for the directory name
430      * @param pattern the regular expression to match, or null
431      * @param format the format to use
432      * @param separator the separator to use for multiple files, or null for single file only
433      */

434     void addBinding(String JavaDoc command, String JavaDoc scriptPath, String JavaDoc target, String JavaDoc propertyName, String JavaDoc dir, String JavaDoc pattern, String JavaDoc format, String JavaDoc separator) throws IOException JavaDoc {
435         // XXX cannot use FreeformProjectGenerator since that is currently not a public support SPI from ant/freeform
436
// XXX should this try to find an existing binding? probably not, since it is assumed that if there was one, we would never get here to begin with
437
Element JavaDoc data = Util.getPrimaryConfigurationData(helper);
438         Element JavaDoc ideActions = Util.findElement(data, "ide-actions", Util.NAMESPACE); // NOI18N
439
if (ideActions == null) {
440             // Probably won't happen, since generator produces it always.
441
// Not trivial to just add it now, since order is significant in the schema. (FPG deals with these things.)
442
return;
443         }
444         Document JavaDoc doc = data.getOwnerDocument();
445         Element JavaDoc action = doc.createElementNS(Util.NAMESPACE, "action"); // NOI18N
446
action.setAttribute("name", command); // NOI18N
447
Element JavaDoc script = doc.createElementNS(Util.NAMESPACE, "script"); // NOI18N
448
script.appendChild(doc.createTextNode(scriptPath));
449         action.appendChild(script);
450         Element JavaDoc targetEl = doc.createElementNS(Util.NAMESPACE, "target"); // NOI18N
451
targetEl.appendChild(doc.createTextNode(target));
452         action.appendChild(targetEl);
453         ideActions.appendChild(action);
454         
455         if (propertyName != null) {
456             Element JavaDoc context = doc.createElementNS(Util.NAMESPACE, "context"); // NOI18N
457
Element JavaDoc property = doc.createElementNS(Util.NAMESPACE, "property"); // NOI18N
458
property.appendChild(doc.createTextNode(propertyName));
459             context.appendChild(property);
460             Element JavaDoc folder = doc.createElementNS(Util.NAMESPACE, "folder"); // NOI18N
461
folder.appendChild(doc.createTextNode(dir));
462             context.appendChild(folder);
463             if (pattern != null) {
464                 Element JavaDoc patternEl = doc.createElementNS(Util.NAMESPACE, "pattern"); // NOI18N
465
patternEl.appendChild(doc.createTextNode(pattern));
466                 context.appendChild(patternEl);
467             }
468             Element JavaDoc formatEl = doc.createElementNS(Util.NAMESPACE, "format"); // NOI18N
469
formatEl.appendChild(doc.createTextNode(format));
470             context.appendChild(formatEl);
471             Element JavaDoc arity = doc.createElementNS(Util.NAMESPACE, "arity"); // NOI18N
472
if (separator != null) {
473                 Element JavaDoc separatorEl = doc.createElementNS(Util.NAMESPACE, "separated-files"); // NOI18N
474
separatorEl.appendChild(doc.createTextNode(separator));
475                 arity.appendChild(separatorEl);
476             } else {
477                 arity.appendChild(doc.createElementNS(Util.NAMESPACE, "one-file-only")); // NOI18N
478
}
479             context.appendChild(arity);
480             action.appendChild(context);
481         } else {
482             // Add a context menu item, since it applies to the project as a whole.
483
// Assume there is already a <context-menu> defined, which is quite likely.
484
Element JavaDoc view = Util.findElement(data, "view", Util.NAMESPACE); // NOI18N
485
if (view != null) {
486                 Element JavaDoc contextMenu = Util.findElement(view, "context-menu", Util.NAMESPACE); // NOI18N
487
if (contextMenu != null) {
488                     Element JavaDoc ideAction = doc.createElementNS(Util.NAMESPACE, "ide-action"); // NOI18N
489
ideAction.setAttribute("name", command); // NOI18N
490
contextMenu.appendChild(ideAction);
491                 }
492             }
493         }
494
495         Util.putPrimaryConfigurationData(helper, data);
496         ProjectManager.getDefault().saveProject(project);
497     }
498     
499     private String JavaDoc writeDebugProperties() throws IOException JavaDoc {
500         String JavaDoc fileName = "debug"; // NOI18N
501
String JavaDoc file;
502         int i = 0;
503         do {
504             file = "nbproject/" + fileName + (i != 0 ? String.valueOf(i) : "") + ".properties"; // NOI18N
505
i++;
506         } while (helper.resolveFileObject(file) != null);
507         FileObject fo = FileUtil.createData(project.getProjectDirectory(), file);
508         FileLock lock = fo.lock();
509         OutputStream JavaDoc out = null;
510         InputStream JavaDoc in = null;
511         try {
512             out = new BufferedOutputStream JavaDoc(fo.getOutputStream(lock));
513             in = getClass().getResourceAsStream(DEBUG_PROPERTIES_TEMPLATE);
514             byte[] buffer = new byte[4096];
515             int read;
516             do {
517                 read = in.read(buffer);
518                 out.write(buffer, 0, read);
519             } while (read == buffer.length);
520         }
521         finally {
522             if (in != null)
523                 in.close();
524             if (out != null)
525                 out.close();
526             lock.releaseLock();
527         }
528         
529         // set the generated properties
530
EditableProperties ep = helper.getProperties(file);
531         ProjectInformation pi = ProjectUtils.getInformation(project);
532         ep.setProperty(WebFreeformProperties.JPDA_SESSION_NAME, pi.getName());
533         ep.setProperty(WebFreeformProperties.SRC_FOLDERS, findSourceFolders(JavaProjectConstants.SOURCES_TYPE_JAVA));
534         ep.setProperty(WebFreeformProperties.WEB_DOCBASE_DIR, findSourceFolders(WebProjectConstants.TYPE_DOC_ROOT));
535         String JavaDoc contextPath = findContextPath();
536         ep.setProperty(WebFreeformProperties.CLIENT_URL, ep.getProperty(WebFreeformProperties.CLIENT_URL) + (contextPath != null ? contextPath : "/")); // NOI18N
537
helper.putProperties(file, ep);
538         
539         return file;
540     }
541
542     /**
543      * Jump to an action binding in the editor.
544      * @param command an {@link ActionProvider} command name found in project.xml
545      */

546     private void jumpToBinding(String JavaDoc command) {
547         jumpToFile(AntProjectHelper.PROJECT_XML_PATH, command, "action", "name"); // NOI18N
548
}
549
550     /**
551      * Jump to a target in the editor.
552      * @param scriptPath the script to open
553      * @param target the name of the target (in scriptPath)
554      */

555     private void jumpToBuildScript(String JavaDoc scriptPath, String JavaDoc target) {
556         jumpToFile(scriptPath, target, "target", "name"); // NOI18N
557
}
558     
559     /**
560      * Jump to some line in an XML file.
561      * @param path project-relative path to the file
562      * @param match {@see #findLine}
563      * @param elementLocalName {@see #findLine}
564      * @param elementAttributeName {@see #findLine}
565      */

566     private void jumpToFile(String JavaDoc path, String JavaDoc match, String JavaDoc elementLocalName, String JavaDoc elementAttributeName) {
567         FileObject file = helper.getProjectDirectory().getFileObject(path);
568         if (file == null) {
569             return;
570         }
571         int line;
572         try {
573             line = findLine(file, match, elementLocalName, elementAttributeName);
574         } catch (IOException JavaDoc e) {
575             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
576             return;
577         } catch (SAXException JavaDoc e) {
578             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
579             return;
580         } catch (ParserConfigurationException JavaDoc e) {
581             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
582             return;
583         }
584         if (line == -1) {
585             // Just open it.
586
line = 0;
587         }
588         DataObject fileDO;
589         try {
590             fileDO = DataObject.find(file);
591         } catch (DataObjectNotFoundException e) {
592             throw new AssertionError JavaDoc(e);
593         }
594         LineCookie lines = (LineCookie) fileDO.getCookie(LineCookie.class);
595         if (lines != null) {
596             try {
597                 lines.getLineSet().getCurrent(line).show(Line.SHOW_GOTO);
598             } catch (IndexOutOfBoundsException JavaDoc e) {
599                 // XXX reproducibly thrown if the document was already open. Why?? (file.refresh() above does not help.)
600
ErrorManager.getDefault().getInstance(WebFreeFormActionProvider.class.getName()).log(
601                             ErrorManager.WARNING, e + " [file=" + file + " match=" + match + " line=" + line + "]"); // NOI18N
602
lines.getLineSet().getCurrent(0).show(Line.SHOW_GOTO);
603             }
604         }
605     }
606     
607     private void openFile(String JavaDoc path) {
608         FileObject file = helper.getProjectDirectory().getFileObject(path);
609         if (file == null)
610             return;
611         
612         DataObject fileDO;
613         try {
614             fileDO = DataObject.find(file);
615         }
616         catch (DataObjectNotFoundException e) {
617             throw new AssertionError JavaDoc(e);
618         }
619         
620         EditCookie edit = (EditCookie)fileDO.getCookie(EditCookie.class);
621         if (edit != null) {
622             edit.edit();
623         }
624     }
625
626     /**
627      * Find the line number of a target in an Ant script, or some other line in an XML file.
628      * Able to find a certain element with a certain attribute matching a given value.
629      * See also AntTargetNode.TargetOpenCookie.
630      * @param file an Ant script or other XML file
631      * @param match the attribute value to match (e.g. target name)
632      * @param elementLocalName the (local) name of the element to look for
633      * @param elementAttributeName the name of the attribute to match on
634      * @return the line number (0-based), or -1 if not found
635      */

636     static final int findLine(FileObject file, final String JavaDoc match, final String JavaDoc elementLocalName, final String JavaDoc elementAttributeName) throws IOException JavaDoc, SAXException JavaDoc, ParserConfigurationException JavaDoc {
637         InputSource JavaDoc in = new InputSource JavaDoc(file.getURL().toString());
638         SAXParserFactory JavaDoc factory = SAXParserFactory.newInstance();
639         factory.setNamespaceAware(true);
640         SAXParser JavaDoc parser = factory.newSAXParser();
641         final int[] line = new int[] {-1};
642         class Handler extends DefaultHandler JavaDoc {
643             private Locator JavaDoc locator;
644             public void setDocumentLocator(Locator JavaDoc l) {
645                 locator = l;
646             }
647             public void startElement(String JavaDoc uri, String JavaDoc localname, String JavaDoc qname, Attributes JavaDoc attr) throws SAXException JavaDoc {
648                 if (line[0] == -1) {
649                     if (localname.equals(elementLocalName) && match.equals(attr.getValue(elementAttributeName))) { // NOI18N
650
line[0] = locator.getLineNumber() - 1;
651                     }
652                 }
653             }
654         }
655         parser.parse(in, new Handler JavaDoc());
656         return line[0];
657     }
658     
659     private String JavaDoc findSourceFolders(String JavaDoc type) {
660         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
661         Element JavaDoc data = Util.getPrimaryConfigurationData(helper);
662         Element JavaDoc foldersEl = Util.findElement(data, "folders", Util.NAMESPACE); // NOI18N
663
if (foldersEl != null) {
664             for (Iterator JavaDoc i = Util.findSubElements(foldersEl).iterator(); i.hasNext();) {
665                 Element JavaDoc sourceFolderEl = (Element JavaDoc)i.next();
666                 Element JavaDoc typeEl = Util.findElement(sourceFolderEl , "type", Util.NAMESPACE); // NOI18N
667
if (typeEl == null || !Util.findText(typeEl).equals(type))
668                     continue;
669                 Element JavaDoc locationEl = Util.findElement(sourceFolderEl , "location", Util.NAMESPACE); // NOI18N
670
if (locationEl == null)
671                     continue;
672                 String JavaDoc location = Util.findText(locationEl);
673                 if (result.length() > 0)
674                     result.append(":"); // NOI18N
675
result.append(location);
676             }
677         }
678         return result.toString();
679     }
680     
681     private String JavaDoc findContextPath() {
682         Element JavaDoc data = aux.getConfigurationFragment("web-data", WebProjectNature.NS_WEB, true); // NOI18N
683
Element JavaDoc webModulEl = Util.findElement(data, "web-module", WebProjectNature.NS_WEB); // NOI18N
684
if (webModulEl == null)
685             return null;
686         Element JavaDoc contextPathEl = Util.findElement(webModulEl, "context-path", WebProjectNature.NS_WEB); // NOI18N
687
if (contextPathEl == null)
688             return null;
689         return Util.findText(contextPathEl);
690     }
691     
692 }
693
Popular Tags