KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > ejbfreeform > EjbFreeFormActionProvider


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.j2ee.ejbfreeform;
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.spi.project.ActionProvider;
38 import org.netbeans.spi.project.AuxiliaryConfiguration;
39 import org.netbeans.spi.project.support.ant.AntProjectHelper;
40 import org.netbeans.spi.project.support.ant.EditableProperties;
41 import org.openide.DialogDisplayer;
42 import org.openide.ErrorManager;
43 import org.openide.NotifyDescriptor;
44 import org.openide.cookies.EditCookie;
45 import org.openide.cookies.LineCookie;
46 import org.openide.filesystems.FileLock;
47 import org.openide.filesystems.FileObject;
48 import org.openide.filesystems.FileUtil;
49 import org.openide.loaders.DataObject;
50 import org.openide.loaders.DataObjectNotFoundException;
51 import org.openide.text.Line;
52 import org.openide.util.NbBundle;
53 import org.openide.xml.XMLUtil;
54 import org.w3c.dom.Comment JavaDoc;
55 import org.w3c.dom.Document JavaDoc;
56 import org.w3c.dom.Element JavaDoc;
57 import org.xml.sax.Attributes JavaDoc;
58 import org.xml.sax.InputSource JavaDoc;
59 import org.xml.sax.Locator JavaDoc;
60 import org.xml.sax.SAXException JavaDoc;
61 import org.xml.sax.helpers.DefaultHandler JavaDoc;
62
63 /**
64  * Handles providing implementations of some Web-oriented IDE-specific actions.
65  *
66  * @author Libor Kotouc
67  * @author Andrei Badea
68  */

69 public class EjbFreeFormActionProvider 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         EjbFreeformProperties.JPDA_SESSION_NAME,
97         EjbFreeformProperties.JPDA_HOST,
98         EjbFreeformProperties.JPDA_ADDRESS,
99         EjbFreeformProperties.JPDA_TRANSPORT,
100         EjbFreeformProperties.DEBUG_SOURCEPATH,
101     };
102             
103     private static final String JavaDoc DEBUG_PROPERTIES_TEMPLATE = "/org/netbeans/modules/j2ee/ejbfreeform/resources/debug-properties.template"; // NOI18N
104

105     private final Project project;
106     private final AntProjectHelper helper;
107     private final AuxiliaryConfiguration aux;
108     
109     private static final String JavaDoc[] SUPPORTED_ACTIONS = {
110         ActionProvider.COMMAND_DEBUG,
111     };
112     
113     /**
114      * Creates a new instance of EjbFreeFormActionProvider
115      */

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

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

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

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

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

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

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

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

287     private void writeTargets(Document JavaDoc script, String JavaDoc propertiesFile) {
288         createLoadPropertiesTarget(script, propertiesFile);
289         createCheckPropertiesTarget(script);
290         createInitTarget(script);
291         createDebugTarget(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      * </target>
318      * @param script Script to write to.
319      */

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

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

352     private void createDebugTarget(Document JavaDoc script) {
353         Element JavaDoc target = script.createElement("target");
354         target.setAttribute("name", DEBUG_TARGET); // NOI18N
355
target.setAttribute("depends", INIT_TARGET); // NOI18N
356
target.setAttribute("if", "netbeans.home"); // NOI18N
357
Element JavaDoc nbjpdaconnect = script.createElement("nbjpdaconnect"); // NOI18N
358
nbjpdaconnect.setAttribute("name", "${" + EjbFreeformProperties.JPDA_SESSION_NAME + "}"); // NOI18N
359
nbjpdaconnect.setAttribute("host", "${" + EjbFreeformProperties.JPDA_HOST + "}"); // NOI18N
360
nbjpdaconnect.setAttribute("address", "${" + EjbFreeformProperties.JPDA_ADDRESS + "}"); // NOI18N
361
nbjpdaconnect.setAttribute("transport", "${" + EjbFreeformProperties.JPDA_TRANSPORT + "}"); // NOI18N
362
Element JavaDoc sourcepath = script.createElement("sourcepath"); // NOI18N
363
Element JavaDoc path = script.createElement("path"); // NOI18N
364
path.setAttribute("path", "${debug.sourcepath}"); // NOI18N
365
sourcepath.appendChild(path);
366         nbjpdaconnect.appendChild(sourcepath);
367         target.appendChild(nbjpdaconnect);
368         
369         script.getDocumentElement().appendChild(target);
370     }
371
372     /**
373      * Write a script with a new or modified document.
374      * @param script Document written to the script path.
375      * @param scriptPath e.g. {@link #FILE_SCRIPT_PATH} or {@link #GENERAL_SCRIPT_PATH}
376      */

377     void writeCustomScript(Document JavaDoc script, String JavaDoc scriptPath) throws IOException JavaDoc {
378         FileObject scriptFile = helper.getProjectDirectory().getFileObject(scriptPath);
379         if (scriptFile == null) {
380             scriptFile = FileUtil.createData(helper.getProjectDirectory(), scriptPath);
381         }
382         FileLock lock = scriptFile.lock();
383         try {
384             OutputStream JavaDoc os = scriptFile.getOutputStream(lock);
385             try {
386                 XMLUtil.write(script, os, "UTF-8"); // NOI18N
387
} finally {
388                 os.close();
389             }
390         } finally {
391             lock.releaseLock();
392         }
393     }
394
395     /**
396      * Add an action binding to project.xml.
397      * If there is no required context, the action is also added to the context menu of the project node.
398      * @param command the command name
399      * @param scriptPath the path to the generated script
400      * @param target the name of the target (in scriptPath)
401      * @param propertyName a property name to hold the selection (or null for no context, in which case remainder should be null)
402      * @param dir the raw text to use for the directory name
403      * @param pattern the regular expression to match, or null
404      * @param format the format to use
405      * @param separator the separator to use for multiple files, or null for single file only
406      */

407     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 {
408         // XXX cannot use FreeformProjectGenerator since that is currently not a public support SPI from ant/freeform
409
// 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
410
Element JavaDoc data = Util.getPrimaryConfigurationData(helper);
411         Element JavaDoc ideActions = Util.findElement(data, "ide-actions", Util.NAMESPACE); // NOI18N
412
if (ideActions == null) {
413             // Probably won't happen, since generator produces it always.
414
// Not trivial to just add it now, since order is significant in the schema. (FPG deals with these things.)
415
return;
416         }
417         Document JavaDoc doc = data.getOwnerDocument();
418         Element JavaDoc action = doc.createElementNS(Util.NAMESPACE, "action"); // NOI18N
419
action.setAttribute("name", command); // NOI18N
420
Element JavaDoc script = doc.createElementNS(Util.NAMESPACE, "script"); // NOI18N
421
script.appendChild(doc.createTextNode(scriptPath));
422         action.appendChild(script);
423         Element JavaDoc targetEl = doc.createElementNS(Util.NAMESPACE, "target"); // NOI18N
424
targetEl.appendChild(doc.createTextNode(target));
425         action.appendChild(targetEl);
426         ideActions.appendChild(action);
427         
428         if (propertyName != null) {
429             Element JavaDoc context = doc.createElementNS(Util.NAMESPACE, "context"); // NOI18N
430
Element JavaDoc property = doc.createElementNS(Util.NAMESPACE, "property"); // NOI18N
431
property.appendChild(doc.createTextNode(propertyName));
432             context.appendChild(property);
433             Element JavaDoc folder = doc.createElementNS(Util.NAMESPACE, "folder"); // NOI18N
434
folder.appendChild(doc.createTextNode(dir));
435             context.appendChild(folder);
436             if (pattern != null) {
437                 Element JavaDoc patternEl = doc.createElementNS(Util.NAMESPACE, "pattern"); // NOI18N
438
patternEl.appendChild(doc.createTextNode(pattern));
439                 context.appendChild(patternEl);
440             }
441             Element JavaDoc formatEl = doc.createElementNS(Util.NAMESPACE, "format"); // NOI18N
442
formatEl.appendChild(doc.createTextNode(format));
443             context.appendChild(formatEl);
444             Element JavaDoc arity = doc.createElementNS(Util.NAMESPACE, "arity"); // NOI18N
445
if (separator != null) {
446                 Element JavaDoc separatorEl = doc.createElementNS(Util.NAMESPACE, "separated-files"); // NOI18N
447
separatorEl.appendChild(doc.createTextNode(separator));
448                 arity.appendChild(separatorEl);
449             } else {
450                 arity.appendChild(doc.createElementNS(Util.NAMESPACE, "one-file-only")); // NOI18N
451
}
452             context.appendChild(arity);
453             action.appendChild(context);
454         } else {
455             // Add a context menu item, since it applies to the project as a whole.
456
// Assume there is already a <context-menu> defined, which is quite likely.
457
Element JavaDoc view = Util.findElement(data, "view", Util.NAMESPACE); // NOI18N
458
if (view != null) {
459                 Element JavaDoc contextMenu = Util.findElement(view, "context-menu", Util.NAMESPACE); // NOI18N
460
if (contextMenu != null) {
461                     Element JavaDoc ideAction = doc.createElementNS(Util.NAMESPACE, "ide-action"); // NOI18N
462
ideAction.setAttribute("name", command); // NOI18N
463
contextMenu.appendChild(ideAction);
464                 }
465             }
466         }
467
468         Util.putPrimaryConfigurationData(helper, data);
469         ProjectManager.getDefault().saveProject(project);
470     }
471     
472     private String JavaDoc writeDebugProperties() throws IOException JavaDoc {
473         String JavaDoc fileName = "debug"; // NOI18N
474
String JavaDoc file;
475         int i = 0;
476         do {
477             file = "nbproject/" + fileName + (i != 0 ? String.valueOf(i) : "") + ".properties"; // NOI18N
478
i++;
479         } while (helper.resolveFileObject(file) != null);
480         FileObject fo = FileUtil.createData(project.getProjectDirectory(), file);
481         FileLock lock = fo.lock();
482         OutputStream JavaDoc out = null;
483         InputStream JavaDoc in = null;
484         try {
485             out = new BufferedOutputStream JavaDoc(fo.getOutputStream(lock));
486             in = EjbFreeFormActionProvider.class.getResourceAsStream(DEBUG_PROPERTIES_TEMPLATE);
487             byte[] buffer = new byte[4096];
488             int read;
489             do {
490                 read = in.read(buffer);
491                 out.write(buffer, 0, read);
492             } while (read == buffer.length);
493         }
494         finally {
495             if (in != null)
496                 in.close();
497             if (out != null)
498                 out.close();
499             lock.releaseLock();
500         }
501         
502         // set the generated properties
503
EditableProperties ep = helper.getProperties(file);
504         ProjectInformation pi = ProjectUtils.getInformation(project);
505         ep.setProperty(EjbFreeformProperties.JPDA_SESSION_NAME, pi.getName());
506         ep.setProperty(EjbFreeformProperties.DEBUG_SOURCEPATH, findSourceFolders(JavaProjectConstants.SOURCES_TYPE_JAVA));
507         helper.putProperties(file, ep);
508         
509         return file;
510     }
511
512     /**
513      * Jump to an action binding in the editor.
514      * @param command an {@link ActionProvider} command name found in project.xml
515      */

516     private void jumpToBinding(String JavaDoc command) {
517         jumpToFile(AntProjectHelper.PROJECT_XML_PATH, command, "action", "name"); // NOI18N
518
}
519
520     /**
521      * Jump to a target in the editor.
522      * @param scriptPath the script to open
523      * @param target the name of the target (in scriptPath)
524      */

525     private void jumpToBuildScript(String JavaDoc scriptPath, String JavaDoc target) {
526         jumpToFile(scriptPath, target, "target", "name"); // NOI18N
527
}
528     
529     /**
530      * Jump to some line in an XML file.
531      * @param path project-relative path to the file
532      * @param match {@see #findLine}
533      * @param elementLocalName {@see #findLine}
534      * @param elementAttributeName {@see #findLine}
535      */

536     private void jumpToFile(String JavaDoc path, String JavaDoc match, String JavaDoc elementLocalName, String JavaDoc elementAttributeName) {
537         FileObject file = helper.getProjectDirectory().getFileObject(path);
538         if (file == null) {
539             return;
540         }
541         int line;
542         try {
543             line = findLine(file, match, elementLocalName, elementAttributeName);
544         } catch (Exception JavaDoc e) {
545             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
546             return;
547         }
548         if (line == -1) {
549             // Just open it.
550
line = 0;
551         }
552         DataObject fileDO;
553         try {
554             fileDO = DataObject.find(file);
555         } catch (DataObjectNotFoundException e) {
556             throw new AssertionError JavaDoc(e);
557         }
558         LineCookie lines = (LineCookie) fileDO.getCookie(LineCookie.class);
559         if (lines != null) {
560             try {
561                 lines.getLineSet().getCurrent(line).show(Line.SHOW_GOTO);
562             } catch (IndexOutOfBoundsException JavaDoc e) {
563                 // XXX reproducibly thrown if the document was already open. Why?? (file.refresh() above does not help.)
564
ErrorManager.getDefault().getInstance(EjbFreeFormActionProvider.class.getName()).log(
565                             ErrorManager.WARNING, e + " [file=" + file + " match=" + match + " line=" + line + "]"); // NOI18N
566
lines.getLineSet().getCurrent(0).show(Line.SHOW_GOTO);
567             }
568         }
569     }
570     
571     private void openFile(String JavaDoc path) {
572         FileObject file = helper.getProjectDirectory().getFileObject(path);
573         if (file == null)
574             return;
575         
576         DataObject fileDO;
577         try {
578             fileDO = DataObject.find(file);
579         }
580         catch (DataObjectNotFoundException e) {
581             throw new AssertionError JavaDoc(e);
582         }
583         
584         EditCookie edit = (EditCookie)fileDO.getCookie(EditCookie.class);
585         if (edit != null) {
586             edit.edit();
587         }
588     }
589
590     /**
591      * Find the line number of a target in an Ant script, or some other line in an XML file.
592      * Able to find a certain element with a certain attribute matching a given value.
593      * See also AntTargetNode.TargetOpenCookie.
594      * @param file an Ant script or other XML file
595      * @param match the attribute value to match (e.g. target name)
596      * @param elementLocalName the (local) name of the element to look for
597      * @param elementAttributeName the name of the attribute to match on
598      * @return the line number (0-based), or -1 if not found
599      */

600     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 {
601         InputSource JavaDoc in = new InputSource JavaDoc(file.getURL().toString());
602         SAXParserFactory JavaDoc factory = SAXParserFactory.newInstance();
603         factory.setNamespaceAware(true);
604         SAXParser JavaDoc parser = factory.newSAXParser();
605         final int[] line = new int[] {-1};
606         class Handler extends DefaultHandler JavaDoc {
607             private Locator JavaDoc locator;
608             public void setDocumentLocator(Locator JavaDoc l) {
609                 locator = l;
610             }
611             public void startElement(String JavaDoc uri, String JavaDoc localname, String JavaDoc qname, Attributes JavaDoc attr) throws SAXException JavaDoc {
612                 if (line[0] == -1) {
613                     if (localname.equals(elementLocalName) && match.equals(attr.getValue(elementAttributeName))) { // NOI18N
614
line[0] = locator.getLineNumber() - 1;
615                     }
616                 }
617             }
618         }
619         parser.parse(in, new Handler JavaDoc());
620         return line[0];
621     }
622     
623     private String JavaDoc findSourceFolders(String JavaDoc type) {
624         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
625         Element JavaDoc data = Util.getPrimaryConfigurationData(helper);
626         Element JavaDoc foldersEl = Util.findElement(data, "folders", Util.NAMESPACE); // NOI18N
627
if (foldersEl != null) {
628             for (Iterator JavaDoc i = Util.findSubElements(foldersEl).iterator(); i.hasNext();) {
629                 Element JavaDoc sourceFolderEl = (Element JavaDoc)i.next();
630                 Element JavaDoc typeEl = Util.findElement(sourceFolderEl , "type", Util.NAMESPACE); // NOI18N
631
if (typeEl == null || !Util.findText(typeEl).equals(type))
632                     continue;
633                 Element JavaDoc locationEl = Util.findElement(sourceFolderEl , "location", Util.NAMESPACE); // NOI18N
634
if (locationEl == null)
635                     continue;
636                 String JavaDoc location = Util.findText(locationEl);
637                 if (result.length() > 0)
638                     result.append(":"); // NOI18N
639
result.append(location);
640             }
641         }
642         return result.toString();
643     }
644 }
645
Popular Tags