001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common
008: * Development and Distribution License("CDDL") (collectively, the
009: * "License"). You may not use this file except in compliance with the
010: * License. You can obtain a copy of the License at
011: * http://www.netbeans.org/cddl-gplv2.html
012: * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
013: * specific language governing permissions and limitations under the
014: * License. When distributing the software, include this License Header
015: * Notice in each file and include the License file at
016: * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
017: * particular file as subject to the "Classpath" exception as provided
018: * by Sun in the GPL Version 2 section of the License file that
019: * accompanied this code. If applicable, add the following below the
020: * License Header, with the fields enclosed by brackets [] replaced by
021: * your own identifying information:
022: * "Portions Copyrighted [year] [name of copyright owner]"
023: *
024: * Contributor(s):
025: *
026: * The Original Software is NetBeans. The Initial Developer of the Original
027: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
028: * Microsystems, Inc. All Rights Reserved.
029: *
030: * If you wish your version of this file to be governed by only the CDDL
031: * or only the GPL Version 2, indicate your decision by adding
032: * "[Contributor] elects to include this software in this distribution
033: * under the [CDDL or GPL Version 2] license." If you do not indicate a
034: * single choice of license, a recipient has the option to distribute
035: * your version of this file under either the CDDL, the GPL Version 2 or
036: * to extend the choice of license to its licensees as provided above.
037: * However, if you add GPL Version 2 code and therefore, elected the GPL
038: * Version 2 license, then the option applies only if the new code is
039: * made subject to such option by the copyright holder.
040: */
041: package org.netbeans.modules.j2ee.ddloaders.multiview;
042:
043: import java.awt.Color;
044: import java.awt.Component;
045: import java.awt.Container;
046: import java.io.IOException;
047: import org.netbeans.modules.j2ee.dd.api.ejb.Ejb;
048: import org.netbeans.modules.j2ee.ddloaders.multiview.ui.BrowseFolders;
049: import org.openide.DialogDisplayer;
050: import org.openide.NotifyDescriptor;
051: import org.openide.filesystems.FileObject;
052: import org.openide.filesystems.FileUtil;
053: import org.openide.util.NbBundle;
054: import org.openide.util.Utilities;
055:
056: import javax.swing.*;
057: import java.util.ArrayList;
058: import java.util.List;
059: import javax.lang.model.element.TypeElement;
060: import org.netbeans.api.java.classpath.ClassPath;
061: import org.netbeans.api.java.source.CompilationController;
062: import org.netbeans.api.java.source.ElementHandle;
063: import org.netbeans.api.java.source.JavaSource;
064: import org.netbeans.api.java.source.Task;
065: import org.netbeans.api.java.source.ui.ElementOpen;
066: import org.netbeans.modules.j2ee.api.ejbjar.EjbJar;
067: import org.netbeans.modules.j2ee.dd.api.ejb.EjbJarMetadata;
068: import org.netbeans.modules.j2ee.metadata.model.api.MetadataModel;
069: import org.netbeans.modules.j2ee.metadata.model.api.MetadataModelAction;
070: import org.netbeans.modules.j2ee.metadata.model.api.MetadataModelException;
071: import org.openide.util.Exceptions;
072:
073: /**
074: * @author pfiala
075: */
076: public class Utils {
077:
078: public static final String ICON_BASE_DD_VALID = "org/netbeans/modules/j2ee/ddloaders/resources/DDValidIcon"; // NOI18N
079: public static final String ICON_BASE_DD_INVALID = "org/netbeans/modules/j2ee/ddloaders/resources/DDInvalidIcon"; // NOI18N
080: public static final String ICON_BASE_EJB_MODULE_NODE = "org/netbeans/modules/j2ee/ddloaders/resources/EjbModuleNodeIcon"; // NOI18N
081: public static final String ICON_BASE_ENTERPRISE_JAVA_BEANS_NODE = "org/netbeans/modules/j2ee/ddloaders/resources/EjbContainerNodeIcon"; // NOI18N
082: public static final String ICON_BASE_SESSION_NODE = "org/netbeans/modules/j2ee/ddloaders/resources/SessionNodeIcon"; // NOI18N
083: public static final String ICON_BASE_ENTITY_NODE = "org/netbeans/modules/j2ee/ddloaders/resources/EntityNodeIcon"; // NOI18N
084: public static final String ICON_BASE_MESSAGE_DRIVEN_NODE = "org/netbeans/modules/j2ee/ddloaders/resources/MessageNodeIcon"; // NOI18N
085: public static final String ICON_BASE_MISC_NODE = "org/netbeans/modules/j2ee/ddloaders/resources/MiscNodeIcon"; // NOI18N
086:
087: private static BrowseFolders.FileObjectFilter imageFileFilter = new BrowseFolders.FileObjectFilter() {
088: public boolean accept(FileObject fileObject) {
089: return fileObject.getMIMEType().startsWith("image/"); // NOI18N
090: }
091: };
092:
093: public static String browseIcon(EjbJarMultiViewDataObject dataObject) {
094: FileObject fileObject = org.netbeans.modules.j2ee.ddloaders.multiview.ui.BrowseFolders
095: .showDialog(dataObject.getSourceGroups(),
096: imageFileFilter);
097: String relativePath;
098: if (fileObject != null) {
099: FileObject projectDirectory = dataObject
100: .getProjectDirectory();
101: relativePath = FileUtil.getRelativePath(projectDirectory,
102: fileObject);
103: } else {
104: relativePath = null;
105: }
106: return relativePath;
107: }
108:
109: public static Color getErrorColor() {
110: // inspired by org.openide.WizardDescriptor
111: Color c = UIManager.getColor("nb.errorForeground"); //NOI18N
112: return c == null ? new Color(89, 79, 191) : c;
113: }
114:
115: public static JTree findTreeComponent(Component component) {
116: if (component instanceof JTree) {
117: return (JTree) component;
118: }
119: if (component instanceof Container) {
120: Component[] components = ((Container) component)
121: .getComponents();
122: for (int i = 0; i < components.length; i++) {
123: JTree tree = findTreeComponent(components[i]);
124: if (tree != null) {
125: return tree;
126: }
127: }
128: }
129: return null;
130: }
131:
132: public static void scrollToVisible(JComponent component) {
133: org.netbeans.modules.xml.multiview.Utils
134: .scrollToVisible(component);
135: }
136:
137: public static String getBundleMessage(String messageId) {
138: return NbBundle.getMessage(Utils.class, messageId);
139: }
140:
141: public static String getBundleMessage(String messageId,
142: Object param1) {
143: return NbBundle.getMessage(Utils.class, messageId, param1);
144: }
145:
146: public static String getBundleMessage(String messageId,
147: Object param1, Object param2) {
148: return NbBundle.getMessage(Utils.class, messageId, param1,
149: param2);
150: }
151:
152: public static String getBundleMessage(String messageId,
153: Object param1, Object param2, Object param3) {
154: return NbBundle.getMessage(Utils.class, messageId, param1,
155: param2, param3);
156: }
157:
158: public static boolean isJavaIdentifier(String id) {
159: return Utilities.isJavaIdentifier(id);
160: }
161:
162: /**
163: * Returns true, if the passed string can be used as a qualified identifier.
164: * it does not check for semantic, only for syntax.
165: * The function returns true for any sequence of identifiers separated by
166: * dots.
167: */
168: public static boolean isValidPackageName(String packageName) {
169: String[] strings = packageName.split("[.]"); // NOI18N
170: if (strings.length == 0) {
171: return false;
172: }
173: for (int i = 0; i < strings.length; i++) {
174: if (!isJavaIdentifier(strings[i])) {
175: return false;
176: }
177: }
178: return packageName.charAt(packageName.length() - 1) != '.';
179: }
180:
181: public static void removeClass(ClassPath classPath, String className) {
182: FileObject sourceFile = getSourceFile(classPath, className);
183: if (sourceFile != null) {
184: // try {
185: //// JavaDataObject.find(sourceFile).delete();
186: // } catch (DataObjectNotFoundException e) {
187: // notifyError(e);
188: // } catch (IOException e) {
189: // notifyError(e);
190: // }
191: }
192: }
193:
194: public static FileObject getPackageFile(ClassPath classPath,
195: String packageName) {
196: return classPath.findResource(packageToPath(packageName));
197: }
198:
199: private static String packageToPath(String packageName) {
200: return packageName.replace('.', '/');
201: }
202:
203: public static String getPackage(String ejbClass) {
204: final int i = ejbClass.lastIndexOf('.');
205: if (i < 0) {
206: return "";
207: } else {
208: return ejbClass.substring(0, i);
209: }
210:
211: }
212:
213: public static void notifyError(Exception ex) {
214: NotifyDescriptor ndd = new NotifyDescriptor.Message(ex
215: .getMessage(), NotifyDescriptor.ERROR_MESSAGE);
216: DialogDisplayer.getDefault().notify(ndd);
217: }
218:
219: public static FileObject getSourceFile(ClassPath classPath,
220: String className) {
221: return classPath.findResource(packageToPath(className)
222: + ".java");
223: }
224:
225: // public static Node createEntityNode(FileObject ejbJarFile, ClassPath classPath, Entity entity) {
226: // //todo:
227: // //classPath = getSourceClassPath(ejbJarFile);
228: // EjbJar ejbJar;
229: // try {
230: // ejbJar = DDProvider.getDefault().getDDRoot(ejbJarFile);
231: // } catch (IOException e) {
232: // notifyError(e);
233: // return null;
234: // }
235: // return J2eeProjectView.getEjbNodesFactory().createEntityNode (entity, ejbJar, classPath, ejbJarFile);
236: // }
237:
238: // public static ClassPath getSourceClassPath(FileObject ejbJarFile) {
239: // Sources sources = ProjectUtils.getSources(FileOwnerQuery.getOwner(ejbJarFile));
240: // SourceGroup[] groups = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
241: // ClassPath srcClassPath = ClassPathFactory.createClassPath(new ClassPathImpl(groups));
242: // ClassPath bootClassPath = ClassPath.getClassPath(ejbJarFile, ClassPath.BOOT);
243: // return ClassPathSupport.createProxyClassPath(new ClassPath[]{srcClassPath, bootClassPath});
244: // }
245:
246: // public static Method getMethod(JavaClass javaClass, Method method) {
247: // if (javaClass == null || method == null) {
248: // return null;
249: // } else {
250: // List parameters = new LinkedList();
251: // for (Iterator it = method.getParameters().iterator(); it.hasNext();) {
252: // parameters.add(((Parameter) it.next()).getType());
253: // }
254: // return javaClass.getMethod(method.getName(), parameters, false);
255: // }
256: // }
257:
258: // public static void addMethod(JavaClass javaClass, Method prototype) {
259: // addMethod(javaClass, prototype, false);
260: // }
261:
262: // public static void addMethod(JavaClass javaClass, Method prototype, boolean remote) {
263: // if (prototype != null) {
264: // addMethod(javaClass, prototype, remote, prototype.getModifiers());
265: // }
266: // }
267: //
268: // public static void addMethod(JavaClass interfaceClass, Method prototype, boolean remote, int modifiers) {
269: // if (interfaceClass == null || prototype == null) {
270: // return;
271: // }
272: // if (getMethod(interfaceClass, prototype) != null) {
273: // return;
274: // }
275: // beginJmiTransaction(true);
276: // boolean rollback = true;
277: // try {
278: // Method method = JMIUtils.createMethod(interfaceClass);
279: // method.setName(prototype.getName());
280: // Type type = prototype.getType();
281: // if (type != null) {
282: // method.setType(JMIUtils.resolveType(type.getName()));
283: // }
284: // JMIUtils.replaceParameters(method, prototype.getParameters());
285: // method.setModifiers(modifiers);
286: // if (remote) {
287: // JMIUtils.addException(method, RemoteException.class.getName());
288: // }
289: // for (Iterator it = prototype.getExceptionNames().iterator(); it.hasNext();) {
290: // MultipartId mpId= (MultipartId) it.next();
291: // String exceptionName = mpId.getName();
292: // if (!"RemoteException".equals(exceptionName) && !"java.rmi.RemoteException".equals(exceptionName)) {
293: // JMIUtils.addException(method, exceptionName);
294: // }
295: // }
296: // getContents(interfaceClass).add(method);
297: // rollback = false;
298: // } finally {
299: // endJmiTransaction(rollback);
300: // }
301: // }
302: //
303: // public static List getContents(JavaClass javaClass) {
304: // return ((JavaClass) JMIUtils.resolveType(javaClass.getName())).getContents();
305: // }
306: //
307: // public static void removeMethod(JavaClass javaClass, Method method) {
308: // if (javaClass == null || method == null) {
309: // return;
310: // }
311: // beginJmiTransaction(true);
312: // boolean rollback = true;
313: // try {
314: // getContents(javaClass).remove(getMethod(javaClass, method));
315: // rollback = false;
316: // } finally {
317: // endJmiTransaction(rollback);
318: // }
319: // }
320: //
321: // private static Lookup createClassRefactoringLookup(String fullClassName) {
322: // Node node = SourceNodes.getExplorerFactory().createClassNode((JavaClass) JMIUtils.resolveType(fullClassName));
323: // InstanceContent ic = new InstanceContent();
324: // ic.add(node);
325: // return new AbstractLookup(ic);
326: // }
327: //
328: // public static void activateRenameClassUI(String fullClassName) {
329: // Lookup lookup = createClassRefactoringLookup(fullClassName);
330: // final Action action = RefactoringActionsFactory.renameAction().createContextAwareInstance(lookup);
331: // action.actionPerformed(RefactoringActionsFactory.DEFAULT_EVENT);
332: // }
333: //
334: // public static void activateMoveClassUI(String fullClassName) {
335: // Lookup lookup = createClassRefactoringLookup(fullClassName);
336: // final Action action = RefactoringActionsFactory.moveClassAction().createContextAwareInstance(lookup);
337: // action.actionPerformed(RefactoringActionsFactory.DEFAULT_EVENT);
338: // }
339: //
340: // public static void renameMethod(Method method, String name) {
341: // if (method != null) {
342: // method.setName(name);
343: // }
344: // }
345:
346: public static String getEjbDisplayName(Ejb ejb) {
347: String name = ejb.getDefaultDisplayName();
348: if (name == null) {
349: name = ejb.getEjbName();
350: if (name == null) {
351: name = " "; // NOI18N
352: }
353: }
354: return name;
355: }
356:
357: /**
358: * Opens the editor for the given <code>ejbClass</code>.
359: * @param ejbJarFile the ejb-jar.xml file where the class is defined.
360: * @param ejbClass the FQN of the Ejb to be opened.
361: */
362: public static void openEditorFor(FileObject ejbJarFile,
363: final String ejbClass) {
364: EjbJar ejbModule = EjbJar.getEjbJar(ejbJarFile);
365: // see #123848
366: if (ejbModule == null) {
367: displaySourceNotFoundDialog();
368: return;
369: }
370:
371: MetadataModel<EjbJarMetadata> ejbModel = ejbModule
372: .getMetadataModel();
373: try {
374: FileObject classFo = ejbModel
375: .runReadAction(new MetadataModelAction<EjbJarMetadata, FileObject>() {
376:
377: public FileObject run(EjbJarMetadata metadata)
378: throws Exception {
379: return metadata.findResource(ejbClass
380: .replace('.', '/')
381: + ".java"); //NO18N
382: }
383: });
384:
385: final List<ElementHandle<TypeElement>> handle = new ArrayList<ElementHandle<TypeElement>>(
386: 1);
387: if (classFo != null) {
388: JavaSource source = JavaSource.forFileObject(classFo);
389: source.runUserActionTask(
390: new Task<CompilationController>() {
391:
392: public void run(
393: CompilationController controller)
394: throws Exception {
395: controller
396: .toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
397: TypeElement typeElement = controller
398: .getElements().getTypeElement(
399: ejbClass);
400: if (typeElement != null) {
401: handle.add(ElementHandle
402: .create(typeElement));
403: }
404: }
405: }, false);
406: }
407: if (!handle.isEmpty()) {
408: ElementOpen.open(classFo, handle.get(0));
409: } else {
410: displaySourceNotFoundDialog();
411: }
412:
413: } catch (MetadataModelException ex) {
414: Exceptions.printStackTrace(ex);
415: } catch (IOException ex) {
416: Exceptions.printStackTrace(ex);
417: }
418: }
419:
420: private static void displaySourceNotFoundDialog() {
421: DialogDisplayer.getDefault().notify(
422: new NotifyDescriptor.Message(NbBundle.getMessage(
423: Utils.class, "MSG_sourceNotFound")));
424:
425: }
426:
427: /**
428: * Make sure that the code will run in AWT dispatch thread
429: * @param runnable
430: */
431: public static void runInAwtDispatchThread(Runnable runnable) {
432: org.netbeans.modules.xml.multiview.Utils
433: .runInAwtDispatchThread(runnable);
434: }
435:
436: // public static void changeParameterType(final Method method, Type type) {
437: // if (method != null) {
438: // Parameter parameter = (Parameter) method.getParameters().get(0);
439: // parameter.setType(type);
440: // }
441: // }
442: //
443: // public static void beginJmiTransaction(boolean writeAccess) {
444: // JavaModel.getJavaRepository().beginTrans(writeAccess);
445: // }
446: //
447: // public static void endJmiTransaction(boolean rollback) {
448: // JavaModel.getJavaRepository().endTrans(rollback);
449: // }
450:
451: // private static class ClassPathImpl implements ClassPathImplementation {
452: //
453: // private List resources = new LinkedList();
454: //
455: // private class PathResourceImpl implements PathResourceImplementation {
456: //
457: // URL[] roots;
458: //
459: // public PathResourceImpl(URL root) {
460: // this.roots = new URL[]{root};
461: // }
462: //
463: // public URL[] getRoots() {
464: // return roots;
465: // }
466: //
467: // public ClassPathImplementation getContent() {
468: // return ClassPathImpl.this;
469: // }
470: //
471: // public void addPropertyChangeListener(PropertyChangeListener listener) {
472: // }
473: //
474: // public void removePropertyChangeListener(PropertyChangeListener listener) {
475: // }
476: // }
477: //
478: // public ClassPathImpl(SourceGroup[] groups) {
479: // for (int i = 0; i < groups.length; i++) {
480: // SourceGroup group = groups[i];
481: // try {
482: // resources.add(new PathResourceImpl(group.getRootFolder().getURL()));
483: // } catch (FileStateInvalidException e) {
484: // notifyError(e);
485: // }
486: // }
487: // }
488: //
489: // public java.util.List /*<PathResourceImplementation>*/ getResources() {
490: // return resources;
491: // }
492: //
493: // public void addPropertyChangeListener(PropertyChangeListener listener) {
494: // }
495: //
496: // public void removePropertyChangeListener(PropertyChangeListener listener) {
497: // }
498: // }
499: }
|