diff options
Diffstat (limited to 'plugins/org.eclipse.jst.j2ee/common')
51 files changed, 0 insertions, 9524 deletions
diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/CMPJavaChangeSynchronizationAdapter.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/CMPJavaChangeSynchronizationAdapter.java deleted file mode 100644 index 1992762b4..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/CMPJavaChangeSynchronizationAdapter.java +++ /dev/null @@ -1,378 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.eclipse.core.resources.IProject; -import org.eclipse.emf.common.notify.AdapterFactory; -import org.eclipse.emf.common.notify.Notification; -import org.eclipse.emf.common.notify.Notifier; -import org.eclipse.emf.common.notify.impl.AdapterImpl; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.EStructuralFeature; -import org.eclipse.emf.ecore.resource.Resource; -import org.eclipse.emf.ecore.util.EcoreUtil; -import org.eclipse.jem.internal.adapters.jdom.JavaJDOMAdapterFactory; -import org.eclipse.jem.internal.java.adapters.ReadAdaptor; -import org.eclipse.jem.internal.java.adapters.ReflectionAdaptor; -import org.eclipse.jem.java.Field; -import org.eclipse.jem.java.JavaClass; -import org.eclipse.jem.java.JavaVisibilityKind; -import org.eclipse.jem.java.util.NotificationUtil; -import org.eclipse.jem.util.emf.workbench.ProjectUtilities; -import org.eclipse.jem.util.emf.workbench.nature.EMFNature; -import org.eclipse.jst.j2ee.ejb.CMPAttribute; -import org.eclipse.jst.j2ee.ejb.ContainerManagedEntity; -import org.eclipse.jst.j2ee.ejb.EJBJar; -import org.eclipse.jst.j2ee.ejb.EjbPackage; -import org.eclipse.jst.j2ee.ejb.internal.impl.EjbFactoryImpl; - -/** - * This adapter is used to listen for changes to the ejb class or the primary key class in order to - * reflect the proper CMP field types and the proper key attributes. - */ -public class CMPJavaChangeSynchronizationAdapter extends AdapterImpl { - - private static final String J2EE_PROJ_MIGRATION_ADAPTER = "J2EEProjectMigration"; //$NON-NLS-1$ - - protected static EjbPackage EJB_PACK = EjbFactoryImpl.getPackage(); - - private static HashMap enablementMap = new HashMap(); - - public static void disable(ContainerManagedEntity cmp) { - enablementMap.put(cmp, Boolean.FALSE); - } - - public static void enable(ContainerManagedEntity cmp) { - enablementMap.put(cmp, Boolean.TRUE); - } - - public static boolean isEnabled(ContainerManagedEntity cmp) { - if (!enablementMap.containsKey(cmp)) - return true; - return ((Boolean) enablementMap.get(cmp)).booleanValue(); - } - - protected Resource cmpResource; - - private List foundKeys = new ArrayList(); - - /* - * This Set is used to avoid reacting to notifications for a notifier while - * updating that notifier. - */ - private Set updatingSet = new HashSet(); - - public CMPJavaChangeSynchronizationAdapter() { - super(); - } // EJBKeyShapeMaintenanceAdapter - - /** - * Notifies if there is change in the key shape. - * - * @param Notification - * msg - Message indicates what has changed. - */ - public void notifyChanged(Notification msg) { - if (!isEnabled(getCMP())) { - enable(getCMP()); - return; - } - Object notifier = msg.getNotifier(); - if (!updatingSet.contains(notifier)) { - try { - updatingSet.add(notifier); - switch (msg.getEventType()) { - case Notification.SET : - setNotification(msg); - break; - case Notification.UNSET : - unsetNotification(msg); - break; - case Notification.REMOVING_ADAPTER : - removeAdapterNotification(msg); - break; - case ReflectionAdaptor.EVENT : - jemFlushNotification(msg); - break; - } - } finally { - updatingSet.remove(notifier); - } - } - } - - /** - * Use if the there was an set notification. - * - * @param Notification - * msg - Message indicates what has changed. - */ - protected void setNotification(Notification msg) { - EStructuralFeature sf = (EStructuralFeature) msg.getFeature(); - if (sf == EJB_PACK.getEnterpriseBean_EjbClass() || sf == EJB_PACK.getEntity_PrimaryKey()) { - if (!isMigrating()) { - removeAttributeMaintenanceAdapter((Notifier) msg.getOldValue()); - addAttributeMaintenanceAdapter((Notifier) msg.getNewValue()); - touchKeyShapeAdapter(msg); - } - } else if (sf == EJB_PACK.getEntity_PrimaryKey()) { - removeAttributeMaintenanceAdapter((Notifier) msg.getOldValue()); - if (shouldAddToPrimaryKeyClass((ContainerManagedEntity) getTarget())) - addAttributeMaintenanceAdapter((Notifier) msg.getNewValue()); - } else { - jemFlushNotification(msg); //In EMF a TOUCH is a SET. - } - } // setNotification - - /** - * @return - */ - private boolean isMigrating() { - EJBJar jar = ((ContainerManagedEntity) getTarget()).getEjbJar(); - if (jar != null) - return EcoreUtil.getExistingAdapter(jar, J2EE_PROJ_MIGRATION_ADAPTER) != null; - return false; - } - - // setNotification - /** - * Use if the there was an unset notification. - * - * @param Notification - * msg - Message indicates what has changed. - */ - protected void unsetNotification(Notification msg) { - EStructuralFeature sf = (EStructuralFeature) msg.getFeature(); - if ((sf == EJB_PACK.getEnterpriseBean_EjbClass() || sf == EJB_PACK.getEntity_PrimaryKey()) && !isMigrating()) { - removeAttributeMaintenanceAdapter((Notifier) msg.getOldValue()); - } - } // unsetNotification - - /** - * Use if the there was an touch notification. - * - * @param Notification - * msg - Message indicates what has changed. - */ - protected void jemFlushNotification(Notification msg) { - if ((NotificationUtil.isFlushNewEvent(msg) || NotificationUtil.isFlushEvent(msg)) && !isMigrating()) { - if (msg.getNotifier() == ((ContainerManagedEntity) getTarget()).getEjbClass()) { - touchBeanAdapter(msg); - } else if (msg.getNotifier() == ((ContainerManagedEntity) getTarget()).getPrimaryKey()) { - touchKeyShapeAdapter(msg); - } // if - //if the notifier is eq the primary key - //else ejb bean class flush - } // if - } // touchNotification - - protected void removeAdapterNotification(Notification msg) { - if (msg.getOldValue() == this && msg.getNotifier() instanceof ContainerManagedEntity) { - ContainerManagedEntity cmp = (ContainerManagedEntity) msg.getNotifier(); - if (cmp.getEjbClass() != null) - cmp.getEjbClass().eAdapters().remove(this); - if (cmp.getPrimaryKey() != null) - cmp.getPrimaryKey().eAdapters().remove(this); - } - } - - /** - * Adds the key shape adapter - * - * @param Notifier - * notifier - The current notifier. - */ - protected void addAttributeMaintenanceAdapter(Notifier notifier) { - if (notifier != null && !notifier.eAdapters().contains(this)) - notifier.eAdapters().add(this); - } - - /** - * Remove the key shape adapter - */ - protected void removeAttributeMaintenanceAdapter(Notifier notifier) { - if (notifier != null) - notifier.eAdapters().remove(this); - } - - /** - * The key has been touched. - * - * @param Notification - * msg - The notification message. - */ - protected void touchKeyShapeAdapter(Notification msg) { - if (msg == null) - return; - ContainerManagedEntity cmp = (ContainerManagedEntity) getTarget(); - JavaClass primaryKeyClass = cmp.getPrimaryKey(); - //Synch the two lists. - synchCMPandKeyAttributes(cmp, primaryKeyClass); - } // touchKeyShapeAdapter - - /** - * The ejb class has been flushed. - * - * @param Notification - * msg - The notification message. - */ - protected void touchBeanAdapter(Notification msg) { - if (msg == null) - return; - ContainerManagedEntity cmp = (ContainerManagedEntity) getTarget(); - List cmpAttributes = cmp.getPersistentAttributes(); - if (cmpAttributes != null || !cmpAttributes.isEmpty()) { - boolean modFlag = getCurrentModificationFlag(); - try { - for (int i = 0; i < cmpAttributes.size(); i++) { - CMPAttribute cmpAttr = (CMPAttribute) cmpAttributes.get(i); - if (cmpAttr != null && !cmpAttr.isDerived()) { - cmpAttr.setEType(null); - } - } - } finally { - setModificationFlag(modFlag); - } - } - synchCMPandKeyAttributes(cmp, cmp.getPrimaryKey()); - } - - /** - * Synchronzies the cmp and primary key class attributes. - * - * @param ContainerManagedEntity - * cmp - The cmp. - * @param JavaClass - * primaryKeyClass - */ - protected void synchCMPandKeyAttributes(ContainerManagedEntity cmp, JavaClass primaryKeyClass) { - if (cmp == null || primaryKeyClass == null || cmp.getPrimKeyField() != null || primaryKeyClass.getQualifiedName().startsWith("java.lang")) //$NON-NLS-1$ - return; - - // make sure we flush the primary key to get latest updates if no save - // took place - flushPrimaryKeyClass(primaryKeyClass); - - List cmpAttributes = cmp.getPersistentAttributes(); - if (cmpAttributes != null || !cmpAttributes.isEmpty()) { - foundKeys.clear(); - List keyAttributesList = cmp.getKeyAttributes(); - foundKeys.addAll(keyAttributesList); - boolean modFlag = getCurrentModificationFlag(); - try { - List keyFields = primaryKeyClass.getFieldsExtended(); - for (int i = 0; i < keyFields.size(); i++) { - Field field = (Field) keyFields.get(i); - if (field.getJavaVisibility() != JavaVisibilityKind.PUBLIC_LITERAL) - continue; - String fieldName = field.getName(); - if (fieldName != null) { - CMPAttribute keyAttr = cmp.getKeyAttribute(fieldName); - if (keyAttr == null) - cmp.addKeyAttributeName(fieldName); - else - foundKeys.remove(keyAttr); - } - } - if (!foundKeys.isEmpty()) - keyAttributesList.removeAll(foundKeys); - } finally { - setModificationFlag(modFlag); - } - } - } - - public void setTarget(Notifier newTarget) { - boolean isChanged = getTarget() != newTarget; - if (newTarget == null) { - super.setTarget(newTarget); - cmpResource = null; - } else if (newTarget instanceof ContainerManagedEntity) { - //TODO - uncomment when compile errors are gone - if (false)/* (EJBCommandCopier.isCodegenCopy(newTarget)) */ - newTarget.eAdapters().remove(this); - else { - Resource res = ((ContainerManagedEntity) newTarget).eResource(); - if (res != null && res.getResourceSet() != null) { - super.setTarget(newTarget); - if (isChanged) - initializeTarget(); - } - } - } - } - - /** - * - */ - private void initializeTarget() { - ContainerManagedEntity cmp = (ContainerManagedEntity) getTarget(); - addAttributeMaintenanceAdapter(cmp.getEjbClass()); - if (shouldAddToPrimaryKeyClass(cmp)) - addAttributeMaintenanceAdapter(cmp.getPrimaryKey()); - } - - private boolean shouldAddToPrimaryKeyClass(ContainerManagedEntity cmp) { - return cmp.getPrimKeyField() == null && cmp.getPrimaryKey() != null && !cmp.getPrimaryKey().getQualifiedName().startsWith("java.lang"); //$NON-NLS-1$ - } - - protected Resource getCMPResource() { - if (cmpResource == null && getTarget() != null) - cmpResource = ((EObject) getTarget()).eResource(); - return cmpResource; - } - - protected boolean getCurrentModificationFlag() { - return getCMPResource() != null && cmpResource.getContents() != null ? cmpResource.isModified() : false; - } - - protected void setModificationFlag(boolean aBoolean) { - if (getCMPResource() != null) - getCMPResource().setModified(aBoolean); - } - - public ContainerManagedEntity getCMP() { - if (getTarget() instanceof ContainerManagedEntity) - return (ContainerManagedEntity) getTarget(); - return null; - } - - protected boolean flushPrimaryKeyClass(JavaClass primaryKeyClass) { - // ensure the primary key class is flushed and reloaded to get latest - // content - IProject p = ProjectUtilities.getProject(primaryKeyClass); - try { - List natures = EMFNature.getRegisteredRuntimes(p); - EMFNature nature = null; - for (int i = 0; i < natures.size(); i++) { - if (natures.get(i) instanceof EMFNature) - nature = (EMFNature) natures.get(i); - } - List adapterFactories = nature.getResourceSet().getAdapterFactories(); - AdapterFactory factory = EcoreUtil.getAdapterFactory(adapterFactories, ReadAdaptor.TYPE_KEY); - if (factory instanceof JavaJDOMAdapterFactory) { - JavaJDOMAdapterFactory javaFactory = (JavaJDOMAdapterFactory) factory; - javaFactory.flushReflectionNoNotification(primaryKeyClass.getQualifiedName()); - return true; - } - } catch (Exception e) { - // We don't really care what the exception was, we'll just bail out - // and return false; - } - return false; - } -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/ClasspathModel.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/ClasspathModel.java deleted file mode 100644 index d1c9d3ef3..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/ClasspathModel.java +++ /dev/null @@ -1,661 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common; - - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Path; -import org.eclipse.emf.common.util.URI; -import org.eclipse.jem.util.emf.workbench.ProjectUtilities; -import org.eclipse.jem.util.logger.proxy.Logger; -import org.eclipse.jst.j2ee.application.internal.operations.ClassPathSelection; -import org.eclipse.jst.j2ee.application.internal.operations.ClasspathElement; -import org.eclipse.jst.j2ee.classpathdep.ClasspathDependencyUtil; -import org.eclipse.jst.j2ee.commonarchivecore.internal.helpers.ArchiveManifest; -import org.eclipse.jst.j2ee.componentcore.J2EEModuleVirtualComponent; -import org.eclipse.jst.j2ee.internal.J2EEConstants; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; -import org.eclipse.jst.j2ee.internal.project.J2EEProjectUtilities; -import org.eclipse.wst.common.componentcore.ComponentCore; -import org.eclipse.wst.common.componentcore.UnresolveableURIException; -import org.eclipse.wst.common.componentcore.internal.ModuleStructuralModel; -import org.eclipse.wst.common.componentcore.internal.StructureEdit; -import org.eclipse.wst.common.componentcore.internal.impl.ModuleURIUtil; -import org.eclipse.wst.common.componentcore.internal.util.ComponentUtilities; -import org.eclipse.wst.common.componentcore.resources.IVirtualComponent; -import org.eclipse.wst.common.componentcore.resources.IVirtualReference; -import org.eclipse.wst.common.internal.emfworkbench.validateedit.ResourceStateInputProvider; -import org.eclipse.wst.common.internal.emfworkbench.validateedit.ResourceStateValidator; -import org.eclipse.wst.common.internal.emfworkbench.validateedit.ResourceStateValidatorImpl; -import org.eclipse.wst.common.internal.emfworkbench.validateedit.ResourceStateValidatorPresenter; - -public class ClasspathModel implements ResourceStateInputProvider, ResourceStateValidator { - - protected IProject project; - protected IVirtualComponent selectedEARComponent; - protected IVirtualComponent component; - protected IVirtualComponent[] availableEARComponents = null; - protected ClassPathSelection classPathSelection; - protected List listeners; - protected List nonResourceFiles; - protected ResourceStateValidator stateValidator; - protected ArchiveManifest manifest; - public static String NO_EAR_MESSAGE = CommonEditResourceHandler.getString("NO_EAR_JARDEP_FOR_MOD_UI_"); //$NON-NLS-1$ - protected List targetWLPRefComponentList; - protected boolean isWLPModel = false; - protected ClassPathSelection classPathWLPSelection; - - protected Comparator comparator = new Comparator() { - public int compare(Object o1, Object o2) { - IVirtualComponent e1 = (IVirtualComponent) o1; - IVirtualComponent e2 = (IVirtualComponent) o2; - return e1.getProject().getName().compareTo(e2.getProject().getName()); - } - }; - - public ClasspathModel(ArchiveManifest initialManifest) { - this(initialManifest, false); - } - - public ClasspathModel(ArchiveManifest initialManifest, boolean isWLPModel) { - super(); - manifest = initialManifest; - this.isWLPModel = isWLPModel; - } - - public IProject getProject() { - return project; - } - - public void setProject(IProject project) { - this.project = project; - initializeComponent(); - getAvailableEARComponents(); - } - - private void initializeComponent() { - setComponent(ComponentCore.createComponent(getProject())); - } - - protected IVirtualComponent[] refreshAvailableEARs() { - if (component != null) { - IProject[] earProjects = J2EEProjectUtilities.getReferencingEARProjects(getComponent().getProject()); - availableEARComponents = ComponentUtilities.getComponents(earProjects); - if (availableEARComponents != null && availableEARComponents.length > 0) { - Arrays.sort(availableEARComponents, comparator); - if (selectedEARComponent == null || !Arrays.asList(availableEARComponents).contains(selectedEARComponent)) { - if (availableEARComponents.length > 0) - selectedEARComponent = availableEARComponents[0]; - else - selectedEARComponent = null; - } - } - } - return availableEARComponents; - } - - public IVirtualComponent[] getAvailableEARComponents() { - if (availableEARComponents == null) - refreshAvailableEARs(); - return availableEARComponents; - } - - public IVirtualComponent getSelectedEARComponent() { - return selectedEARComponent; - } - - public void setSelectedEARComponent(IVirtualComponent component) { - selectedEARComponent = component; - fireNotification(new ClasspathModelEvent(ClasspathModelEvent.EAR_PROJECT_CHANGED)); - } - - public String getArchiveURI() { - if (selectedEARComponent != null) { - IVirtualReference [] refs = selectedEARComponent.getReferences(); - IVirtualComponent moduleComp = getComponent(); - for(int i=0; i<refs.length; i++){ - if(refs[i].getReferencedComponent().equals(moduleComp)){ - return refs[i].getArchiveName(); - } - } - } - return null; - } - - protected void initializeSelection(ArchiveManifest existing) { - if (!J2EEProjectUtilities.isEARProject(getProject())) { - if (getProject() != null) { - if(existing != null){ - manifest = existing; - } - } - createClassPathSelection(); - } - } - - protected void createClassPathSelection() { - if (getComponent() != null && selectedEARComponent != null ) { - classPathSelection = new ClassPathSelection(getComponent(), selectedEARComponent); - } else if (selectedEARComponent == null) { - classPathSelection = new ClassPathSelection(getComponent()); - } else { - classPathSelection = null; - } - } - - public void dispose() { - } - - public ClassPathSelection getClassPathSelection() { - if (classPathSelection == null) - initializeSelection(null); - return classPathSelection; - } - - public void resetClassPathSelection(ArchiveManifest mf) { - initializeSelection(mf); - fireNotification(new ClasspathModelEvent(ClasspathModelEvent.CLASS_PATH_RESET)); - } - - public void resetClassPathSelection() { - resetClassPathSelection(null); - } - - public void resetClassPathSelectionForWLPs() { - classPathWLPSelection = null; - } - - public void addListener(ClasspathModelListener listener) { - if (listeners == null) - listeners = new ArrayList(); - - listeners.add(listener); - } - - public void removeListener(ClasspathModelListener listener) { - if (listeners != null) - listeners.remove(listener); - } - - public void fireNotification(ClasspathModelEvent evt) { - if (listeners == null) - return; - - for (int i = 0; i < listeners.size(); i++) { - ClasspathModelListener listener = (ClasspathModelListener) listeners.get(i); - listener.modelChanged(evt); - } - } - - /** - * Sets the isSelected for the classpath element and sends out a notification of type - * {@link ClasspathModelEvent#CLASS_PATH_CHANGED} - */ - public void setSelection(ClasspathElement element, boolean selected) { - element.setSelected(selected); - if (!isWLPModel()) { - updateManifestClasspath(); - } else { - // at least fire the change event - fireNotification(new ClasspathModelEvent(ClasspathModelEvent.CLASS_PATH_CHANGED)); - } - } - - /** - * Select or deselect all and notify - */ - public void setAllClasspathElementsSelected(boolean selected) { - ClassPathSelection s = getClassPathSelection(); - if (s != null) { - s.setAllSelected(selected); - updateManifestClasspath(); - } - } - - /** - * Select or deselect all and notify - */ - public void setAllClasspathElementsSelected(List elements, boolean selected) { - ClassPathSelection s = getClassPathSelection(); - if (s != null) { - s.setAllSelected(elements, selected); - updateManifestClasspath(); - } - } - - /** - * Updates the manifest Class-Path:, and sends out a notification of type - * {@link ClasspathModelEvent#CLASS_PATH_CHANGED} - */ - public void updateManifestClasspath() { - if (classPathSelection != null && classPathSelection.isModified()) { - manifest.setClassPath(classPathSelection.toString()); - fireNotification(new ClasspathModelEvent(ClasspathModelEvent.CLASS_PATH_CHANGED)); - } - } - - /** - * Updates the manifest Main-Class:, and sends out a notification of type - * {@link ClasspathModelEvent#MAIN_CLASS_CHANGED} - */ - public void updateMainClass(String mainClass) { - manifest.setMainClass(mainClass); - fireNotification(new ClasspathModelEvent(ClasspathModelEvent.MAIN_CLASS_CHANGED)); - } - - /** - * Updates the manifest Main-Class:, and sends out a notification of type - * {@link ClasspathModelEvent#MAIN_CLASS_CHANGED} - */ - public void updateImplVersion(String implVersion) { - manifest.setImplemenationVersion(implVersion); - fireNotification(new ClasspathModelEvent(ClasspathModelEvent.IMPL_VERSION_CHANGED)); - } - - public void fireSavedEvent() { - fireNotification(new ClasspathModelEvent(ClasspathModelEvent.MODEL_SAVED)); - } - - /** - * Sets the manifest without touching the archive, or notifying - */ - public void primSetManifest(ArchiveManifest mf) { - manifest = mf; - } - - /** - * Sets the manfest on the archive, updates the classpath selection, and notifies - */ - public void setManifest(ArchiveManifest newManifest) { - try { - J2EEProjectUtilities.writeManifest(getProject(), newManifest); - } catch (IOException e) { - J2EEPlugin.logError(e); - } - getClassPathSelection(); // Ensure the selection is initialized. - fireNotification(new ClasspathModelEvent(ClasspathModelEvent.MANIFEST_CHANGED)); - } - - public void selectEAR(int index) { - selectedEARComponent = availableEARComponents[index]; - initializeSelection(null); - fireNotification(new ClasspathModelEvent(ClasspathModelEvent.EAR_PROJECT_CHANGED)); - } - - public void moveUp(List toMoveUp) { - getClassPathSelection().moveUp(toMoveUp); - updateManifestClasspath(); - } - - public void moveDown(List toMoveDown) { - getClassPathSelection().moveDown(toMoveDown); - updateManifestClasspath(); - } - - public void refresh() { - ArchiveManifest mf = null; - if (getComponent() != null) - mf = J2EEProjectUtilities.readManifest(getProject()); - refreshAvailableEARs(); - resetClassPathSelection(mf); - } - - /** - * @see com.ibm.etools.emf.workbench.ResourceStateInputProvider#cacheNonResourceValidateState(List) - */ - public void cacheNonResourceValidateState(List roNonResourceFiles) { - } - - /** - * @see com.ibm.etools.emf.workbench.ResourceStateInputProvider#getNonResourceFiles() - */ - public List getNonResourceFiles() { - if (nonResourceFiles == null) - initNonResourceFiles(); - return nonResourceFiles; - } - - protected void initNonResourceFiles() { - // Might be opened from a JAR - if (getComponent() == null || getComponent().isBinary()){ - return; - } - nonResourceFiles = new ArrayList(1); - if(isWLPModel){ - IFile dotProject = getComponent().getProject().getFile(ProjectUtilities.DOT_PROJECT); - if(dotProject != null){ - nonResourceFiles.add(dotProject); - } - } else { - IFile mf = J2EEProjectUtilities.getManifestFile(getComponent().getProject()); - if (mf != null){ - nonResourceFiles.add(mf); - } - } - } - - /** - * @see com.ibm.etools.emf.workbench.ResourceStateInputProvider#getNonResourceInconsistentFiles() - */ - public List getNonResourceInconsistentFiles() { - return null; - } - - /** - * @see com.ibm.etools.emf.workbench.ResourceStateInputProvider#isDirty() - */ - public boolean isDirty() { - ClassPathSelection selection = getClassPathSelection(); - if (selection == null) - return false; - return selection.isModified(); - } - - - /** - * Return a list of all the files that will get modified as a result of running this operation; - * used for validateEdit - */ - public Set getAffectedFiles() { - Set result = new HashSet(); - IFile aFile = J2EEProjectUtilities.getManifestFile(getComponent().getProject()); - if (aFile != null && aFile.exists()) - result.add(aFile); - result.addAll(ProjectUtilities.getFilesAffectedByClasspathChange(getComponent().getProject())); - return result; - } - - /** - * @see com.ibm.etools.emf.workbench.ResourceStateInputProvider#getResources() - */ - public List getResources() { - if(isWLPModel){ - StructureEdit sEdit = null; - try { - sEdit = StructureEdit.getStructureEditForWrite(project); - ModuleStructuralModel structuralModel = sEdit.getModuleStructuralModel(); - List resources = new ArrayList(); - resources.addAll(structuralModel.getResources()); - return resources; - } catch(Exception e){ - e.printStackTrace(); - return Collections.EMPTY_LIST; - } - finally { - if (sEdit !=null){ - sEdit.dispose(); - } - } - } else { - return Collections.EMPTY_LIST; - } - } - - public boolean selectDependencyIfNecessary(IProject referencedProject) { - getClassPathSelection(); - if (classPathSelection == null || classPathSelection.hasDirectOrIndirectDependencyTo(referencedProject)) - return false; - - ClasspathElement element = classPathSelection.getClasspathElement(referencedProject); - if (element != null) { - setSelection(element, true); - return true; - } - return false; - } - - public boolean selectDependencyIfNecessary(String jarName) { - getClassPathSelection(); - if (classPathSelection == null || classPathSelection.hasDirectOrIndirectDependencyTo(jarName)) - return false; - - ClasspathElement element = classPathSelection.getClasspathElement(jarName); - if (element != null) { - setSelection(element, true); - return true; - } - return false; - } - - public void removeDependency(String jarName) { - getClassPathSelection(); - if (classPathSelection == null) - return; - - ClasspathElement element = classPathSelection.getClasspathElement(jarName); - if (element != null && element.isValid()) - setSelection(element, false); - } - - public void removeDependency(IProject referencedProject) { - getClassPathSelection(); - if (classPathSelection == null) - return; - - ClasspathElement element = classPathSelection.getClasspathElement(referencedProject); - if (element != null && element.isValid()) - setSelection(element, false); - } - - public void selectFilterLevel(int filterLevel) { - getClassPathSelection(); - if (classPathSelection != null) - classPathSelection.selectFilterLevel(filterLevel); - updateManifestClasspath(); - } - - /** - * Gets the stateValidator. - * - * @return Returns a ResourceStateValidator - */ - public ResourceStateValidator getStateValidator() { - if (stateValidator == null) - stateValidator = createStateValidator(); - return stateValidator; - } - - /** - * Method createStateValidator. - * - * @return ResourceStateValidator - */ - private ResourceStateValidator createStateValidator() { - return new ResourceStateValidatorImpl(this); - } - - /** - * @see ResourceStateValidator#checkActivation(ResourceStateValidatorPresenter) - */ - public void checkActivation(ResourceStateValidatorPresenter presenter) throws CoreException { - getStateValidator().checkActivation(presenter); - } - - /** - * @see ResourceStateValidator#lostActivation(ResourceStateValidatorPresenter) - */ - public void lostActivation(ResourceStateValidatorPresenter presenter) throws CoreException { - getStateValidator().lostActivation(presenter); - } - - /** - * @see ResourceStateValidator#validateState(ResourceStateValidatorPresenter) - */ - public IStatus validateState(ResourceStateValidatorPresenter presenter) throws CoreException { - return getStateValidator().validateState(presenter); - } - - /** - * @see ResourceStateValidator#checkSave(ResourceStateValidatorPresenter) - */ - public boolean checkSave(ResourceStateValidatorPresenter presenter) throws CoreException { - return getStateValidator().checkSave(presenter); - } - - /** - * @see ResourceStateValidator#checkReadOnly() - */ - public boolean checkReadOnly() { - return getStateValidator().checkReadOnly(); - } - - public IVirtualComponent getComponent() { - return component; - } - - public void setComponent(IVirtualComponent component) { - this.component = component; - } - - public ClassPathSelection getClassPathSelectionForWLPs() { - if (classPathWLPSelection == null) - initializeSelectionForWLPs(); - return classPathWLPSelection; - } - - //copied from WebArtifactEdit - private static IPath WEBLIB = new Path(J2EEConstants.WEB_INF_LIB).makeAbsolute(); - private static IPath WEBINF_CLASSES = new Path(J2EEConstants.WEB_INF_CLASSES).makeAbsolute(); - private static IVirtualReference[] getLibModules(IProject project) { - List result = new ArrayList(); - IVirtualComponent comp = ComponentCore.createComponent(project); - IVirtualReference[] refComponents = null; - if (!comp.isBinary()) - refComponents = ((J2EEModuleVirtualComponent)comp).getNonManifestReferences(); - else - refComponents = comp.getReferences(); - // Check the deployed path to make sure it has a lib parent folder and matchs the web.xml - // base path - for (int i = 0; i < refComponents.length; i++) { - if (refComponents[i].getRuntimePath().equals(WEBLIB)) - result.add(refComponents[i]); - } - - return (IVirtualReference[]) result.toArray(new IVirtualReference[result.size()]); - } - - private void initializeSelectionForWLPs() { - classPathWLPSelection = new ClassPathSelection(); - classPathWLPSelection.setFilterLevel(ClassPathSelection.FILTER_NONE); - //this is the set of all projects that are already mapped as web library projects - HashSet existingWebLibProjects = new HashSet(); - List otherExistingWebLibRefs = new ArrayList(); - IVirtualReference [] libModules = getLibModules(component.getProject()); - for(int i=0;i<libModules.length; i++){ - IVirtualComponent comp = libModules[i].getReferencedComponent(); - if(comp != null && comp.exists()){ - if(comp.isBinary()){ - otherExistingWebLibRefs.add(libModules[i]); - } else { - IProject p = comp.getProject(); - if(p != null && p.exists()){ - existingWebLibProjects.add(p); - } - } - } - } - - //this is the list of all projects that should show up in the list - HashSet possibleWebLibs = new HashSet(); - try{ - List javaProjects = J2EEProjectUtilities.getAllJavaNonFlexProjects(); - possibleWebLibs.addAll(javaProjects); - } catch(CoreException e){ - Logger.getLogger().logError(e); - } - IProject[] utilityProjects = J2EEProjectUtilities.getAllProjectsInWorkspaceOfType(J2EEProjectUtilities.UTILITY); - possibleWebLibs.addAll(Arrays.asList(utilityProjects)); - IProject[] ejbProjects = J2EEProjectUtilities.getAllProjectsInWorkspaceOfType(J2EEProjectUtilities.EJB); - possibleWebLibs.addAll(Arrays.asList(ejbProjects)); - - Map pathToComp = new HashMap(); - - //first handle the projects case - for(Iterator iterator = possibleWebLibs.iterator(); iterator.hasNext();){ - IProject possibleWebLib = (IProject)iterator.next(); - if(possibleWebLib.getName().startsWith(".")){ //$NON-NLS-1$ - continue; - } - boolean isExistingWebLib = existingWebLibProjects.contains(possibleWebLib); - classPathWLPSelection.createProjectElement(possibleWebLib, isExistingWebLib); - // build of map of all unique classpath component contributions from dependent projects - if(isExistingWebLib){ - IVirtualComponent component = ComponentCore.createComponent(possibleWebLib); - if(component != null){ - classPathWLPSelection.buildClasspathComponentDependencyMap(component, pathToComp); - } - } - } - //next handle entries for all other web lib refs - //e.g. to jars in other projects, or outside the workspace or relative to a var - for(Iterator iterator = otherExistingWebLibRefs.iterator(); iterator.hasNext();){ - IVirtualReference ref = (IVirtualReference)iterator.next(); - IVirtualComponent referencedComponent = ref.getReferencedComponent(); - // do not add if this is a classpath entry dependency - if (ClasspathDependencyUtil.isClasspathComponentDependency(referencedComponent)) { - continue; - } - try { - String unresolvedURI = ModuleURIUtil.getArchiveName(URI.createURI(ModuleURIUtil.getHandleString(referencedComponent))); - URI archiveURI = URI.createURI(unresolvedURI); - ClasspathElement element = classPathWLPSelection.createArchiveElement(URI.createURI(ModuleURIUtil.getHandleString(referencedComponent)), referencedComponent.getName(), archiveURI.lastSegment()); - classPathWLPSelection.addClasspathElement(element, unresolvedURI); - } catch (UnresolveableURIException e) { - Logger.getLogger(J2EEPlugin.PLUGIN_ID).logError(e); - } - } - - // add ClasspathElements for all dependent project cp dependencies - final Iterator it = pathToComp.values().iterator(); - while (it.hasNext()) { - final IVirtualComponent c = (IVirtualComponent) it.next(); - final URI archiveURI = URI.createURI(ModuleURIUtil.getHandleString(c)); - String unresolvedURI = null; - try { - unresolvedURI = ModuleURIUtil.getArchiveName(archiveURI); - } catch (UnresolveableURIException e) { - Logger.getLogger(J2EEPlugin.PLUGIN_ID).logError(e); - } - if (unresolvedURI != null) { - final ClasspathElement element = classPathWLPSelection.createClasspathArchiveElement(c.getProject(), archiveURI, unresolvedURI); - classPathWLPSelection.addClasspathElement(element, unresolvedURI); - } - } - - // Add elements for raw classpath entries (either already tagged or potentially taggable) - try { - classPathWLPSelection.createClasspathEntryElements(component, WEBLIB, WEBINF_CLASSES); - } catch (CoreException ce) { - Logger.getLogger(J2EEPlugin.PLUGIN_ID).logError(ce); - } - } - - public boolean isWLPModel() { - return isWLPModel; - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/ClasspathModelEvent.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/ClasspathModelEvent.java deleted file mode 100644 index 388409f28..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/ClasspathModelEvent.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common; - - -public class ClasspathModelEvent extends Object { - protected int eventType; - public static final int CLASS_PATH_CHANGED = 1; - public static final int EAR_PROJECT_CHANGED = 2; - public static final int MANIFEST_CHANGED = 3; - public static final int CLASS_PATH_RESET = 4; - public static final int MAIN_CLASS_CHANGED = 5; - public static final int MODEL_SAVED = 6; - public static final int IMPL_VERSION_CHANGED = 7; - - /** - * Constructor for ClasspathModelEvent. - */ - public ClasspathModelEvent(int eventType) { - super(); - this.eventType = eventType; - } - - /** - * Gets the eventType. - * - * @return Returns a int - */ - public int getEventType() { - return eventType; - } - - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/ClasspathModelListener.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/ClasspathModelListener.java deleted file mode 100644 index c3333f392..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/ClasspathModelListener.java +++ /dev/null @@ -1,14 +0,0 @@ -/*************************************************************************************************** - * Copyright (c) 2003, 2004 IBM Corporation and others. All rights reserved. This program and the - * accompanying materials are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: IBM Corporation - initial API and implementation - **************************************************************************************************/ -package org.eclipse.jst.j2ee.internal.common; - - -public interface ClasspathModelListener { - void modelChanged(ClasspathModelEvent evt); -}
\ No newline at end of file diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/CreationConstants.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/CreationConstants.java deleted file mode 100644 index a375bff8f..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/CreationConstants.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common; - -import org.eclipse.jst.common.frameworks.CommonFrameworksPlugin; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPreferences; - -public interface CreationConstants { - - /** - * @deprecated, use the preferences directly - * @since 2.0 - */ - String DEFAULT_WEB_SOURCE_FOLDER = CommonFrameworksPlugin.getDefault().getPluginPreferences().getString(CommonFrameworksPlugin.DEFAULT_SOURCE_FOLDER); - /** - * @deprecated, use the preferences directly - * @since 2.0 - */ - String DEFAULT_EJB_SOURCE_FOLDER = J2EEPlugin.getDefault().getJ2EEPreferences().getString(J2EEPreferences.Keys.EJB_CONTENT_FOLDER); - - /** - * @deprecated, use the preferences directly - * @since 2.0 - */ - String DEFAULT_CONNECTOR_SOURCE_FOLDER = J2EEPlugin.getDefault().getJ2EEPreferences().getString(J2EEPreferences.Keys.JCA_CONTENT_FOLDER); - /** - * @deprecated, use the preferences directly - * @since 2.0 - */ - String DEFAULT_APPCLIENT_SOURCE_FOLDER = J2EEPlugin.getDefault().getJ2EEPreferences().getString(J2EEPreferences.Keys.APP_CLIENT_CONTENT_FOLDER); - String EJB_CLIENT_NAME ="ClientProject";//$NON-NLS-1$ - String CLIENT_JAR_URI="ClientJARURI";//$NON-NLS-1$ -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/FacetedProjectPropertyTester.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/FacetedProjectPropertyTester.java deleted file mode 100644 index 69867cd41..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/FacetedProjectPropertyTester.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common; - -import org.eclipse.core.expressions.PropertyTester; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.wst.common.project.facet.core.FacetedProjectFramework; -import org.eclipse.wst.common.project.facet.core.internal.FacetCorePlugin; - -public final class FacetedProjectPropertyTester extends PropertyTester - -{ -public boolean test( final Object receiver, - final String property, - final Object[] args, - final Object value ) -{ - try - { - if( ! ( receiver instanceof ICompilationUnit ) ) - { - return false; - } - - final IProject pj = ( (ICompilationUnit ) receiver ).getJavaProject().getProject(); - - if( pj == null ) - { - return false; - } - - final String val = (String) value; - final int colon = val.indexOf( ':' ); - - final String fid; - final String vexpr; - - if( colon == -1 || colon == val.length() - 1 ) - { - fid = val; - vexpr = null; - } - else - { - fid = val.substring( 0, colon ); - vexpr = val.substring( colon + 1 ); - } - - return FacetedProjectFramework.hasProjectFacet( pj, fid, vexpr ); - } - catch( CoreException e ) - { - FacetCorePlugin.log( e.getStatus() ); - } - - return false; -} - -} - diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/J2EECommonMessages.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/J2EECommonMessages.java deleted file mode 100644 index 6cb913725..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/J2EECommonMessages.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Dec 3, 2003 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package org.eclipse.jst.j2ee.internal.common; - -import org.eclipse.osgi.util.NLS; - - -/** - * @author DABERG - * - * To change the template for this generated type comment go to Window>Preferences>Java>Code - * Generation>Code and Comments - */ -public class J2EECommonMessages extends NLS { - private static final String BUNDLE_NAME = "j2ee_common";//$NON-NLS-1$ - - private J2EECommonMessages() { - // Do not instantiate - } - - public static String ERR_SECURITY_ROLE_EMPTY; - public static String ERR_SECURITY_ROLE_EXIST; - public static String ERR_JAVA_CLASS_NAME_EMPTY; - public static String ERR_JAVA_CLASS_NAME_EXIST; - public static String ERR_JAVA_CLASS_FILE_NAME_EXIST; - public static String ERR_JAVA_CLASS_FOLDER_NAME_EMPTY; - public static String ERR_JAVA_CLASS_FOLDER_PROJECT_NOT_OPEN; - public static String ERR_JAVA_CLASS_NOT_JAVA_PROJECT; - public static String ERR_JAVA_CLASS_FOLDER_STATIC_PROJECT; - public static String ERR_JAVA_CLASS_FOLDER_NOT_SOURCE; - public static String ERR_JAVA_CLASS_NAME_QUALIFIED; - public static String ERR_JAVA_CLASS_NAME_INVALID; - public static String ERR_JAVA_CLASS_NAME_WARNING; - public static String ERR_JAVA_CLASS_SUPERCLASS_NOT_EXIST; - public static String ERR_JAVA_CLASS_SUPERCLASS_FINAL; - public static String ERR_JAVA_PACAKGE_NAME_INVALID; - public static String ERR_JAVA_PACKAGE_NAME_WARNING; - public static String ERR_BOTH_FINAL_AND_ABSTRACT; - public static String WebServiceClientGenerator_UI_0; - public static String ERR_SECURITY_ROLE_LIST_EMPTY; - - public static String ERR_JAVA_CLASS_FOLDER_NOT_EXIST; - - public static String ERR_EMPTY_MODULE_NAME; - public static String ERR_EMPTY_PROJECT_NAME; - public static String ERR_PROJECT_INACCESSIBLE; - public static String ERR_PROJECT_NAME_EXISTS; - public static String ERR_VERSION_NOT_SUPPORTED; - public static String ERR_NOT_SUPPORTED; - public static String ERR_JAVA_CLASS_FOLDER_NOT_ABSOLUTE; - public static String ERR_NO_MODEL_PROVIDER_FOR_PROJECT; - public static String ERR_NO_MODEL_PROVIDER_FOR_VIRTUAL_COMPONENT; - - public static String J2EE_MODULE_CLASSPATH_CONTAINER_NAME; - - public static String CLASSPATH_ENTRY_DEPENDENCY_PREFIX; - - public static String ERR_TYPE_DIFFERENT_CASE_EXIST; - public static String ERR_TYPE_ALREADY_EXIST; - - static { - NLS.initializeMessages(BUNDLE_NAME, J2EECommonMessages.class); - } - - public static String getResourceString(String key, Object[] args) { - return NLS.bind(key, args); - } -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/J2EEDependencyListener.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/J2EEDependencyListener.java deleted file mode 100644 index 383004e42..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/J2EEDependencyListener.java +++ /dev/null @@ -1,161 +0,0 @@ -package org.eclipse.jst.j2ee.internal.common; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceChangeEvent; -import org.eclipse.core.resources.IResourceChangeListener; -import org.eclipse.core.resources.IResourceDelta; -import org.eclipse.core.resources.IResourceDeltaVisitor; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jst.j2ee.application.internal.operations.IModuleExtensions; -import org.eclipse.jst.j2ee.internal.J2EEConstants; -import org.eclipse.jst.j2ee.internal.common.classpath.J2EEComponentClasspathUpdater; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; -import org.eclipse.jst.j2ee.internal.project.J2EEProjectUtilities; -import org.eclipse.jst.j2ee.project.EarUtilities; -import org.eclipse.wst.common.componentcore.ComponentCore; -import org.eclipse.wst.common.componentcore.internal.builder.IDependencyGraph; -import org.eclipse.wst.common.componentcore.internal.impl.WTPModulesResourceFactory; -import org.eclipse.wst.common.componentcore.resources.IVirtualComponent; -import org.eclipse.wst.common.componentcore.resources.IVirtualFolder; -import org.eclipse.wst.common.componentcore.resources.IVirtualReference; - -public class J2EEDependencyListener implements IResourceChangeListener, IResourceDeltaVisitor { - - public static J2EEDependencyListener INSTANCE = new J2EEDependencyListener(); - - private J2EEDependencyListener() { - } - - private List<IProject> cachedEARModuleDependencies = new ArrayList<IProject>(); - - private void cacheModuleDependencies(IProject earProject) { - if (EarUtilities.isEARProject(earProject)) { - IVirtualReference[] refs = EarUtilities.getComponentReferences(ComponentCore.createComponent(earProject)); - IVirtualComponent comp = null; - for (int j = 0; j < refs.length; j++) { - comp = refs[j].getReferencedComponent(); - if (!comp.isBinary()) { - cachedEARModuleDependencies.add(comp.getProject()); - } - } - } - } - - private void updateModuleDependencies() { - if (!cachedEARModuleDependencies.isEmpty()) { - for (Iterator<IProject> iterator = cachedEARModuleDependencies.iterator(); iterator.hasNext();) { - IDependencyGraph.INSTANCE.update(iterator.next()); - } - cachedEARModuleDependencies.clear(); - } - } - - public void resourceChanged(IResourceChangeEvent event) { - try { - IDependencyGraph.INSTANCE.preUpdate(); - switch (event.getType()) { - case IResourceChangeEvent.PRE_CLOSE: - case IResourceChangeEvent.PRE_DELETE: - IResource resource = event.getResource(); - if (resource.getType() == IResource.PROJECT) { - cacheModuleDependencies((IProject) resource); - } - break; - case IResourceChangeEvent.POST_CHANGE: - event.getDelta().accept(this); - } - } catch (CoreException e) { - J2EEPlugin.logError(e); - } finally { - IDependencyGraph.INSTANCE.postUpdate(); - } - } - - public boolean visit(IResourceDelta delta) throws CoreException { - IResource resource = delta.getResource(); - switch (resource.getType()) { - case IResource.ROOT: - return true; - case IResource.PROJECT: - int kind = delta.getKind(); - if ((IResourceDelta.ADDED & kind) != 0) { - // if an EAR project is added then all dependent modules must be - // updated - if (EarUtilities.isEARProject((IProject) resource)) { - cacheModuleDependencies((IProject) resource); - updateModuleDependencies(); - } - return false; - } else if ((IResourceDelta.REMOVED & kind) != 0) { - updateModuleDependencies(); - return false; - } else if ((IResourceDelta.CHANGED & kind) != 0) { - int flags = delta.getFlags(); - if ((IResourceDelta.OPEN & flags) != 0) { - boolean isOpen = ((IProject) resource).isOpen(); - if (isOpen) { - // if an EAR project is open all dependent modules must - // be updated - cacheModuleDependencies((IProject) resource); - } - // this will also pickup both close and open events - // if the EAR project is closed, the cached dependent - // modules will already - updateModuleDependencies(); - } - return true; - } - return false; - case IResource.FOLDER: - return true; - case IResource.FILE: - String name = resource.getName(); - // MANIFEST.MF must be all caps per spec - if (name.equals(J2EEConstants.MANIFEST_SHORT_NAME)) { - IFile manifestFile = J2EEProjectUtilities.getManifestFile(resource.getProject(), false); - if (null == manifestFile || resource.equals(manifestFile)) { - IDependencyGraph.INSTANCE.update(resource.getProject(), IDependencyGraph.MODIFIED); - } - } else if (name.equals(WTPModulesResourceFactory.WTP_MODULES_SHORT_NAME)) { - if (EarUtilities.isEARProject(resource.getProject())) { - // unfortunately, in this case, the only easy way to update - // is to force the update of all projects - IProject[] allProjects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); - for (IProject sourceProject : allProjects) { - IDependencyGraph.INSTANCE.update(sourceProject, IDependencyGraph.MODIFIED); - } - } - } else if (endsWithIgnoreCase(name, IModuleExtensions.DOT_JAR) || endsWithIgnoreCase(name, IModuleExtensions.DOT_WAR) || endsWithIgnoreCase(name, IModuleExtensions.DOT_RAR)) { - if (EarUtilities.isEARProject(resource.getProject())) { - IVirtualComponent comp = ComponentCore.createComponent(resource.getProject()); - if (isFolder(resource.getParent(), comp.getRootFolder())) { - IVirtualReference[] refs = comp.getReferences(); - for (IVirtualReference ref : refs) { - IDependencyGraph.INSTANCE.update(ref.getReferencedComponent().getProject(), IDependencyGraph.MODIFIED); - } - IDependencyGraph.INSTANCE.update(resource.getProject(), IDependencyGraph.MODIFIED); - } - - } - } - default: - return false; - } - } - - public static boolean endsWithIgnoreCase(String str, String sfx) { - return J2EEComponentClasspathUpdater.endsWithIgnoreCase(str, sfx); - - } - - public static boolean isFolder(IResource resource, IVirtualFolder folder) { - return J2EEComponentClasspathUpdater.isFolder(resource, folder); - } -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/J2EEVersionUtil.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/J2EEVersionUtil.java deleted file mode 100644 index 36dde4c9b..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/J2EEVersionUtil.java +++ /dev/null @@ -1,303 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Mar 21, 2005 - * - * TODO To change the template for this generated file go to - * Window - Preferences - Java - Code Style - Code Templates - */ -package org.eclipse.jst.j2ee.internal.common; - -import org.eclipse.jst.j2ee.internal.J2EEVersionConstants; -import org.eclipse.jst.j2ee.internal.project.J2EEProjectUtilities; -import org.eclipse.wst.common.componentcore.resources.IVirtualComponent; - -/** - * @author nagrawal - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Style - Code Templates - */ -public class J2EEVersionUtil { - - public static String getServletTextVersion(int aVersion) { - switch (aVersion) { - case J2EEVersionConstants.SERVLET_2_2: - return J2EEVersionConstants.VERSION_2_2_TEXT; - - case J2EEVersionConstants.SERVLET_2_3: - return J2EEVersionConstants.VERSION_2_3_TEXT; - - case J2EEVersionConstants.SERVLET_2_4: - return J2EEVersionConstants.VERSION_2_4_TEXT; - - case J2EEVersionConstants.SERVLET_2_5: - return J2EEVersionConstants.VERSION_2_5_TEXT; - } - return ""; //$NON-NLS-1$ - - } - - public static String getEJBTextVersion(int aVersion) { - - switch (aVersion) { - case J2EEVersionConstants.EJB_1_0_ID: - return J2EEVersionConstants.VERSION_1_0_TEXT; - - case J2EEVersionConstants.EJB_1_1_ID: - return J2EEVersionConstants.VERSION_1_1_TEXT; - - case J2EEVersionConstants.EJB_2_0_ID: - return J2EEVersionConstants.VERSION_2_0_TEXT; - - case J2EEVersionConstants.EJB_2_1_ID: - return J2EEVersionConstants.VERSION_2_1_TEXT; - - case J2EEVersionConstants.EJB_3_0_ID: - return J2EEVersionConstants.VERSION_3_0_TEXT; - } - return ""; //$NON-NLS-1$ - } - - public static String getJCATextVersion(int aVersion) { - switch (aVersion) { - case J2EEVersionConstants.JCA_1_0_ID: - return J2EEVersionConstants.VERSION_1_0_TEXT; - - case J2EEVersionConstants.JCA_1_5_ID: - return J2EEVersionConstants.VERSION_1_5_TEXT; - - } - return ""; //$NON-NLS-1$ - } - - public static String getJ2EETextVersion(int aVersion) { - switch (aVersion) { - case J2EEVersionConstants.J2EE_1_2_ID: - return J2EEVersionConstants.VERSION_1_2_TEXT; - - case J2EEVersionConstants.J2EE_1_3_ID: - return J2EEVersionConstants.VERSION_1_3_TEXT; - - case J2EEVersionConstants.J2EE_1_4_ID: - return J2EEVersionConstants.VERSION_1_4_TEXT; - - case J2EEVersionConstants.JEE_5_0_ID: - return J2EEVersionConstants.VERSION_5_0_TEXT; - - } - return "";//$NON-NLS-1$ - } - - public static int convertAppClientVersionStringToJ2EEVersionID(String version) { - if (version.equals(J2EEVersionConstants.VERSION_1_2_TEXT)) - return J2EEVersionConstants.J2EE_1_2_ID; - if (version.equals(J2EEVersionConstants.VERSION_1_3_TEXT)) - return J2EEVersionConstants.J2EE_1_3_ID; - if (version.equals(J2EEVersionConstants.VERSION_1_4_TEXT)) - return J2EEVersionConstants.J2EE_1_4_ID; - if (version.equals(J2EEVersionConstants.VERSION_5_0_TEXT)) - return J2EEVersionConstants.JEE_5_0_ID; - // default - return J2EEVersionConstants.JEE_5_0_ID; - } - - public static int convertEJBVersionStringToJ2EEVersionID(String version) { - if (version.equals(J2EEVersionConstants.VERSION_1_1_TEXT)) - return J2EEVersionConstants.J2EE_1_2_ID; - if (version.equals(J2EEVersionConstants.VERSION_2_0_TEXT)) - return J2EEVersionConstants.J2EE_1_3_ID; - if (version.equals(J2EEVersionConstants.VERSION_2_1_TEXT)) - return J2EEVersionConstants.J2EE_1_4_ID; - if (version.equals(J2EEVersionConstants.VERSION_3_0_TEXT)) - return J2EEVersionConstants.JEE_5_0_ID; - // default - return J2EEVersionConstants.JEE_5_0_ID; - } - - public static int convertWebVersionStringToJ2EEVersionID(String version) { - if (version.equals(J2EEVersionConstants.VERSION_2_2_TEXT)) - return J2EEVersionConstants.J2EE_1_2_ID; - if (version.equals(J2EEVersionConstants.VERSION_2_3_TEXT)) - return J2EEVersionConstants.J2EE_1_3_ID; - if (version.equals(J2EEVersionConstants.VERSION_2_4_TEXT)) - return J2EEVersionConstants.J2EE_1_4_ID; - if (version.equals(J2EEVersionConstants.VERSION_2_5_TEXT)) - return J2EEVersionConstants.JEE_5_0_ID; - // default - return J2EEVersionConstants.J2EE_1_4_ID; - } - - public static int convertConnectorVersionStringToJ2EEVersionID(String version) { - if (version.equals(J2EEVersionConstants.VERSION_1_0_TEXT)) - return J2EEVersionConstants.J2EE_1_3_ID; - if (version.equals(J2EEVersionConstants.VERSION_1_5_TEXT)) - return J2EEVersionConstants.J2EE_1_4_ID; - // default - return J2EEVersionConstants.J2EE_1_4_ID; - } - - public static int convertJ2EEVersionIDToEJBVersionID(int j2eeVersionId) { - switch (j2eeVersionId) { - case J2EEVersionConstants.J2EE_1_2_ID: - return J2EEVersionConstants.EJB_1_1_ID; - case J2EEVersionConstants.J2EE_1_3_ID: - return J2EEVersionConstants.EJB_2_0_ID; - case J2EEVersionConstants.J2EE_1_4_ID: - return J2EEVersionConstants.EJB_2_1_ID; - case J2EEVersionConstants.JEE_5_0_ID: - return J2EEVersionConstants.EJB_3_0_ID; - } - // default - return J2EEVersionConstants.EJB_3_0_ID; - } - - public static int convertJ2EEVersionIDToWebVersionID(int j2eeVersionId) { - switch (j2eeVersionId) { - case J2EEVersionConstants.J2EE_1_2_ID: - return J2EEVersionConstants.WEB_2_2_ID; - case J2EEVersionConstants.J2EE_1_3_ID: - return J2EEVersionConstants.WEB_2_3_ID; - case J2EEVersionConstants.J2EE_1_4_ID: - return J2EEVersionConstants.WEB_2_4_ID; - case J2EEVersionConstants.JEE_5_0_ID: - return J2EEVersionConstants.WEB_2_5_ID; - } - // default - return J2EEVersionConstants.WEB_2_5_ID; - } - - public static int convertJ2EEVersionIDToConnectorVersionID(int j2eeVersionId) { - switch (j2eeVersionId) { - case J2EEVersionConstants.J2EE_1_3_ID: - return J2EEVersionConstants.JCA_1_0_ID; - case J2EEVersionConstants.J2EE_1_4_ID: - return J2EEVersionConstants.JCA_1_5_ID; - } - // default - return J2EEVersionConstants.JCA_1_5_ID; - } - - public static int convertVersionStringToInt(IVirtualComponent comp) { - String version = J2EEProjectUtilities.getJ2EEProjectVersion(comp.getProject()); - if (J2EEProjectUtilities.isDynamicWebProject(comp.getProject())) - return convertWebVersionStringToJ2EEVersionID(version); - if (J2EEProjectUtilities.isEJBProject(comp.getProject())) - return convertEJBVersionStringToJ2EEVersionID(version); - if (J2EEProjectUtilities.isEARProject(comp.getProject())) - return convertVersionStringToInt(version); - if (J2EEProjectUtilities.isJCAProject(comp.getProject())) - return convertConnectorVersionStringToJ2EEVersionID(version); - if (J2EEProjectUtilities.isApplicationClientProject(comp.getProject())) - return convertAppClientVersionStringToJ2EEVersionID(version); - return 0; - } - - public static int convertVersionStringToInt(String version) { - int nVersion = 0; - - if( version.endsWith("")){ //$NON-NLS-1$ - nVersion = 0; - } - - if (version.equals(J2EEVersionConstants.VERSION_1_0_TEXT)) - nVersion = J2EEVersionConstants.VERSION_1_0; - - else if (version.equals(J2EEVersionConstants.VERSION_1_1_TEXT)) - nVersion = J2EEVersionConstants.VERSION_1_1; - - else if (version.equals(J2EEVersionConstants.VERSION_1_2_TEXT)) - nVersion = J2EEVersionConstants.VERSION_1_2; - - else if (version.equals(J2EEVersionConstants.VERSION_1_3_TEXT)) - nVersion = J2EEVersionConstants.VERSION_1_3; - - else if (version.equals(J2EEVersionConstants.VERSION_1_4_TEXT)) - nVersion = J2EEVersionConstants.VERSION_1_4; - - else if (version.equals(J2EEVersionConstants.VERSION_1_5_TEXT)) - nVersion = J2EEVersionConstants.VERSION_1_5; - - else if (version.equals(J2EEVersionConstants.VERSION_2_0_TEXT)) - nVersion = J2EEVersionConstants.VERSION_2_0; - - else if (version.equals(J2EEVersionConstants.VERSION_2_1_TEXT)) - nVersion = J2EEVersionConstants.VERSION_2_1; - - else if (version.equals(J2EEVersionConstants.VERSION_2_2_TEXT)) - nVersion = J2EEVersionConstants.VERSION_2_2; - - else if (version.equals(J2EEVersionConstants.VERSION_2_3_TEXT)) - nVersion = J2EEVersionConstants.VERSION_2_3; - - else if (version.equals(J2EEVersionConstants.VERSION_2_4_TEXT)) - nVersion = J2EEVersionConstants.VERSION_2_4; - - else if (version.equals(J2EEVersionConstants.VERSION_2_5_TEXT)) - nVersion = J2EEVersionConstants.VERSION_2_5; - - else if (version.equals(J2EEVersionConstants.VERSION_5_0_TEXT)) - nVersion = J2EEVersionConstants.VERSION_5_0; - - else if (version.equals(J2EEVersionConstants.VERSION_3_0_TEXT)) - nVersion = J2EEVersionConstants.VERSION_3_0; - - return nVersion; - } - public static String convertVersionIntToString(int version) { - String nVersion = null; - - if (version == J2EEVersionConstants.VERSION_1_0) - nVersion = J2EEVersionConstants.VERSION_1_0_TEXT; - - else if (version == J2EEVersionConstants.VERSION_1_1) - nVersion = J2EEVersionConstants.VERSION_1_1_TEXT; - - else if (version == J2EEVersionConstants.VERSION_1_2) - nVersion = J2EEVersionConstants.VERSION_1_2_TEXT; - - else if (version == J2EEVersionConstants.VERSION_1_3) - nVersion = J2EEVersionConstants.VERSION_1_3_TEXT; - - else if (version == J2EEVersionConstants.VERSION_1_4) - nVersion = J2EEVersionConstants.VERSION_1_4_TEXT; - - else if (version == J2EEVersionConstants.VERSION_1_5) - nVersion = J2EEVersionConstants.VERSION_1_5_TEXT; - - else if (version == J2EEVersionConstants.VERSION_2_0) - nVersion = J2EEVersionConstants.VERSION_2_0_TEXT; - - else if (version == J2EEVersionConstants.VERSION_2_1) - nVersion = J2EEVersionConstants.VERSION_2_1_TEXT; - - else if (version == J2EEVersionConstants.VERSION_2_2) - nVersion = J2EEVersionConstants.VERSION_2_2_TEXT; - - else if (version == J2EEVersionConstants.VERSION_2_3) - nVersion = J2EEVersionConstants.VERSION_2_3_TEXT; - - else if (version == J2EEVersionConstants.VERSION_2_4) - nVersion = J2EEVersionConstants.VERSION_2_4_TEXT; - - else if (version == J2EEVersionConstants.VERSION_2_5) - nVersion = J2EEVersionConstants.VERSION_2_5_TEXT; - - else if (version == J2EEVersionConstants.VERSION_3_0) - nVersion = J2EEVersionConstants.VERSION_3_0_TEXT; - - else if (version == J2EEVersionConstants.VERSION_5_0) - nVersion = J2EEVersionConstants.VERSION_5_0_TEXT; - - return nVersion; - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/UpdateProjectClasspath.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/UpdateProjectClasspath.java deleted file mode 100644 index d0003acf4..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/UpdateProjectClasspath.java +++ /dev/null @@ -1,90 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.jst.j2ee.internal.common; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; -import org.eclipse.jdt.core.IClasspathEntry; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.internal.core.ClasspathEntry; -import org.eclipse.jem.util.logger.proxy.Logger; - - -/** - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Style - Code Templates - */ -public class UpdateProjectClasspath { - - - public UpdateProjectClasspath(String sourceFolder, String componentName, IProject jProject){ - addSrcFolderToProject(sourceFolder, componentName, jProject); - } - - private IClasspathEntry[] getClasspathEntries(String sourceFolder, String componentName, - IProject jProject) { - - ArrayList list = new ArrayList(); - list.add(JavaCore.newSourceEntry(jProject.getFullPath().append(sourceFolder))); - - IClasspathEntry[] classpath = new IClasspathEntry[list.size()]; - - - IPath newOutputPath = null; - for (int i = 0; i < classpath.length; i++) { - classpath[i] = (IClasspathEntry) list.get(i); - newOutputPath = Path.fromOSString(Path.SEPARATOR +jProject.getName() + "/bin/"); - ((ClasspathEntry)classpath[i]).specificOutputLocation = newOutputPath; - } - return classpath; - } - - private void addSrcFolderToProject(String sourceFolder,String componentName, - IProject jProject) { - - IJavaProject javaProject = JavaCore.create( jProject ); - try { - - IClasspathEntry[] oldEntries = javaProject.getRawClasspath(); - List oldEntriesList,classpathList; - IClasspathEntry[] newEntries = getClasspathEntries(sourceFolder, componentName, - jProject); - /** - * Warning clean-up 12/05/2005 - */ - //int oldSize = oldEntries.length; - //int newSize = newEntries.length; - - classpathList = new ArrayList(); - oldEntriesList = Arrays.asList(oldEntries); - classpathList.addAll(oldEntriesList); - for( int j=0; j< newEntries.length; j++){ - if(!oldEntriesList.contains(newEntries[j])) { - classpathList.add(newEntries[j]); - } - } - IClasspathEntry[] classpathEntries = (IClasspathEntry[]) classpathList.toArray(new IClasspathEntry[classpathList.size()]); - javaProject.setRawClasspath(classpathEntries, null); - } - catch (JavaModelException e) { - Logger.getLogger().logError(e); - } - } -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/VirtualArchiveComponentAdapterFactory.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/VirtualArchiveComponentAdapterFactory.java deleted file mode 100644 index a7b6a331e..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/VirtualArchiveComponentAdapterFactory.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common; - -import org.eclipse.core.runtime.IAdapterFactory; -import org.eclipse.core.runtime.IPath; -import org.eclipse.jst.j2ee.internal.project.J2EEProjectUtilities; -import org.eclipse.wst.common.componentcore.internal.resources.VirtualArchiveComponent; - -public class VirtualArchiveComponentAdapterFactory implements IAdapterFactory { - - public Object getAdapter(Object adaptableObject, Class adapterType) { - if (adapterType == VirtualArchiveComponent.ADAPTER_TYPE ) { - VirtualArchiveComponent component = (VirtualArchiveComponent) adaptableObject; - IPath path = J2EEProjectUtilities.getResolvedPathForArchiveComponent(component.getName()); - return path; - } - return null; - } - - - public Class[] getAdapterList() { - return new Class[]{VirtualArchiveComponent.class}; - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/J2EEComponentClasspathContainer.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/J2EEComponentClasspathContainer.java deleted file mode 100644 index 6d1eb26fb..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/J2EEComponentClasspathContainer.java +++ /dev/null @@ -1,434 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.classpath; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; -import org.eclipse.jdt.core.IAccessRule; -import org.eclipse.jdt.core.IClasspathAttribute; -import org.eclipse.jdt.core.IClasspathContainer; -import org.eclipse.jdt.core.IClasspathEntry; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.internal.core.ClasspathEntry; -import org.eclipse.jdt.internal.core.JavaProject; -import org.eclipse.jdt.internal.core.util.Util; -import org.eclipse.jem.util.emf.workbench.ProjectUtilities; -import org.eclipse.jem.util.logger.proxy.Logger; -import org.eclipse.jst.common.jdt.internal.classpath.ClasspathDecorations; -import org.eclipse.jst.common.jdt.internal.classpath.ClasspathDecorationsManager; -import org.eclipse.jst.j2ee.componentcore.J2EEModuleVirtualComponent; -import org.eclipse.jst.j2ee.internal.common.J2EECommonMessages; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; -import org.eclipse.jst.j2ee.internal.project.J2EEProjectUtilities; -import org.eclipse.wst.common.componentcore.ComponentCore; -import org.eclipse.wst.common.componentcore.internal.StructureEdit; -import org.eclipse.wst.common.componentcore.internal.builder.DependencyGraphManager; -import org.eclipse.wst.common.componentcore.internal.resources.VirtualArchiveComponent; -import org.eclipse.wst.common.componentcore.resources.IVirtualComponent; -import org.eclipse.wst.common.componentcore.resources.IVirtualReference; - -/** - * This classpath container is based on the Component references; not the manifest entries. Other - * mechanisms are in place to ensure that the component references are updated when the manifest is - * updated, and also to make sure the manifest is updated when the component references are updated. - * - */ -public class J2EEComponentClasspathContainer implements IClasspathContainer { - - public static final String CONTAINER_ID = "org.eclipse.jst.j2ee.internal.module.container"; //$NON-NLS-1$ - public static final IPath CONTAINER_PATH = new Path(CONTAINER_ID); - - private static IPath WEBLIB = new Path("/WEB-INF/lib"); //$NON-NLS-1$ - - private static ClasspathDecorationsManager decorationsManager = new ClasspathDecorationsManager(J2EEPlugin.PLUGIN_ID); - - public static ClasspathDecorationsManager getDecorationsManager() { - return decorationsManager; - } - - private IPath containerPath; - private IJavaProject javaProject; - private IClasspathEntry[] entries = new IClasspathEntry[0]; - private boolean exportEntries = true; //the default behavior is to always export these dependencies - private static Map keys = new Hashtable(); - private static Map previousSelves = new Hashtable(); - private static int MAX_RETRIES = 10; - private static Map retries = new Hashtable(); - - private class LastUpdate { - private long dotClasspathModificationStamp = -1; - private int refCount = 0; - private boolean[] isBinary = new boolean[refCount]; - private IPath[] paths = new IPath[refCount]; - } - - private LastUpdate lastUpdate = new LastUpdate(); - - public J2EEComponentClasspathContainer(IPath path, IJavaProject javaProject) { - this.containerPath = path; - this.javaProject = javaProject; - } - - private boolean requiresUpdate() { - IVirtualComponent component = ComponentCore.createComponent(javaProject.getProject()); - if (component == null) { - return false; - } - - IFile dotClasspath = javaProject.getProject().getFile(ProjectUtilities.DOT_CLASSPATH); - long dotClasspathModificationStamp = dotClasspath.exists() ? dotClasspath.getModificationStamp() : 0; - if(dotClasspathModificationStamp != lastUpdate.dotClasspathModificationStamp){ - return true; - } - - IVirtualReference[] refs = component instanceof J2EEModuleVirtualComponent ? ((J2EEModuleVirtualComponent)component).getReferences(true, true): component.getReferences(); - IVirtualComponent comp = null; - - // avoid updating the container if references haven't changed - if (refs.length == lastUpdate.refCount) { - for (int i = 0; i < lastUpdate.refCount; i++) { - comp = refs[i].getReferencedComponent(); - if (comp.isBinary() != lastUpdate.isBinary[i]) { - return true; - } else { - IPath path = null; - if (comp.isBinary()) { - VirtualArchiveComponent archiveComp = (VirtualArchiveComponent) comp; - java.io.File diskFile = archiveComp.getUnderlyingDiskFile(); - if (diskFile.exists()) - path = new Path(diskFile.getAbsolutePath()); - else { - IFile iFile = archiveComp.getUnderlyingWorkbenchFile(); - path = iFile.getFullPath(); - } - } else { - path = comp.getProject().getFullPath(); - } - if (!path.equals(lastUpdate.paths[i])) { - return true; - } - } - } - return false; - } - return true; - } - - private void update() { - if(!javaProject.isOpen()){ - try { - if(javaProject.getProject().exists() && javaProject.getProject().hasNature(JavaCore.NATURE_ID)){ - javaProject.open(null); - } else { - return; - } - } catch (JavaModelException e) { - Logger.getLogger().logError(e); - } catch (CoreException e) { - //ignore - return; - } - } - - IVirtualComponent component = ComponentCore.createComponent(javaProject.getProject()); - Object key = keys.get(new Integer(javaProject.getProject().hashCode())); - J2EEComponentClasspathContainer firstPreviousSelf = (J2EEComponentClasspathContainer)previousSelves.get(key); - if (component == null) { - return; - } - - if(!javaProject.getProject().getFile(StructureEdit.MODULE_META_FILE_NAME).exists()){ - Integer retryCount = (Integer)retries.get(key); - if(retryCount == null){ - retryCount = new Integer(1); - } else if(retryCount.intValue() > MAX_RETRIES){ - return; - } else { - retryCount = new Integer(retryCount.intValue() + 1); - } - retries.put(key, retryCount); - J2EEComponentClasspathUpdater.getInstance().queueUpdate(javaProject.getProject()); - return; - } else { - retries.remove(key); - } - - IFile dotClasspath = javaProject.getProject().getFile(ProjectUtilities.DOT_CLASSPATH); - lastUpdate.dotClasspathModificationStamp = dotClasspath.exists() ? dotClasspath.getModificationStamp() : 0; - - IVirtualComponent comp = null; - IVirtualReference ref = null; - - IVirtualReference[] refs = component instanceof J2EEModuleVirtualComponent ? ((J2EEModuleVirtualComponent)component).getReferences(true, true): component.getReferences(); - - List refsList = new ArrayList(); - Set refedComps = new HashSet(); - refedComps.add(component); - for(int i = 0; i<refs.length;i++){ - refsList.add(refs[i]); - refedComps.add(refs[i].getReferencedComponent()); - } - for(int i=0; i< refsList.size(); i++){ - comp = ((IVirtualReference)refsList.get(i)).getReferencedComponent(); - if(comp.isBinary()){ - IVirtualReference [] binaryRefs = comp.getReferences(); - for(int j = 0; j<binaryRefs.length; j++){ - if(!refedComps.contains(binaryRefs[j].getReferencedComponent())){ - refsList.add(binaryRefs[j]); - refedComps.add(binaryRefs[j].getReferencedComponent()); - } - } - } - } - - lastUpdate.refCount = refsList.size(); - lastUpdate.isBinary = new boolean[lastUpdate.refCount]; - lastUpdate.paths = new IPath[lastUpdate.refCount]; - - boolean isWeb = J2EEProjectUtilities.isDynamicWebProject(component.getProject()); - boolean shouldAdd = true; - - List entriesList = new ArrayList(); - - try { - IJavaProject javaProject = JavaCore.create(component.getProject()); - - boolean useJDTToControlExport = J2EEComponentClasspathContainerUtils.getDefaultUseEARLibrariesJDTExport(); - if(useJDTToControlExport){ - //if the default is not enabled, then check whether the container is being exported - try{ - IClasspathEntry [] rawEntries = javaProject.getRawClasspath(); - for(int i=0;i<rawEntries.length; i++){ - IClasspathEntry entry = rawEntries[i]; - if(entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER){ - if(entry.getPath().equals(CONTAINER_PATH)){ - exportEntries = entry.isExported(); - break; - } - } - } - } catch (JavaModelException e) { - Logger.getLogger().logError(e); - } - } - - Collection <IClasspathEntry> existingEntries = new ArrayList<IClasspathEntry>(); - try { - IClasspathContainer container = JavaCore.getClasspathContainer(CONTAINER_PATH, javaProject); - IClasspathEntry[] previousEntries = null; - if(null != container){ - previousEntries = container.getClasspathEntries(); - } - existingEntries.addAll(Arrays.asList(javaProject.getResolvedClasspath(true))); - removeMatchingEntries(previousEntries, existingEntries); - - if(firstPreviousSelf != null){ - removeMatchingEntries(firstPreviousSelf.entries, existingEntries); - } - J2EEComponentClasspathContainer secondPreviousSelf = (J2EEComponentClasspathContainer)previousSelves.get(key); - if(firstPreviousSelf != secondPreviousSelf && secondPreviousSelf != null){ - removeMatchingEntries(secondPreviousSelf.entries, existingEntries); - } - removeMatchingEntries(entries, existingEntries); - } catch (JavaModelException e) { - Logger.getLogger().logError(e); - } - - for (int i = 0; i < refsList.size(); i++) { - ref = (IVirtualReference)refsList.get(i); - comp = ref.getReferencedComponent(); - lastUpdate.isBinary[i] = comp.isBinary(); - shouldAdd = !(isWeb && ref.getRuntimePath().equals(WEBLIB)); - if (!shouldAdd) { - continue; - } - if (comp.isBinary()) { - VirtualArchiveComponent archiveComp = (VirtualArchiveComponent) comp; - if (archiveComp.getArchiveType().equals(VirtualArchiveComponent.CLASSPATHARCHIVETYPE)) { - // do not process components dynamically computed from the Java classpath - continue; - } - java.io.File diskFile = archiveComp.getUnderlyingDiskFile(); - if (diskFile.exists()) { - lastUpdate.paths[i] = new Path(diskFile.getAbsolutePath()); - } else { - IFile iFile = archiveComp.getUnderlyingWorkbenchFile(); - lastUpdate.paths[i] = iFile.getFullPath(); - } - if (!isAlreadyOnClasspath(existingEntries, lastUpdate.paths[i])) { - ClasspathDecorations dec = decorationsManager.getDecorations( getPath().toString(), lastUpdate.paths[i].toString() ); - - IPath srcpath = null; - IPath srcrootpath = null; - IClasspathAttribute[] attrs = {}; - IAccessRule[] access = {}; - - if( dec != null ) { - srcpath = dec.getSourceAttachmentPath(); - srcrootpath = dec.getSourceAttachmentRootPath(); - attrs = dec.getExtraAttributes(); - } - - entriesList.add(JavaCore.newLibraryEntry( lastUpdate.paths[i], srcpath, srcrootpath, access, attrs, exportEntries )); - } - } else { - IProject project = comp.getProject(); - lastUpdate.paths[i] = project.getFullPath(); - if (!isAlreadyOnClasspath(existingEntries, lastUpdate.paths[i])) { - entriesList.add(JavaCore.newProjectEntry(lastUpdate.paths[i], exportEntries)); - } - } - } - } finally { - entries = new IClasspathEntry[entriesList.size()]; - for (int i = 0; i < entries.length; i++) { - entries[i] = (IClasspathEntry) entriesList.get(i); - } - } - previousSelves.put(key, this); - } - - private void removeMatchingEntries(IClasspathEntry [] oldEntries, Collection<IClasspathEntry> existingEntries) { - if(oldEntries != null){ - for(IClasspathEntry oldEntry : oldEntries){ - Iterator <IClasspathEntry> iterator = existingEntries.iterator(); - while(iterator.hasNext()){ - IClasspathEntry existingEntry = iterator.next(); - if(isAlreadyOnClasspath(existingEntry, oldEntry.getPath())){ - iterator.remove(); - break; - } - } - } - } - } - - public static void install(IPath containerPath, IJavaProject javaProject) { - try{ - J2EEComponentClasspathUpdater.getInstance().pauseUpdates(); - Integer hashCode = new Integer(javaProject.getProject().hashCode()); - Object key = keys.get(hashCode); - if(key == null){ - keys.put(hashCode, hashCode); - key = hashCode; - } - final IJavaProject[] projects = new IJavaProject[]{javaProject}; - final J2EEComponentClasspathContainer container = new J2EEComponentClasspathContainer(containerPath, javaProject); - container.update(); - final IClasspathContainer[] conts = new IClasspathContainer[]{container}; - try { - JavaCore.setClasspathContainer(containerPath, projects, conts, null); - previousSelves.put(key, container); - } catch (JavaModelException e) { - Logger.getLogger().log(e); - } - } finally { - J2EEComponentClasspathUpdater.getInstance().resumeUpdates(); - } - } - - public void refresh(boolean force){ - if(force || requiresUpdate()){ - install(containerPath, javaProject); - if (J2EEComponentClasspathUpdater.shouldUpdateDependencyGraph()) - { - // Update dependency graph - DependencyGraphManager.getInstance().forceRefresh(); - // [202820] - J2EEComponentClasspathUpdater.setUpdateDependencyGraph(false); - } - } - } - - public void refresh() { - refresh(false); - } - - private boolean isUpdating = false; - - public IClasspathEntry[] getClasspathEntries() { - if(!isUpdating){ - if(this != J2EEComponentClasspathContainerUtils.getInstalledEARLibrariesContainer(javaProject.getProject())){ - try { - isUpdating = true; - update(); - } finally{ - isUpdating = false; - } - } - } - return entries; - } - - public String getDescription() { - return J2EECommonMessages.J2EE_MODULE_CLASSPATH_CONTAINER_NAME; - } - - public int getKind() { - return K_APPLICATION; - } - - public IPath getPath() { - return containerPath; - } - - /** - * Taken from {@link JavaProject#isOnClasspath(org.eclipse.core.resources.IResource)} - * - * @param classpath - * @param newPath - * @return - */ - private static boolean isAlreadyOnClasspath(Collection<IClasspathEntry> classpath, IPath newPath) { - for (Iterator itr = classpath.iterator(); itr.hasNext();) { - IClasspathEntry entry = (IClasspathEntry) itr.next(); - if(isAlreadyOnClasspath(entry, newPath)){ - return true; - } - } - return false; - } - - /** - * Taken from {@link JavaProject#isOnClasspath(org.eclipse.core.resources.IResource)} - * - * @param classpath - * @param newPath - * @return - */ - private static boolean isAlreadyOnClasspath(IClasspathEntry classpathEntry, IPath newPath){ - IPath entryPath = classpathEntry.getPath(); - if (entryPath.equals(newPath)) { // package fragment roots must match exactly entry - // paths (no exclusion there) - return true; - } - if (entryPath.isPrefixOf(newPath) && !Util.isExcluded(newPath, ((ClasspathEntry) classpathEntry).fullInclusionPatternChars(), ((ClasspathEntry) classpathEntry).fullExclusionPatternChars(), false)) { - return true; - } - return false; - } - -}
\ No newline at end of file diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/J2EEComponentClasspathContainerUtils.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/J2EEComponentClasspathContainerUtils.java deleted file mode 100644 index 93cfe1419..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/J2EEComponentClasspathContainerUtils.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.eclipse.jst.j2ee.internal.common.classpath; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IPath; -import org.eclipse.jdt.core.IClasspathContainer; -import org.eclipse.jdt.core.IClasspathEntry; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jst.common.jdt.internal.classpath.FlexibleProjectContainer; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; - -public class J2EEComponentClasspathContainerUtils { - - public static boolean getDefaultUseEARLibraries() { - return J2EEPlugin.getDefault().getJ2EEPreferences().getUseEARLibraries(); - } - - public static boolean getDefaultUseEARLibrariesJDTExport() { - return J2EEPlugin.getDefault().getJ2EEPreferences().getUseEARLibrariesJDTExport(); - } - - public static boolean getDefaultUseWebAppLibraries() { - return J2EEPlugin.getDefault().getJ2EEPreferences().getUseWebLibaries(); - } - - public static IClasspathContainer getInstalledContainer(IProject project, IPath containerPath) { - IJavaProject jproj = JavaCore.create(project); - IClasspathEntry entry = getInstalledContainerEntry(jproj, containerPath); - IClasspathContainer container = null; - if (entry != null) { - try { - container = JavaCore.getClasspathContainer(containerPath, jproj); - } catch (JavaModelException e) { - J2EEPlugin.getDefault().getLogger().logError(e); - } - } - return container; - } - - public static J2EEComponentClasspathContainer getInstalledEARLibrariesContainer(IProject project) { - IClasspathContainer container = getInstalledContainer(project, J2EEComponentClasspathContainer.CONTAINER_PATH); - J2EEComponentClasspathContainer earLibrariesContainer = null; - if (null != container && container instanceof J2EEComponentClasspathContainer) { - earLibrariesContainer = (J2EEComponentClasspathContainer) container; - } - return earLibrariesContainer; - } - - public static FlexibleProjectContainer getInstalledWebAppLibrariesContainer(IProject project){ - IClasspathContainer container = getInstalledContainer(project, J2EEComponentClasspathUpdater.WEB_APP_LIBS_PATH); - FlexibleProjectContainer webAppLibrariesContainer = null; - if (null != container && container instanceof FlexibleProjectContainer) { - webAppLibrariesContainer = (FlexibleProjectContainer) container; - } - return webAppLibrariesContainer; - } - - public static IClasspathEntry getInstalledContainerEntry(IJavaProject jproj, IPath classpathContainerPath) { - if (jproj.isOpen()) { - try { - IClasspathEntry[] cpes; - cpes = jproj.getRawClasspath(); - for (int j = 0; j < cpes.length; j++) { - final IClasspathEntry cpe = cpes[j]; - if (cpe.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { - if (cpe.getPath().equals(classpathContainerPath)) { - return cpe; // entry found - } - } - } - } catch (JavaModelException e) { - J2EEPlugin.getDefault().getLogger().logError(e); - } - } - // entry not found - return null; - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/J2EEComponentClasspathInitializer.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/J2EEComponentClasspathInitializer.java deleted file mode 100644 index becfb2ef4..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/J2EEComponentClasspathInitializer.java +++ /dev/null @@ -1,65 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.classpath; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.jdt.core.ClasspathContainerInitializer; -import org.eclipse.jdt.core.IClasspathAttribute; -import org.eclipse.jdt.core.IClasspathContainer; -import org.eclipse.jdt.core.IClasspathEntry; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jst.common.jdt.internal.classpath.ClasspathDecorations; -import org.eclipse.jst.common.jdt.internal.classpath.ClasspathDecorationsManager; - -public class J2EEComponentClasspathInitializer extends ClasspathContainerInitializer { - - private static final ClasspathDecorationsManager decorations = J2EEComponentClasspathContainer.getDecorationsManager(); - - public void initialize(IPath containerPath, IJavaProject javaProject) throws CoreException { - J2EEComponentClasspathContainer.install(containerPath, javaProject); - } - - public boolean canUpdateClasspathContainer(final IPath containerPath, final IJavaProject project) { - return true; - } - - public void requestClasspathContainerUpdate(final IPath containerPath, final IJavaProject javaProject, final IClasspathContainer sg) throws CoreException { - final String key = containerPath.toString(); - final IClasspathEntry[] entries = sg.getClasspathEntries(); - - for (int i = 0; i < entries.length; i++) { - final IClasspathEntry entry = entries[i]; - - final IPath srcpath = entry.getSourceAttachmentPath(); - final IPath srcrootpath = entry.getSourceAttachmentRootPath(); - final IClasspathAttribute[] attrs = entry.getExtraAttributes(); - - if (srcpath != null || attrs.length > 0) { - final String eid = entry.getPath().toString(); - final ClasspathDecorations dec = new ClasspathDecorations(); - - dec.setSourceAttachmentPath(srcpath); - dec.setSourceAttachmentRootPath(srcrootpath); - dec.setExtraAttributes(attrs); - - decorations.setDecorations(key, eid, dec); - } - } - - decorations.save(); - - final IClasspathContainer container = JavaCore.getClasspathContainer(containerPath, javaProject); - - ( (J2EEComponentClasspathContainer) container ).refresh( true ); - } -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/J2EEComponentClasspathUpdater.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/J2EEComponentClasspathUpdater.java deleted file mode 100644 index 02ccd314f..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/J2EEComponentClasspathUpdater.java +++ /dev/null @@ -1,543 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.classpath; - -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.eclipse.core.resources.IContainer; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceChangeEvent; -import org.eclipse.core.resources.IResourceChangeListener; -import org.eclipse.core.resources.IResourceDelta; -import org.eclipse.core.resources.IResourceDeltaVisitor; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.ISafeRunnable; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.ListenerList; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.SafeRunner; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.jdt.core.IClasspathContainer; -import org.eclipse.jdt.core.IClasspathEntry; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jem.util.emf.workbench.ProjectUtilities; -import org.eclipse.jst.common.jdt.internal.classpath.FlexibleProjectContainer; -import org.eclipse.jst.j2ee.application.internal.operations.IModuleExtensions; -import org.eclipse.jst.j2ee.componentcore.J2EEModuleVirtualComponent; -import org.eclipse.jst.j2ee.componentcore.util.EARVirtualComponent; -import org.eclipse.jst.j2ee.internal.J2EEConstants; -import org.eclipse.jst.j2ee.internal.componentcore.JavaEEBinaryComponentHelper; -import org.eclipse.jst.j2ee.internal.plugin.IJ2EEModuleConstants; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; -import org.eclipse.jst.j2ee.internal.project.J2EEProjectUtilities; -import org.eclipse.wst.common.componentcore.ComponentCore; -import org.eclipse.wst.common.componentcore.ModuleCoreNature; -import org.eclipse.wst.common.componentcore.internal.StructureEdit; -import org.eclipse.wst.common.componentcore.internal.WorkbenchComponent; -import org.eclipse.wst.common.componentcore.internal.impl.ResourceTreeRootAdapter; -import org.eclipse.wst.common.componentcore.internal.impl.WTPModulesResourceFactory; -import org.eclipse.wst.common.componentcore.resources.IVirtualComponent; -import org.eclipse.wst.common.componentcore.resources.IVirtualFolder; -import org.eclipse.wst.common.componentcore.resources.IVirtualReference; -import org.eclipse.wst.common.internal.emf.utilities.ExtendedEcoreUtil; -import org.eclipse.wst.common.project.facet.core.FacetedProjectFramework; - -public class J2EEComponentClasspathUpdater implements IResourceChangeListener, IResourceDeltaVisitor { - - private static J2EEComponentClasspathUpdater instance = null; - - private static boolean updateDependencyGraph = true; - - private int pauseCount = 0; - - public static IPath WEB_APP_LIBS_PATH = new Path("org.eclipse.jst.j2ee.internal.web.container"); //$NON-NLS-1$ - - public static J2EEComponentClasspathUpdater getInstance() { - if (instance == null) { - init(); - } - return instance; - } - - private static void init() { - if (instance == null) { - instance = new J2EEComponentClasspathUpdater(); - } - } - - /** - * Pauses updates; any caller of this method must ensure through a - * try/finally block that resumeUpdates is subsequently called. - */ - public void pauseUpdates() { - synchronized (this) { - pauseCount++; - } - } - - public void resumeUpdates() { - resumeUpdates(true); - } - - private void resumeUpdates(boolean scheduleJob){ - synchronized (this) { - if (pauseCount > 0) { - pauseCount--; - } - if (pauseCount > 0) { - return; - } - } - if(scheduleJob){ - moduleUpdateJob.schedule(MODULE_UPDATE_DELAY); - } - } - - public void forceUpdate(Collection projects){ - forceUpdate(projects, true); - } - - /** - * Collection of type IProject - * @param projects - */ - public void forceUpdate(Collection projects, boolean runAsJob) { - try { - pauseUpdates(); - Iterator iterator = projects.iterator(); - while(iterator.hasNext()){ - queueUpdate((IProject)iterator.next()); - } - } finally { - forceUpdateOnNextRun = true; - // the following code is in place of the normal call to - // resume updates. This restores the pauseCount and forces - // the job to be scheduled immediately - synchronized (this) { - if (pauseCount > 0) { - pauseCount--; - } - } - if(runAsJob){ - moduleUpdateJob.schedule(0); - } else { - try - { - updateDependencyGraph = false; - moduleUpdateJob.run(new NullProgressMonitor()); - } - finally - { - updateDependencyGraph = true; - } - } - } - } - - private boolean forceUpdateOnNextRun = false; - - public void queueUpdate(IProject project) { - if (J2EEProjectUtilities.isEARProject(project)) { - queueUpdateEAR(project); - } else if (J2EEProjectUtilities.isApplicationClientProject(project) || J2EEProjectUtilities.isEJBProject(project) || J2EEProjectUtilities.isDynamicWebProject(project) - || J2EEProjectUtilities.isJCAProject(project) || J2EEProjectUtilities.isUtilityProject(project)) { - queueUpdateModule(project); - } - } - - public void queueUpdateModule(IProject project) { - moduleUpdateJob.queueModule(project); - synchronized (this) { - if (pauseCount > 0) { - return; - } - } - moduleUpdateJob.schedule(MODULE_UPDATE_DELAY); - } - - public void queueUpdateEAR(IProject earProject) { - moduleUpdateJob.queueEAR(earProject); - synchronized (this) { - if (pauseCount > 0) { - return; - } - } - moduleUpdateJob.schedule(MODULE_UPDATE_DELAY); - } - - public boolean projectsQueued() { - return moduleUpdateJob.projectsQueued() || moduleUpdateJob.getState() != Job.NONE; - } - - private static final int MODULE_UPDATE_DELAY = 30; - public static final String MODULE_UPDATE_JOB_NAME = "EAR Libraries Update Job"; - - private final ModuleUpdateJob moduleUpdateJob = new ModuleUpdateJob(); - - public class ModuleUpdateJob extends Job { - - public boolean belongsTo(Object family) { - if(family == MODULE_UPDATE_JOB_NAME){ - return true; - } - return super.belongsTo(family); - } - - // We use the listener list as a thread safe queue. - private class Queue extends ListenerList { - public synchronized Object[] getListeners() { - Object[] data = super.getListeners(); - clear(); - return data; - } - }; - - private Queue moduleQueue = new Queue(); - - private Queue earQueue = new Queue(); - - //a private queue for adding modules queued by the EAR - private Queue earAddedModuleQueue = new Queue(); - - public ModuleUpdateJob() { - super(MODULE_UPDATE_JOB_NAME); - setRule(ResourcesPlugin.getWorkspace().getRoot()); - setSystem(true); - } - - public void queueEAR(IProject ear) { - earQueue.add(ear); - } - - public void queueModule(IProject project) { - moduleQueue.add(project); - } - - public boolean projectsQueued() { - return !earQueue.isEmpty() || !moduleQueue.isEmpty(); - } - - /** - * Add referenced EARs from the queued modules into the EARs queue - */ - private void queueReferencingEars(Object[] projects) { - for (int p = 0; p < projects.length; p++) { - IProject project = (IProject) projects[p]; - if (!isKnown(project)) { - IProject[] earProjects = J2EEProjectUtilities.getReferencingEARProjects(project); - for (int i = 0; i < earProjects.length; i++) { - queueEAR(earProjects[i]); - } - } - } - } - - private void processEars() { - Object[] earProjects = earQueue.getListeners(); - for (int i = 0; i < earProjects.length; i++) { - IProject earProject = (IProject) earProjects[i]; - if (J2EEProjectUtilities.isEARProject(earProject)) - { - IVirtualComponent earComponent = ComponentCore.createComponent(earProject); - IVirtualReference[] refs = J2EEProjectUtilities.getComponentReferences(earComponent); - IVirtualComponent comp = null; - for (int j = 0; j < refs.length; j++) { - comp = refs[j].getReferencedComponent(); - if (!comp.isBinary()) { - earAddedModuleQueue.add(comp.getProject()); - } - } - if(null != earComponent){ - JavaEEBinaryComponentHelper.clearDisconnectedArchivesInEAR(earComponent); - } - } - } - } - - private void processModules(Object[] projects) { - for (int i = 0; i < projects.length; i++) { - IProject project = (IProject) projects[i]; - // this block is for Web app Libraries - if (J2EEProjectUtilities.isDynamicWebProject(project)) { - IClasspathContainer webAppLibrariesContainer = J2EEComponentClasspathContainerUtils.getInstalledWebAppLibrariesContainer(project); - // If the container is present, refresh it - if (webAppLibrariesContainer != null) { - ((FlexibleProjectContainer) webAppLibrariesContainer).refresh(); - } - } - - // ******************** The following is for EAR Libraries - IClasspathContainer earLibrariesContainer = J2EEComponentClasspathContainerUtils.getInstalledEARLibrariesContainer(project); - // If the container is present, refresh it - if (earLibrariesContainer != null) { - ((J2EEComponentClasspathContainer) earLibrariesContainer).refresh(forceUpdateOnNextRun); - } - } - // [202820] - updateDependencyGraph = true; - } - - protected IStatus run(IProgressMonitor monitor) { - - SafeRunner.run(new ISafeRunnable() { - public void handleException(Throwable e) { - J2EEPlugin.getDefault().getLogger().logError(e); - } - - public void run() throws Exception { - try { - Object[] moduleProjects = moduleQueue.getListeners(); - queueReferencingEars(moduleProjects); - processEars(); - Object [] earQueuedModuleProjects = earAddedModuleQueue.getListeners(); - Set modulesSet = new HashSet(); - modulesSet.addAll(Arrays.asList(moduleProjects)); - modulesSet.addAll(Arrays.asList(earQueuedModuleProjects)); - Object [] modulesArray = modulesSet.toArray(); - processModules(modulesArray); - } finally { - forceUpdateOnNextRun = false; - } - - } - }); - - return Status.OK_STATUS; - } - }; - - public IClasspathContainer getWebAppLibrariesContainer(IProject webProject, boolean create) { - IJavaProject jproj = JavaCore.create(webProject); - IClasspathContainer container = null; - IClasspathEntry entry = create ? null : getExistingContainer(jproj, WEB_APP_LIBS_PATH); - if (entry != null || create) { - try { - container = JavaCore.getClasspathContainer(WEB_APP_LIBS_PATH, jproj); - } catch (JavaModelException e) { - J2EEPlugin.getDefault().getLogger().logError(e); - } - } - return container; - } - - /** - * Returns the existing classpath container if it is already on the classpath. This will not - * create a new container. - * - * @param jproj - * @param classpathContainerID - * @return - */ - public IClasspathEntry getExistingContainer(IJavaProject jproj, IPath classpathContainerPath) { - return J2EEComponentClasspathContainerUtils.getInstalledContainerEntry(jproj, classpathContainerPath); - } - - private Set knownProjects = new HashSet(); - - private boolean isKnown(IProject project){ - return !knownProjects.add(project.getName()); - } - - private void forgetProject(IProject project){ - knownProjects.remove(project.getName()); - } - - public void resourceChanged(IResourceChangeEvent event) { - boolean scheduleJob = false; - try { - pauseUpdates(); - switch (event.getType()){ - case IResourceChangeEvent.PRE_CLOSE: - case IResourceChangeEvent.PRE_DELETE: - IResource resource = event.getResource(); - if(resource.getType() == IResource.PROJECT){ - if(ModuleCoreNature.isFlexibleProject((IProject) resource)){ - if(J2EEProjectUtilities.isEARProject((IProject)resource)){ - IProject earProject = (IProject) resource; - - IVirtualReference[] refs = J2EEProjectUtilities.getComponentReferences(ComponentCore.createComponent(earProject)); - IVirtualComponent comp = null; - for (int j = 0; j < refs.length; j++) { - comp = refs[j].getReferencedComponent(); - if (!comp.isBinary()) { - queueUpdateModule(comp.getProject()); - } - } - - } else { - IProject[] earProjects = J2EEProjectUtilities.getReferencingEARProjects((IProject)resource); - for(int i=0; i<earProjects.length; i++){ - queueUpdateEAR(earProjects[i]); - } - } - forgetProject((IProject)resource); - } - JavaEEBinaryComponentHelper.clearAllArchivesInProject((IProject)resource); - } - break; - case IResourceChangeEvent.POST_CHANGE: - scheduleJob = true; - event.getDelta().accept(this); - IResourceDelta[] d = event.getDelta().getAffectedChildren(); - findNode(d); - - break; - } - } catch (CoreException e) { - J2EEPlugin.getDefault().getLogger().logError(e); - } - finally { - resumeUpdates(scheduleJob); - } - } - - - public static void clearResourceTreeRootCache(WorkbenchComponent aModule) { - - ResourceTreeRootAdapter resourceTreeAdapter = (ResourceTreeRootAdapter) ExtendedEcoreUtil - .getAdapter(aModule, aModule.eAdapters(), - ResourceTreeRootAdapter.DEPLOY_ADAPTER_TYPE); - if(null != resourceTreeAdapter) { - resourceTreeAdapter.setResourceTreeRoot(null); - } - resourceTreeAdapter = (ResourceTreeRootAdapter) ExtendedEcoreUtil - .getAdapter(aModule, aModule.eAdapters(), - ResourceTreeRootAdapter.SOURCE_ADAPTER_TYPE); - if(null != resourceTreeAdapter){ - resourceTreeAdapter.setResourceTreeRoot(null); - } - } - - - /* - * Needs to notice changes to MANIFEST.MF in any J2EE projects, changes to - * .component in any J2EE Projects, and any archive changes in EAR projects - */ - - public boolean findNode(IResourceDelta[] delta) { - - for (int i = 0; i < delta.length; i++) { - if (delta[i].toString().indexOf(IJ2EEModuleConstants.COMPONENT_FILE_NAME) != -1) { - StructureEdit core = StructureEdit - .getStructureEditForRead(delta[i].getResource() - .getProject()); - if(null != core){ - WorkbenchComponent component = core.getComponent(); - if(component != null){ - clearResourceTreeRootCache(component); - } - } - } else { - findNode(delta[i].getAffectedChildren()); - } - } - - return true; - } - - public boolean visit(IResourceDelta delta) { - IResource resource = delta.getResource(); - switch (resource.getType()) { - case IResource.ROOT: - return true; - case IResource.PROJECT: - return ModuleCoreNature.isFlexibleProject((IProject) resource); - case IResource.FOLDER: { - if (resource.getName().equals(IJ2EEModuleConstants.DOT_SETTINGS)) { - return true; - } - IVirtualComponent comp = ComponentCore.createComponent(resource.getProject()); - - if (comp instanceof J2EEModuleVirtualComponent || comp instanceof EARVirtualComponent) { - IVirtualFolder rootFolder = comp.getRootFolder(); - if (comp instanceof EARVirtualComponent) { - return isRootAncester(resource, rootFolder); - } else { // J2EEModuleVirtualComponent - return isRootAncester(resource, rootFolder) || isFolder(resource, rootFolder.getFolder(J2EEConstants.META_INF)); - } - } - return false; - } - case IResource.FILE: { - String name = resource.getName(); - if (name.equals(WTPModulesResourceFactory.WTP_MODULES_SHORT_NAME) || name.equals(ProjectUtilities.DOT_CLASSPATH)) { - queueUpdate(resource.getProject()); - } else if (name.equals(J2EEConstants.MANIFEST_SHORT_NAME)) { // MANIFEST.MF must be all caps per spec - IFile manifestFile = J2EEProjectUtilities.getManifestFile(resource.getProject(), false); - if (null == manifestFile || resource.equals(manifestFile)) { - queueUpdateModule(resource.getProject()); - } - } else if (endsWithIgnoreCase(name, IModuleExtensions.DOT_JAR)) { - try { - if (FacetedProjectFramework.hasProjectFacet(resource.getProject(), J2EEProjectUtilities.ENTERPRISE_APPLICATION)) { - IVirtualComponent comp = ComponentCore.createComponent(resource.getProject()); - if(isFolder(resource.getParent(), comp.getRootFolder())){ - queueUpdateEAR(resource.getProject()); - } - } - } catch (CoreException e) { - J2EEPlugin.getDefault().getLogger().logError(e); - } - } - } - default: - return false; - } - } - - public static boolean endsWithIgnoreCase(String str, String sfx) { - return str.regionMatches(true, str.length() - sfx.length(), sfx, 0, sfx.length()); - } - - public static boolean isFolder(IResource resource, IVirtualFolder folder) { - IContainer[] realFolders = folder.getUnderlyingFolders(); - for (int i = 0; i < realFolders.length; i++) { - if (realFolders[i].equals(resource)) { - return true; - } - } - return false; - } - - public static boolean isRootAncester(IResource resource, IVirtualFolder rootFolder) { - IContainer[] realRoots = rootFolder.getUnderlyingFolders(); - IPath currentResourcePath = resource.getFullPath(); - for (int i = 0; i < realRoots.length; i++) { - if (currentResourcePath.isPrefixOf(realRoots[i].getFullPath())) - return true; - } - return false; - } - - public static boolean shouldUpdateDependencyGraph() - { - return updateDependencyGraph; - } - - // [202820] - public static void setUpdateDependencyGraph(boolean value) - { - updateDependencyGraph = value; - } -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/WtpUserLibraryProviderInstallOperation.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/WtpUserLibraryProviderInstallOperation.java deleted file mode 100644 index 325d89225..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/WtpUserLibraryProviderInstallOperation.java +++ /dev/null @@ -1,66 +0,0 @@ -/****************************************************************************** - * Copyright (c) 2008 Oracle - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Konstantin Komissarchik - initial implementation and ongoing maintenance - ******************************************************************************/ - -package org.eclipse.jst.j2ee.internal.common.classpath; - -import org.eclipse.jdt.core.IClasspathAttribute; -import org.eclipse.jdt.core.IClasspathEntry; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jst.common.project.facet.core.libprov.user.UserLibraryProviderInstallOperation; -import org.eclipse.jst.common.project.facet.core.libprov.user.UserLibraryProviderInstallOperationConfig; -import org.eclipse.jst.j2ee.classpathdep.ClasspathDependencyUtil; -import org.eclipse.jst.j2ee.classpathdep.IClasspathDependencyConstants; -import org.eclipse.jst.j2ee.project.facet.IJ2EEFacetConstants; -import org.eclipse.wst.common.project.facet.core.IFacetedProjectBase; -import org.eclipse.wst.common.project.facet.core.IProjectFacet; -import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager; - -/** - * @author <a href="mailto:konstantin.komissarchik@oracle.com">Konstantin Komissarchik</a> - */ - -public class WtpUserLibraryProviderInstallOperation - - extends UserLibraryProviderInstallOperation - -{ - private static final IProjectFacet WEB_FACET - = ProjectFacetsManager.getProjectFacet( IJ2EEFacetConstants.DYNAMIC_WEB ); - - @Override - protected IClasspathEntry createClasspathEntry( final UserLibraryProviderInstallOperationConfig config, - final String libraryName ) - { - final WtpUserLibraryProviderInstallOperationConfig cfg - = (WtpUserLibraryProviderInstallOperationConfig) config; - - final IFacetedProjectBase fproj = cfg.getFacetedProject(); - final boolean isWebProject = fproj.hasProjectFacet( WEB_FACET ); - - final IClasspathAttribute attr; - - if( cfg.isIncludeWithApplicationEnabled() ) - { - attr = JavaCore.newClasspathAttribute( IClasspathDependencyConstants.CLASSPATH_COMPONENT_DEPENDENCY, - ClasspathDependencyUtil.getDefaultRuntimePath( isWebProject ).toString() ); - } - else - { - attr = JavaCore.newClasspathAttribute( IClasspathDependencyConstants.CLASSPATH_COMPONENT_NON_DEPENDENCY, "" ); - } - - IClasspathEntry cpe = super.createClasspathEntry( config, libraryName ); - cpe = JavaCore.newContainerEntry( cpe.getPath(), null, new IClasspathAttribute[]{ attr }, false ); - - return cpe; - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/WtpUserLibraryProviderInstallOperationConfig.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/WtpUserLibraryProviderInstallOperationConfig.java deleted file mode 100644 index 88281010a..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/classpath/WtpUserLibraryProviderInstallOperationConfig.java +++ /dev/null @@ -1,121 +0,0 @@ -/****************************************************************************** - * Copyright (c) 2008 Oracle - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Konstantin Komissarchik - initial implementation and ongoing maintenance - ******************************************************************************/ - -package org.eclipse.jst.j2ee.internal.common.classpath; - -import java.util.List; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.jdt.core.IClasspathAttribute; -import org.eclipse.jdt.core.IClasspathEntry; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jst.common.project.facet.core.internal.ClasspathUtil; -import org.eclipse.jst.common.project.facet.core.libprov.ILibraryProvider; -import org.eclipse.jst.common.project.facet.core.libprov.LibraryProviderFramework; -import org.eclipse.jst.common.project.facet.core.libprov.user.UserLibraryProviderInstallOperationConfig; -import org.eclipse.jst.j2ee.classpathdep.IClasspathDependencyConstants; -import org.eclipse.wst.common.project.facet.core.IFacetedProjectBase; -import org.eclipse.wst.common.project.facet.core.IProjectFacet; -import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion; - -/** - * @author <a href="mailto:konstantin.komissarchik@oracle.com">Konstantin Komissarchik</a> - */ - -public class WtpUserLibraryProviderInstallOperationConfig - - extends UserLibraryProviderInstallOperationConfig - -{ - private static final String CLASS_NAME - = WtpUserLibraryProviderInstallOperationConfig.class.getName(); - - public static final String PROP_INCLUDE_WITH_APPLICATION_ENABLED - = CLASS_NAME + ".INCLUDE_WITH_APPLICATION_ENABLED"; //$NON-NLS-1$ - - private boolean includeWithApplication = true; - - public boolean isIncludeWithApplicationEnabled() - { - return this.includeWithApplication; - } - - public void setIncludeWithApplicationEnabled( final boolean includeWithApplication ) - { - final boolean oldValue = this.includeWithApplication; - this.includeWithApplication = includeWithApplication; - notifyListeners( PROP_INCLUDE_WITH_APPLICATION_ENABLED, oldValue, this.includeWithApplication ); - } - - @Override - public synchronized void init( final IFacetedProjectBase fproj, - final IProjectFacetVersion fv, - final ILibraryProvider provider ) - { - super.init( fproj, fv, provider ); - - this.includeWithApplication = true; - - final IProject project = fproj.getProject(); - - if( project != null ) - { - final IProjectFacet f = fv.getProjectFacet(); - - final ILibraryProvider currentProvider - = LibraryProviderFramework.getCurrentProvider( project, f ); - - if( currentProvider == provider ) - { - final List<IClasspathEntry> entries; - - try - { - entries = ClasspathUtil.getClasspathEntries( project, f ); - } - catch( CoreException e ) - { - throw new RuntimeException( e ); - } - - this.includeWithApplication = getIncludeWithApplicationSetting( entries ); - } - } - } - - private static boolean getIncludeWithApplicationSetting( final List<IClasspathEntry> entries ) - { - for( IClasspathEntry cpe : entries ) - { - if( cpe.getEntryKind() == IClasspathEntry.CPE_CONTAINER ) - { - final IPath path = cpe.getPath(); - - if( path.segmentCount() >= 2 && path.segment( 0 ).equals( JavaCore.USER_LIBRARY_CONTAINER_ID ) ) - { - for( IClasspathAttribute attr : cpe.getExtraAttributes() ) - { - if( attr.getName().equals( IClasspathDependencyConstants.CLASSPATH_COMPONENT_NON_DEPENDENCY ) ) - { - return false; - } - } - } - } - } - - return true; - } - - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/AddJavaEEArtifactOperation.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/AddJavaEEArtifactOperation.java deleted file mode 100644 index 29ced257b..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/AddJavaEEArtifactOperation.java +++ /dev/null @@ -1,113 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 SAP AG and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Kaloyan Raev, kaloyan.raev@sap.com - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.operations; - -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.CLASS_NAME; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.JAVA_PACKAGE; -import static org.eclipse.wst.common.componentcore.internal.operation.IArtifactEditOperationDataModelProperties.PROJECT_NAME; - -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Status; -import org.eclipse.jem.util.emf.workbench.ProjectUtilities; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; -import org.eclipse.jst.j2ee.model.IModelProvider; -import org.eclipse.jst.j2ee.model.ModelProviderManager; -import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelOperation; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; - -public abstract class AddJavaEEArtifactOperation extends AbstractDataModelOperation { - - protected IModelProvider provider; - - public AddJavaEEArtifactOperation(IDataModel dataModel) { - super(dataModel); - provider = ModelProviderManager.getModelProvider(getTargetProject()); - } - - @Override - public IStatus execute(final IProgressMonitor monitor, final IAdaptable info) throws ExecutionException { - Runnable runnable = null; - if (provider.validateEdit(null, null).isOK()) { - runnable = new Runnable(){ - public void run() { - try { - doExecute(monitor, info); - } catch (ExecutionException e) { - J2EEPlugin.logError(e); - } - } - }; - provider.modify(runnable, null); - } - //return doExecute(monitor, info); - return Status.CANCEL_STATUS; - } - - public IStatus doExecute(IProgressMonitor monitor, IAdaptable info) - throws ExecutionException { - // create the java class - createClass(); - return OK_STATUS; - } - - protected String createClass() { - // Create bean java class file using the NewBeanClassOperation. - NewJavaEEArtifactClassOperation op = getNewClassOperation(); - try { - IStatus status = op.execute(new NullProgressMonitor(), null); - if (!status.isOK()) { - J2EEPlugin.log(status); - } - } catch (Exception e) { - J2EEPlugin.logError(e); - } - // Return the qualified class name of the newly created java class for - // the bean - return getQualifiedClassName(); - } - - protected abstract NewJavaEEArtifactClassOperation getNewClassOperation(); - - public IProject getTargetProject() { - String projectName = model.getStringProperty(PROJECT_NAME); - return ProjectUtilities.getProject(projectName); - } - - /** - * This method will return the qualified java class name as specified by the - * class name and package name properties in the data model. This method - * should not return null. - * - * @see #CLASS_NAME - * @see #JAVA_PACKAGE - * - * @return String qualified java class name - */ - public final String getQualifiedClassName() { - // Use the java package name and unqualified class name to create a - // qualified java class name - String packageName = model.getStringProperty(JAVA_PACKAGE); - String className = model.getStringProperty(CLASS_NAME); - - // Ensure the class is not in the default package before adding package - // name to qualified name - if (packageName != null && packageName.trim().length() > 0) - return packageName + "." + className; //$NON-NLS-1$ - - return className; - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/BinaryConstructor.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/BinaryConstructor.java deleted file mode 100644 index 27edc78f5..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/BinaryConstructor.java +++ /dev/null @@ -1,135 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 SAP AG and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Kaloyan Raev, kaloyan.raev@sap.com - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.operations; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.jdt.core.Flags; -import org.eclipse.jdt.core.IMethod; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.Signature; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; - -public class BinaryConstructor implements Constructor { - - private IMethod method; - - public BinaryConstructor(IMethod method) { - this.method = method; - } - - /** - * @see Constructor#isParameterless() - */ - public boolean isParameterless() { - return method.getNumberOfParameters() == 0; - } - - /** - * @see Constructor#isPublic() - */ - public boolean isPublic() { - int flags; - try { - flags = method.getFlags(); - } catch (JavaModelException e) { - J2EEPlugin.logError(e); - flags = 0; - } - return Flags.isPublic(flags); - } - - /** - * @see Constructor#isProtected() - */ - public boolean isProtected() { - int flags; - try { - flags = method.getFlags(); - } catch (JavaModelException e) { - J2EEPlugin.logError(e); - flags = 0; - } - return Flags.isProtected(flags); - } - - /** - * @see Constructor#getParamsForCall() - */ - public String getParamsForCall() { - return this.getParams(false, true); - } - - /** - * @see Constructor#getParamsForDeclaration() - */ - public String getParamsForDeclaration() { - return this.getParams(true, true); - } - - /** - * @see Constructor#getParamsForJavadoc()() - */ - public String getParamsForJavadoc() { - return this.getParams(true, false); - } - - /** - * @see Constructor#getNonPrimitiveParameterTypes() - */ - public List<String> getNonPrimitiveParameterTypes() { - List<String> result = new ArrayList<String>(); - - String[] parameterTypes = method.getParameterTypes(); - for (String parameterType : parameterTypes) { - if (Signature.getTypeSignatureKind(parameterType) != Signature.BASE_TYPE_SIGNATURE) { - result.add(Signature.toString(parameterType)); - } - } - - return result; - } - - private String getParams(boolean types, boolean names) { - StringBuilder result = new StringBuilder(); - - String[] parameterTypes = method.getParameterTypes(); - String[] parameterNames; - try { - parameterNames = method.getParameterNames(); - } catch (JavaModelException e) { - J2EEPlugin.logError(e); - - parameterNames = new String[parameterTypes.length]; - for (int i = 0; i < parameterNames.length; i++) { - parameterNames[i] = "arg" + i; - } - } - - for (int i = 0; i < parameterTypes.length; i++) { - if (types) - result.append(Signature.getSignatureSimpleName(parameterTypes[i])); - - if (types && names) - result.append(" "); //$NON-NLS-1$ - - if (names) - result.append(parameterNames[i]); - - if (i < parameterNames.length - 1) - result.append(", "); //$NON-NLS-1$ - } - - return result.toString(); - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/BinaryMethod.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/BinaryMethod.java deleted file mode 100644 index 026130bfd..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/BinaryMethod.java +++ /dev/null @@ -1,251 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 SAP AG and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Kaloyan Raev, kaloyan.raev@sap.com - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.operations; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.eclipse.jdt.core.IMethod; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.Signature; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; - -public class BinaryMethod implements Method { - - private IMethod method; - - public BinaryMethod(IMethod method) { - this.method = method; - } - - /** - * @see Method#getSignature() - */ - public String getSignature() { - try { - return method.getSignature(); - } catch (JavaModelException e) { - throw new RuntimeException(e); - } - } - - /** - * @see Method#getName() - */ - public String getName() { - return method.getElementName(); - } - - /** - * @see Method#getContainingJavaClass() - */ - public String getContainingJavaClass() { - return method.getDeclaringType().getElementName(); - } - - /** - * @see Method#getReturnType() - */ - public String getReturnType() { - try { - return Signature.getSignatureSimpleName(method.getReturnType()); - } catch (JavaModelException e) { - throw new RuntimeException(e); - } - } - - /** - * @see Method#getDefaultReturnValue() - */ - public String getDefaultReturnValue() { - try { - String signature = method.getReturnType(); - int kind = Signature.getTypeSignatureKind(signature); - if (kind == Signature.BASE_TYPE_SIGNATURE) { - if (Signature.SIG_VOID.equals(signature)) { - return null; - } else if (Signature.SIG_BOOLEAN.equals(signature)) { - return "false"; - } else { - return "0"; - } - } else { - return "null"; - } - } catch (JavaModelException e) { - throw new RuntimeException(e); - } - } - - /** - * @see Method#getReturnTypeImports() - */ - public Collection<String> getReturnTypeImports() { - try { - List<String> result = new ArrayList<String>(); - - String signature = method.getReturnType(); - getTypeImports(signature, result); - - return result; - } catch (JavaModelException e) { - throw new RuntimeException(e); - } - } - - /** - * @see Method#getParamsForCall() - */ - public String getParamsForCall() { - return this.getParams(false, true); - } - - /** - * @see Method#getParamsForDeclaration() - */ - public String getParamsForDeclaration() { - return this.getParams(true, true); - } - - /** - * @see Method#getParamsForJavadoc()() - */ - public String getParamsForJavadoc() { - return this.getParams(true, false); - } - - /** - * @see Method#getParameterImports() - */ - public Collection<String> getParameterImports() { - List<String> result = new ArrayList<String>(); - - String[] parameterTypes = method.getParameterTypes(); - for (String parameterType : parameterTypes) { - getTypeImports(parameterType, result); - } - - return result; - } - - /** - * @see Object#equals(Object) - */ - public boolean equals(Object o) { - Method obj = (Method) o; - return this.getName().equals(obj.getName()) && - this.getSignature().equals(obj.getSignature()); - } - - /** - * @see Object#hashCode() - */ - public int hashCode() { - return getName().hashCode() * getSignature().hashCode(); - } - - private String getParams(boolean types, boolean names) { - StringBuilder result = new StringBuilder(); - - String[] parameterTypes = method.getParameterTypes(); - String[] parameterNames; - try { - parameterNames = method.getParameterNames(); - } catch (JavaModelException e) { - J2EEPlugin.logError(e); - - parameterNames = new String[parameterTypes.length]; - for (int i = 0; i < parameterNames.length; i++) { - parameterNames[i] = "arg" + i; - } - } - - for (int i = 0; i < parameterTypes.length; i++) { - if (types) - result.append(Signature.getSignatureSimpleName(parameterTypes[i])); - - if (types && names) - result.append(" "); //$NON-NLS-1$ - - if (names) - result.append(parameterNames[i]); - - if (i < parameterNames.length - 1) - result.append(", "); //$NON-NLS-1$ - } - - return result.toString(); - } - - private void getTypeImports(String type, List<String> result) { - int kind = Signature.getTypeSignatureKind(type); - - switch (kind) { - case Signature.ARRAY_TYPE_SIGNATURE: - getArrayTypeImports(type, result); - break; - - case Signature.BASE_TYPE_SIGNATURE: - getBaseTypeImports(type, result); - break; - - case Signature.CAPTURE_TYPE_SIGNATURE: - getCaptureTypeImports(type, result); - break; - - case Signature.CLASS_TYPE_SIGNATURE: - getClassTypeImports(type, result); - break; - - case Signature.TYPE_VARIABLE_SIGNATURE: - getTypeVarialbleImports(type, result); - break; - - case Signature.WILDCARD_TYPE_SIGNATURE: - getWildcardTypeImports(type, result); - break; - - default: - throw new IllegalStateException("invalid type signature kind: " + kind); - - } - } - - private void getArrayTypeImports(String type, List<String> result) { - String elementType = Signature.getElementType(type); - getTypeImports(elementType, result); - } - - private void getBaseTypeImports(String type, List<String> result) { - // do nothing - no imports required for primitive types - } - - private void getCaptureTypeImports(String type, List<String> result) { - // TODO Auto-generated method stub - - } - - private void getClassTypeImports(String type, List<String> result) { - result.add(Signature.toString(type)); - } - - private void getTypeVarialbleImports(String type, List<String> result) { - // TODO Auto-generated method stub - - } - - private void getWildcardTypeImports(String type, List<String> result) { - // TODO Auto-generated method stub - - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/Constructor.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/Constructor.java deleted file mode 100644 index 91689df58..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/Constructor.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 SAP AG and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Kaloyan Raev, kaloyan.raev@sap.com - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.operations; - -import java.util.List; - -/** - * Represents a constructor declaration in a Java class. - * - * <p> - * This interface defines methods that are used by the JETEmitter template - * model. - * </p> - * - * @author kraev - */ -public interface Constructor { - - /** - * Determines whether the constructor has any parameters - * - * @return <code>true</code> if the constructor has no parameters, - * <code>false</code> - otherwise. - */ - public boolean isParameterless(); - - /** - * Determines whether the constructor has a <code>public</code> modifier. - * - * @return <code>true</code> if the constructor is public, - * <code>false</code> - otherwise. - */ - public boolean isPublic(); - - /** - * Determines whether the constructor has a <code>protected</code> - * modifier. - * - * @return <code>true</code> if the constructor is protected, - * <code>false</code> - otherwise. - */ - public boolean isProtected(); - - /** - * Returns the list of constructor's parameters in a format that is - * convenient for usage in a Javadoc <b>@see</b> annotation. - * - * @return a String representation of the parameters list. - */ - public String getParamsForJavadoc(); - - /** - * Returns the list of constructor's parameters in a format that is - * convenient for usage in a method declaration. - * - * @return a String representation of the parameters list. - */ - public String getParamsForDeclaration(); - - /** - * Returns the list of constructor's parameters in a format that is - * convenient for usage in a method call. - * - * @return a String representation of the parameters list. - */ - public String getParamsForCall(); - - /** - * Returns the list of all non-primitive constructor's parameter types. - * - * @return a <code>List</code> of String representation of the parameter - * types. - */ - public List<String> getNonPrimitiveParameterTypes(); - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/CreateJavaEEArtifactTemplateModel.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/CreateJavaEEArtifactTemplateModel.java deleted file mode 100644 index a3b4727e6..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/CreateJavaEEArtifactTemplateModel.java +++ /dev/null @@ -1,394 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 SAP AG and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Kaloyan Raev, kaloyan.raev@sap.com - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.operations; - -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.ABSTRACT_METHODS; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.CLASS_NAME; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.CONSTRUCTOR; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.INTERFACES; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.JAVA_PACKAGE; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.MODIFIER_ABSTRACT; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.MODIFIER_FINAL; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.MODIFIER_PUBLIC; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.PROJECT; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.SUPERCLASS; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.core.resources.IProject; -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.IMethod; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.Signature; -import org.eclipse.jdt.core.dom.AST; -import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.ASTParser; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.core.dom.ITypeBinding; -import org.eclipse.jdt.core.dom.MethodDeclaration; -import org.eclipse.jdt.core.dom.Type; -import org.eclipse.jdt.core.dom.TypeDeclaration; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; - -public class CreateJavaEEArtifactTemplateModel { - - /** - * Constant representing no compatibility flag. - */ - public static final int FLAG_NONE = 0x00000000; - - /** - * Constant representing the <i>Qualified Superclass Name</i> compatibility - * flag. - * - * <p> - * When this flag is set then the {@link #getSuperclassName()} method always - * returns the qualified name of the superclass. - * </p> - * - * @see #getSuperclassName() - */ - public static final int FLAG_QUALIFIED_SUPERCLASS_NAME = 0x00000001; - - /** - * Constant representing a combination of all possible compatibility flags. - */ - public static final int FLAG_ALL = 0xffffffff; - - /** - * Compatibility flags. - * - * @see #addFlags(int) - * @see #removeFlags(int) - * @see #FLAG_NONE - * @see #FLAG_QUALIFIED_SUPERCLASS_NAME - * @see #FLAG_ALL - */ - protected int flags; - - protected IDataModel dataModel; - - public CreateJavaEEArtifactTemplateModel(IDataModel dataModel) { - this.dataModel = dataModel; - this.flags = FLAG_QUALIFIED_SUPERCLASS_NAME; - } - - /** - * Adds compatibility flags represented by the given bitmask. - * - * @param bitmask - - * represents the flags to add. - * - * @see #addFlags(int) - * @see #removeFlags(int) - * @see #FLAG_NONE - * @see #FLAG_QUALIFIED_SUPERCLASS_NAME - * @see #FLAG_ALL - */ - public void addFlags(int bitmask) { - flags = flags | bitmask; - } - - /** - * Removes compatibility flags represented by the given bitmask. - * - * @param bitmask - - * represents the flags to remove. - * - * @see #addFlags(int) - * @see #removeFlags(int) - * @see #FLAG_NONE - * @see #FLAG_QUALIFIED_SUPERCLASS_NAME - * @see #FLAG_ALL - */ - public void removeFlags(int bitmask) { - flags = flags & ~bitmask; - } - - /** - * Check if compatibility flags, represented by the given bitmask, are set. - * - * @param bitmask - - * represents the flags to check. - * - * @return <code>true</code> - if all of the given flags are set, - * <code>false</code> - if any of the given flags is not set. - * - * @see #addFlags(int) - * @see #removeFlags(int) - * @see #FLAG_NONE - * @see #FLAG_QUALIFIED_SUPERCLASS_NAME - * @see #FLAG_ALL - */ - public boolean areFlagsSet(int bitmask) { - return (flags & bitmask) != 0; - } - - public Collection<String> getImports() { - Collection<String> collection = new ImportsCollection(this); - - String className = getClassName(); - String superclassName = getQualifiedSuperclassName(); - - if (superclassName != null && superclassName.length() > 0 && - !areFlagsSet(FLAG_QUALIFIED_SUPERCLASS_NAME) && - !equalSimpleNames(className, superclassName)) { - collection.add(superclassName); - } - - List<String> interfaces = getQualifiedInterfaces(); - if (interfaces != null) { - for (String iface : interfaces) { - if (!equalSimpleNames(getClassName(), iface)) { - collection.add(iface); - } - } - } - - List<Constructor> constructors = getConstructors(); - for (Constructor constructor : constructors) { - List<String> types = constructor.getNonPrimitiveParameterTypes(); - for (String type : types) { - collection.add(type); - } - } - - Collection<Method> methods = getUnimplementedMethods(); - for (Method method : methods) { - collection.addAll(method.getParameterImports()); - collection.addAll(method.getReturnTypeImports()); - } - - return collection; - } - - public String getClassName() { - return getProperty(CLASS_NAME).trim(); - } - - public String getJavaPackageName() { - return getProperty(JAVA_PACKAGE).trim(); - } - - public String getQualifiedJavaClassName() { - return getJavaPackageName() + "." + getClassName(); //$NON-NLS-1$ - } - - public String getSuperclassName() { - String qualified = getQualifiedSuperclassName(); - if (areFlagsSet(FLAG_QUALIFIED_SUPERCLASS_NAME) || equalSimpleNames(getClassName(), qualified)) { - return qualified; - } else { - return Signature.getSimpleName(qualified); - } - } - - public String getQualifiedSuperclassName() { - return getProperty(SUPERCLASS).trim(); - } - - public List<String> getInterfaces() { - List<String> qualifiedInterfaces = getQualifiedInterfaces(); - List<String> interfaces = new ArrayList<String>(qualifiedInterfaces.size()); - - for (String qualified : qualifiedInterfaces) { - if (equalSimpleNames(getClassName(), qualified)) { - interfaces.add(qualified); - } else { - interfaces.add(Signature.getSimpleName(qualified)); - } - } - - return interfaces; - } - - public List<String> getQualifiedInterfaces() { - List<String> interfaces = (List<String>) dataModel.getProperty(INTERFACES); - return (interfaces == null) ? new ArrayList<String>() : interfaces; - } - - public boolean isPublic() { - return dataModel.getBooleanProperty(MODIFIER_PUBLIC); - } - - public boolean isFinal() { - return dataModel.getBooleanProperty(MODIFIER_FINAL); - } - - public boolean isAbstract() { - return dataModel.getBooleanProperty(MODIFIER_ABSTRACT); - } - - public boolean shouldGenSuperclassConstructors() { - return dataModel.getBooleanProperty(CONSTRUCTOR); - } - - public boolean shouldImplementAbstractMethods(){ - return dataModel.getBooleanProperty(ABSTRACT_METHODS); - } - - public boolean hasEmptySuperclassConstructor() { - List<Constructor> constructors = getConstructors(); - for (Constructor constructor : constructors) { - if (constructor.isParameterless()) - return true; - } - - return false; - } - - public List<Constructor> getConstructors() { - List<Constructor> constrs = new ArrayList<Constructor>(); - - String superclass = dataModel.getStringProperty(SUPERCLASS); - if (superclass != null && superclass.length() > 0) { - IProject p = (IProject) dataModel.getProperty(PROJECT); - IJavaProject javaProject = JavaCore.create(p); - if (javaProject != null) { - try { - IType type = javaProject.findType(superclass); - if (type != null) { - if (type.isBinary()) { - IMethod[] methods = type.getMethods(); - for (IMethod method : methods) { - if (method.isConstructor()) - constrs.add(new BinaryConstructor(method)); - } - } else { - ICompilationUnit compilationUnit = type.getCompilationUnit(); - TypeDeclaration declarationFromType = getTypeDeclarationFromType(superclass, compilationUnit); - if (declarationFromType != null) { - MethodDeclaration[] methods = declarationFromType.getMethods(); - for (MethodDeclaration method : methods) { - if (method.isConstructor()) - constrs.add(new SourceConstructor(method)); - } - } - } - } - } catch (JavaModelException e) { - J2EEPlugin.logError(e); - } - } - } - - return constrs; - } - - public Collection<Method> getUnimplementedMethods() { - Collection<Method> unimplementedMethods = new HashSet<Method>(); - - if (shouldImplementAbstractMethods()) { - IJavaProject javaProject = getJavaProject(); - List<String> interfaces = getQualifiedInterfaces(); - for (String iface : interfaces) { - try { - IType type = javaProject.findType(iface); - if (type != null) - getUnimplementedMethod0(type, unimplementedMethods); - } catch (JavaModelException e) { - J2EEPlugin.logError(e); - } - } - } - - return unimplementedMethods; - } - - private void getUnimplementedMethod0(IType type, Collection<Method> unimplementedMethods) throws JavaModelException { - IJavaProject javaProject = getJavaProject(); - if (type.isBinary()) { - IMethod[] methods = type.getMethods(); - for (IMethod method : methods) { - unimplementedMethods.add(new BinaryMethod(method)); - } - - // process super interfaces - String[] superInterfaces = type.getSuperInterfaceNames(); - for (String superInterface : superInterfaces) { - IType superInterfaceType = javaProject.findType(superInterface); - if (superInterfaceType != null) - getUnimplementedMethod0(superInterfaceType, unimplementedMethods); - } - } else { - ICompilationUnit compilationUnit = type.getCompilationUnit(); - TypeDeclaration declarationFromType = getTypeDeclarationFromType(type.getFullyQualifiedName(), compilationUnit); - if (declarationFromType != null) { - MethodDeclaration[] methods = declarationFromType.getMethods(); - for (MethodDeclaration method : methods) { - unimplementedMethods.add(new SourceMethod(method)); - } - } - - // process super interfaces - List<Type> superInterfaces = declarationFromType.superInterfaceTypes(); - for (Type superInterface : superInterfaces) { - ITypeBinding binding = superInterface.resolveBinding(); - IType superInterfaceType = javaProject.findType(binding.getQualifiedName()); - if (superInterfaceType != null) - getUnimplementedMethod0(superInterfaceType, unimplementedMethods); - } - } - } - - protected String getProperty(String propertyName) { - return dataModel.getStringProperty(propertyName); - } - - protected boolean equalSimpleNames(String name1, String name2) { - String simpleName1 = Signature.getSimpleName(name1); - String simpleName2 = Signature.getSimpleName(name2); - return simpleName1.equals(simpleName2); - } - - protected IJavaProject getJavaProject() { - IProject p = (IProject) dataModel.getProperty(PROJECT); - return JavaCore.create(p); - } - - private TypeDeclaration getTypeDeclarationFromType(String typeName, ICompilationUnit unit) { - CompilationUnit cu = (CompilationUnit) parse(unit); - Iterator iterator = cu.types().iterator(); - while (iterator.hasNext()) { - Object obj = iterator.next(); - if (obj instanceof TypeDeclaration) { - TypeDeclaration declaration = (TypeDeclaration) obj; - ITypeBinding tb = declaration.resolveBinding(); - if (tb != null) { - String declarationName = tb.getQualifiedName(); - if (typeName.equals(declarationName)) { - return declaration; - } - } - } - } - - return null; - } - - private ASTNode parse(ICompilationUnit unit) { - ASTParser parser = ASTParser.newParser(AST.JLS3); - parser.setKind(ASTParser.K_COMPILATION_UNIT); - parser.setSource(unit); - parser.setResolveBindings(true); - parser.setStatementsRecovery(true); - return parser.createAST(null); - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/INewJavaClassDataModelProperties.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/INewJavaClassDataModelProperties.java deleted file mode 100644 index fe85b7b13..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/INewJavaClassDataModelProperties.java +++ /dev/null @@ -1,113 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.operations; - -import org.eclipse.wst.common.componentcore.internal.operation.IArtifactEditOperationDataModelProperties; - -public interface INewJavaClassDataModelProperties extends IArtifactEditOperationDataModelProperties { - - /** - * Required, String property used to set the unqualified java class name for the new java class. - */ - public static final String CLASS_NAME = "NewJavaClassDataModel.CLASS_NAME"; //$NON-NLS-1$ - - /** - * Optional, String property used to set the source folder location for the new java class. The first - * source folder found in the project will be used if one is not specified. - */ - public static final String SOURCE_FOLDER = "NewJavaClassDataModel.SOURCE_FOLDER"; //$NON-NLS-1$ - - /** - * Optional, String property used to to set the java package for the new java class. The default - * package is used if one is not specified. - */ - public static final String JAVA_PACKAGE = "NewJavaClassDataModel.JAVA_PACKAGE"; //$NON-NLS-1$ - - /** - * Optional, String property used to set the qualified java class name of the superclass of the - * new java class. - */ - public static final String SUPERCLASS = "NewJavaClassDataModel.SUPERCLASS"; //$NON-NLS-1$ - - /** - * Optional, boolean property used to set the visibility of the new java class. This is true - * by default. - */ - public static final String MODIFIER_PUBLIC = "NewJavaClassDataModel.MODIFIER_PUBLIC"; //$NON-NLS-1$ - - /** - * Optional, boolean property used to set whether the new java class is abstract. This is false - * by default. - */ - public static final String MODIFIER_ABSTRACT = "NewJavaClassDataModel.MODIFIER_ABSTRACT"; //$NON-NLS-1$ - - /** - * Optional, boolean property used to set whether the new java class is declared final. This is false - * by default. - */ - public static final String MODIFIER_FINAL = "NewJavaClassDataModel.MODIFIER_FINAL"; //$NON-NLS-1$ - - /** - * Optional, List property of all the qualified names of interfaces the new java class should implement. - */ - public static final String INTERFACES = "NewJavaClassDataModel.INTERFACES"; //$NON-NLS-1$ - - /** - * Optional, boolean property used to set whether the new java class should generate a main method. This - * is false by default. - */ - public static final String MAIN_METHOD = "NewJavaClassDataModel.MAIN_METHOD"; //$NON-NLS-1$ - - /** - * Optional, boolean property used to set whether or not the constructor from the superclass should be - * generated in the new java class. The default value is true. - */ - public static final String CONSTRUCTOR = "NewJavaClassDataModel.CONSTRUCTOR"; //$NON-NLS-1$ - - /** - * Optional, boolean property used to set whether the new java class should add method stubs for unimplemented - * methods defined in the interfaces of the interface list. This is true by default. - */ - public static final String ABSTRACT_METHODS = "NewJavaClassDataModel.ABSTRACT_METHODS"; //$NON-NLS-1$ - - /** - * Optional, boolean property used to set whether the new java class should - * be open in the default editor. The default value is true. The value could - * be changed to false if opening the java class in the editor is not - * desired. - */ - public static final String OPEN_IN_EDITOR = "NewJavaClassDataModel.OPEN_IN_EDITOR"; //$NON-NLS-1$ - - /** - * THIS PROPERTY SHOULD NOT BE SET, it's value is meant to be determined as a helper method - */ - public static final String JAVA_PACKAGE_FRAGMENT_ROOT = "NewJavaClassDataModel.JAVA_PACKAGE_FRAGMENT_ROOT"; //$NON-NLS-1$ - - /** - * THIS PROPERTY SHOULD NOT BE SET, it's value is meant to be determined as a helper method - */ - public static final String JAVA_SOURCE_FOLDER = "NewJavaClassDataModel.JAVA_SOURCE_FOLDER"; //$NON-NLS-1$ - - /** - * THIS PROPERTY SHOULD NOT BE SET, it's value is meant to be determined as a helper method - */ - public static final String PROJECT = "NewJavaClassDataModel.PROJECT"; //$NON-NLS-1$ - - /** - * THIS PROPERTY SHOULD NOT BE SET, it's value is meant to be determined as a helper method - */ - public static final String QUALIFIED_CLASS_NAME = "NewJavaClassDataModel.QUALIFIED_CLASS_NAME"; //$NON-NLS-1$ - - /** - * Required, String property used to determine if a default deployment descriptor should be created - */ - public static final String GENERATE_DD = "INewJavaClassDataModelProperties.GENERATE_DD"; //$NON-NLS-1$ -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/ImportsCollection.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/ImportsCollection.java deleted file mode 100644 index de045842f..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/ImportsCollection.java +++ /dev/null @@ -1,99 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 SAP AG and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Kaloyan Raev, kaloyan.raev@sap.com - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.operations; - -import java.util.Collection; -import java.util.Iterator; -import java.util.TreeSet; - -import org.eclipse.jdt.core.Signature; - -public class ImportsCollection implements Collection<String> { - - private Collection<String> collection; - private CreateJavaEEArtifactTemplateModel model; - - public ImportsCollection(CreateJavaEEArtifactTemplateModel model) { - collection = new TreeSet<String>(); - this.model = model; - } - - public boolean add(String o) { - if (!isImportInJavaLang(o) && !isImportInSamePackage(o)) - return collection.add(o); - - return false; - } - - public boolean addAll(Collection<? extends String> c) { - boolean result = false; - - for (String o : c) - result = result | this.add(o); - - return result; - } - - public void clear() { - collection.clear(); - } - - public boolean contains(Object o) { - return collection.contains(o); - } - - public boolean containsAll(Collection<?> c) { - return collection.containsAll(c); - } - - public boolean isEmpty() { - return collection.isEmpty(); - } - - public Iterator<String> iterator() { - return collection.iterator(); - } - - public boolean remove(Object o) { - return collection.remove(o); - } - - public boolean removeAll(Collection<?> c) { - return collection.removeAll(c); - } - - public boolean retainAll(Collection<?> c) { - return collection.retainAll(c); - } - - public int size() { - return collection.size(); - } - - public Object[] toArray() { - return collection.toArray(); - } - - public <T> T[] toArray(T[] a) { - return collection.toArray(a); - } - - private boolean isImportInJavaLang(String arg) { - return arg.startsWith("java.lang."); - } - - private boolean isImportInSamePackage(String arg) { - String qualifier = Signature.getQualifier(arg); - - return qualifier.equals(model.getJavaPackageName()); - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/J2EEModifierHelperCreator.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/J2EEModifierHelperCreator.java deleted file mode 100644 index 16fa74fb1..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/J2EEModifierHelperCreator.java +++ /dev/null @@ -1,195 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.operations; - - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.emf.ecore.EStructuralFeature; -import org.eclipse.jst.j2ee.common.CommonPackage; -import org.eclipse.jst.j2ee.common.SecurityRole; -import org.eclipse.jst.j2ee.ejb.AssemblyDescriptor; -import org.eclipse.jst.j2ee.ejb.EJBJar; -import org.eclipse.jst.j2ee.ejb.EjbPackage; -import org.eclipse.jst.j2ee.ejb.EnterpriseBean; -import org.eclipse.jst.j2ee.ejb.MethodElement; -import org.eclipse.jst.j2ee.ejb.MethodPermission; -import org.eclipse.jst.j2ee.ejb.internal.impl.EjbFactoryImpl; -import org.eclipse.wst.common.internal.emf.utilities.EtoolsCopyUtility; -import org.eclipse.wst.common.internal.emfworkbench.integration.ModifierHelper; - - -/** - * Insert the type's description here. Creation date: (4/8/2001 10:13:52 PM) - * - * @author: Administrator - */ -public class J2EEModifierHelperCreator { - - public static ModifierHelper createAssemblyDescriptorHelper(EJBJar anEJBJar) { - if (anEJBJar == null || anEJBJar.getAssemblyDescriptor() != null) - return null; - EjbPackage pack = EjbFactoryImpl.getPackage(); - EStructuralFeature sf = pack.getEJBJar_AssemblyDescriptor(); - return new ModifierHelper(anEJBJar, sf, null); - } - - /** - * return modifier helper that will create a method element with method type and param - * associated with the methodSig and the methodpermission will be derived from the security - * role. - */ - - public static ModifierHelper createMethodElementAsCopyHelper(MethodElement element, SecurityRole role) { - if (role == null) - return null; - ModifierHelper tempHelper = new ModifierHelper(); - setMethodPermissionOwnerHelper(tempHelper, role); - tempHelper.setFeature(getEjbPackage().getMethodPermission_MethodElements()); - tempHelper.setValue(EtoolsCopyUtility.createCopy(element)); - return tempHelper; - } - - /** - * return modifier helper that will create a method element with method type and param - * associated with the methodSig and the methodpermission will be derived from the security - * role. - */ - - public static ModifierHelper createMethodElementHelper(EnterpriseBean bean, SecurityRole role, String methodType, String methodSig) { - if (role == null) - return null; - ModifierHelper tempHelper = new ModifierHelper(); - setMethodPermissionOwnerHelper(tempHelper, role); - tempHelper.setFeature(getEjbPackage().getMethodPermission_MethodElements()); - tempHelper.addAttribute(getEjbPackage().getMethodElement_Type(), methodType); - int index = methodSig.indexOf("(");//$NON-NLS-1$ - String methodName = methodSig; - String methodParms = null; - if (index > -1) { - methodName = methodSig.substring(0, index); - methodParms = methodSig.substring(index + 1, methodSig.length() - 1); - } - if (methodParms != null) - methodParms = methodParms.replace(',', ' '); - tempHelper.addAttribute(getEjbPackage().getMethodElement_Name(), methodName); - if (methodParms != null) - tempHelper.addAttribute(getEjbPackage().getMethodElement_Parms(), methodParms); - tempHelper.addAttribute(getEjbPackage().getMethodElement_EnterpriseBean(), bean); - return tempHelper; - } - - /** - * return modifier helper that will create a method element with method type and param - * associated with the methodSig and a new methodtransacton for a transtype. - */ - - public static ModifierHelper createMethodElementHelper(EnterpriseBean bean, String methodType, String methodSig, String transType) { - if (bean == null) - return null; - ModifierHelper ownerHelper = createMethodTransactionHelper((EJBJar) bean.eContainer(), transType); - ModifierHelper tempHelper = new ModifierHelper(); - tempHelper.setOwnerHelper(ownerHelper); - tempHelper.setFeature(getEjbPackage().getMethodTransaction_MethodElements()); - tempHelper.addAttribute(getEjbPackage().getMethodElement_Type(), methodType); - int index = methodSig.indexOf("(");//$NON-NLS-1$ - String methodName = methodSig; - String methodParms = null; - if (index > -1) { - methodName = methodSig.substring(0, index); - methodParms = methodSig.substring(index + 1, methodSig.length() - 1); - } - if (methodParms != null) - methodParms = methodParms.replace(',', ' '); - tempHelper.addAttribute(getEjbPackage().getMethodElement_Name(), methodName); - if (methodParms != null) - tempHelper.addAttribute(getEjbPackage().getMethodElement_Parms(), methodParms); - tempHelper.addAttribute(getEjbPackage().getMethodElement_EnterpriseBean(), bean); - return tempHelper; - } - - public static ModifierHelper createMethodPermissionHelper(SecurityRole role) { - - if (role == null) - return null; - - AssemblyDescriptor assembly = (AssemblyDescriptor) role.eContainer(); - EStructuralFeature sf = EjbPackage.eINSTANCE.getAssemblyDescriptor_MethodPermissions(); - ModifierHelper tempHelper = new ModifierHelper(assembly, sf, null); - tempHelper.addAttribute(getEjbPackage().getMethodPermission_Roles(), role); - return tempHelper; - } - - /** - * Create a helper that will create a new MethodTransaction with - * - * @aTransType. - */ - public static ModifierHelper createMethodTransactionHelper(EJBJar anEJBJar, String aTransType) { - if (anEJBJar == null) - return null; - ModifierHelper helper = new ModifierHelper(); - setAssemblyDescriptorOwnerHelper(helper, anEJBJar); - helper.setFeature(getEjbPackage().getAssemblyDescriptor_MethodTransactions()); - helper.addAttribute(getEjbPackage().getMethodTransaction_TransactionAttribute(), aTransType); - return helper; - } - - - - protected static CommonPackage getCommonPackage() { - return CommonPackage.eINSTANCE; - } - - protected static EjbPackage getEjbPackage() { - return EjbFactoryImpl.getPackage(); - } - - /** - * Set the owner of - * - * @helper to be the existing AssemblyDescriptor from - * @anEJBJar or set the ownerHelper of - * @helper for the creation of a new AssemblyDescriptor when one does not exist. - */ - public static void setAssemblyDescriptorOwnerHelper(ModifierHelper helper, EJBJar anEJBJar) { - ModifierHelper ownerHelper = J2EEModifierHelperCreator.createAssemblyDescriptorHelper(anEJBJar); - if (ownerHelper == null) - helper.setOwner(anEJBJar.getAssemblyDescriptor()); - else - helper.setOwnerHelper(ownerHelper); - } - - /** - * Set the owner of - * - * @helper to be the existing AssemblyDescriptor from - * @anEJBJar or set the ownerHelper of - * @helper for the creation of a new AssemblyDescriptor when one does not exist. - */ - public static void setMethodPermissionOwnerHelper(ModifierHelper helper, SecurityRole role) { - List roleList = new ArrayList(1); - roleList.add(role); - MethodPermission permission = ((AssemblyDescriptor) role.eContainer()).getMethodPermission(roleList); - ModifierHelper ownerHelper = null; - if (permission == null) - ownerHelper = J2EEModifierHelperCreator.createMethodPermissionHelper(role); - - if (ownerHelper == null) - helper.setOwner(permission); - else - helper.setOwnerHelper(ownerHelper); - } - - - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/JARDependencyDataModelProperties.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/JARDependencyDataModelProperties.java deleted file mode 100644 index 7a4c70ef2..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/JARDependencyDataModelProperties.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.operations; - -import org.eclipse.jst.j2ee.application.internal.operations.UpdateManifestDataModelProperties; -import org.eclipse.wst.common.frameworks.internal.DoNotUseMeThisWillBeDeletedPost15; - -/** - * {@link DoNotUseMeThisWillBeDeletedPost15} - * - * @deprecated This should no longer be necessary because of the new EAR & Web Lib classpath - * containers - */ -public interface JARDependencyDataModelProperties { - - /** - * String, the ear project name, required - */ - public static final String EAR_PROJECT_NAME = "AbstractJARDependencyDataModel.EAR_PROJECT_NAME"; //$NON-NLS-1$ - - public static final String REFERENCED_PROJECT_NAME = "AbstractJARDependencyDataModel.REFERENCED_PROJECT_NAME"; //$NON-NLS-1$ - - /** - * nested, required - */ - public static final String PROJECT_NAME = UpdateManifestDataModelProperties.PROJECT_NAME; - - - /** - * Used for client JAR dependency inversion - */ - public static final String OPPOSITE_PROJECT_NAME = "AbstractJARDependencyDataModel.OPPOSITE_PROJECT_NAME"; //$NON-NLS-1$ - - /** - * nested - */ - public static final String JAR_LIST = UpdateManifestDataModelProperties.JAR_LIST; - - /** - * type Integer, default JAR_MANIPULATION_ADD, other possible values are JAR_MANIPULATION_REMOVE - * and JAR_MANIPULATION_INVERT - */ - public static final String JAR_MANIPULATION_TYPE = "AbstractJARDependencyDataModel.JAR_MANIPULATION_TYPE"; //$NON-NLS-1$ - - public static final String NESTED_MODEL_UPDATE_MAINFEST = "AbstractJARDependencyDataModel.NESTED_MODEL_UPDATE_MAINFEST"; //$NON-NLS-1$ - - public static final int JAR_MANIPULATION_ADD = 0; - public static final int JAR_MANIPULATION_REMOVE = 1; - public static final int JAR_MANIPULATION_INVERT = 2; - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/JARDependencyDataModelProvider.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/JARDependencyDataModelProvider.java deleted file mode 100644 index 82af68a56..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/JARDependencyDataModelProvider.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Dec 2, 2003 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package org.eclipse.jst.j2ee.internal.common.operations; - -import java.util.Set; - -import org.eclipse.core.resources.IProject; -import org.eclipse.jem.util.emf.workbench.ProjectUtilities; -import org.eclipse.jst.j2ee.application.internal.operations.UpdateManifestDataModelProvider; -import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelProvider; -import org.eclipse.wst.common.frameworks.datamodel.DataModelFactory; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; -import org.eclipse.wst.common.frameworks.datamodel.IDataModelOperation; -import org.eclipse.wst.common.frameworks.internal.DoNotUseMeThisWillBeDeletedPost15; - -/** - * {@link DoNotUseMeThisWillBeDeletedPost15} - * - * @deprecated This should no longer be necessary because of the new EAR & Web Lib classpath - * containers - */ -public class JARDependencyDataModelProvider extends AbstractDataModelProvider implements JARDependencyDataModelProperties { - - public Set getPropertyNames() { - Set propertyNames = super.getPropertyNames(); - propertyNames.add(EAR_PROJECT_NAME); - propertyNames.add(REFERENCED_PROJECT_NAME); - propertyNames.add(JAR_MANIPULATION_TYPE); - propertyNames.add(OPPOSITE_PROJECT_NAME); - return propertyNames; - } - - public void init() { - super.init(); - IDataModel updateManifestDataModel = DataModelFactory.createDataModel(UpdateManifestDataModelProvider.class); - model.addNestedModel(NESTED_MODEL_UPDATE_MAINFEST, updateManifestDataModel); - } - - public Object getDefaultProperty(String propertyName) { - if (propertyName.equals(JAR_MANIPULATION_TYPE)) { - return new Integer(JAR_MANIPULATION_ADD); - } - return super.getDefaultProperty(propertyName); - } - - public IProject getEARProject() { - return ProjectUtilities.getProject(getStringProperty(EAR_PROJECT_NAME)); - } - - /** - * @return - */ - public IDataModel getUpdateManifestDataModel() { - return model.getNestedModel(NESTED_MODEL_UPDATE_MAINFEST); - } - - public IProject getReferencedProject() { - return ProjectUtilities.getProject(getStringProperty(REFERENCED_PROJECT_NAME)); - } - - public IProject getOppositeProject() { - return ProjectUtilities.getProject(getStringProperty(OPPOSITE_PROJECT_NAME)); - } - - public IDataModelOperation getDefaultOperation() { - return new JARDependencyOperation(model); - } -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/JARDependencyOperation.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/JARDependencyOperation.java deleted file mode 100644 index 1f0a7729f..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/JARDependencyOperation.java +++ /dev/null @@ -1,179 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Sep 2, 2003 - * - */ -package org.eclipse.jst.j2ee.internal.common.operations; - -import java.lang.reflect.InvocationTargetException; -import java.util.List; -import java.util.Set; - -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jem.util.emf.workbench.ProjectUtilities; -import org.eclipse.jem.util.logger.proxy.Logger; -import org.eclipse.jem.workbench.utility.JemProjectUtilities; -import org.eclipse.jst.j2ee.application.internal.operations.UpdateManifestDataModelProperties; -import org.eclipse.jst.j2ee.application.internal.operations.UpdateManifestDataModelProvider; -import org.eclipse.jst.j2ee.application.internal.operations.UpdateManifestOperation; -import org.eclipse.jst.j2ee.internal.common.ClasspathModel; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; -import org.eclipse.jst.j2ee.internal.project.J2EEProjectUtilities; -import org.eclipse.wst.common.componentcore.ComponentCore; -import org.eclipse.wst.common.componentcore.resources.IVirtualComponent; -import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelOperation; -import org.eclipse.wst.common.frameworks.datamodel.DataModelFactory; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; -import org.eclipse.wst.common.frameworks.internal.DoNotUseMeThisWillBeDeletedPost15; -import org.eclipse.wst.common.frameworks.internal.operations.IHeadlessRunnableWithProgress; - -/** - * {@link DoNotUseMeThisWillBeDeletedPost15} - * - * @deprecated This should no longer be necessary because of the new EAR & Web Lib classpath - * containers - */ -public class JARDependencyOperation extends AbstractDataModelOperation implements JARDependencyDataModelProperties{ - public JARDependencyOperation(IDataModel dataModel) { - super(dataModel); - } - - public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { - // TODO Auto-generated method stub - return null; - } - - public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { - // TODO Auto-generated method stub - return null; - } - - private void saveModel(ClasspathModel model, IProgressMonitor monitor) throws InvocationTargetException, InterruptedException, CoreException { - if (!model.isDirty()) - return; - validateEdit(model); - monitor.beginTask("", 2); //$NON-NLS-1$ - org.eclipse.jst.j2ee.application.internal.operations.UpdateManifestOperation mfOperation = createManifestOperation(model); - IHeadlessRunnableWithProgress buildPathOperation = createBuildPathOperation(model); - try { - mfOperation.execute(new SubProgressMonitor(monitor, 1), null); - // No longer manipulating build path... containers will calculate - //buildPathOperation.run(new SubProgressMonitor(monitor, 1)); - } catch (Exception e) { - Logger.getLogger().logError(e); - } - } - - /** - * @param model - */ - protected void validateEdit(ClasspathModel aModel) throws CoreException { - Set affectedFiles = aModel.getAffectedFiles(); - IFile[] files = (IFile[]) affectedFiles.toArray(new IFile[affectedFiles.size()]); - IStatus result = J2EEPlugin.getWorkspace().validateEdit(files, null); - if (!result.isOK()) - throw new CoreException(result); - } - - protected UpdateJavaBuildPathOperation createBuildPathOperation(ClasspathModel aModel) { - IJavaProject javaProject = JemProjectUtilities.getJavaProject(aModel.getProject()); - return new UpdateJavaBuildPathOperation(javaProject, aModel.getClassPathSelection()); - } - - private UpdateManifestOperation createManifestOperation(ClasspathModel aModel) { - IDataModel updateManifestDataModel = DataModelFactory.createDataModel(UpdateManifestDataModelProvider.class); - updateManifestDataModel.setProperty(UpdateManifestDataModelProperties.PROJECT_NAME, aModel.getProject().getName()); - updateManifestDataModel.setBooleanProperty(UpdateManifestDataModelProperties.MERGE, false); - updateManifestDataModel.setProperty(UpdateManifestDataModelProperties.JAR_LIST, UpdateManifestDataModelProvider.convertClasspathStringToList(aModel.getClassPathSelection().toString())); - updateManifestDataModel.setProperty(UpdateManifestDataModelProperties.MANIFEST_FILE, J2EEProjectUtilities.getManifestFile( aModel.getProject())); - return new UpdateManifestOperation(updateManifestDataModel); - } - - - public final IStatus execute(IProgressMonitor monitor, IAdaptable adaptable) throws ExecutionException { - - IProject proj = ProjectUtilities.getProject(model.getStringProperty(JARDependencyDataModelProperties.PROJECT_NAME)); - IProject earProject = ProjectUtilities.getProject(model.getStringProperty(JARDependencyDataModelProperties.EAR_PROJECT_NAME)); - - ClasspathModel clpModel = new ClasspathModel(J2EEProjectUtilities.readManifest(proj)); - IVirtualComponent earComponent = ComponentCore.createComponent( earProject ); - if( !earComponent.exists() ) - return OK_STATUS; - - clpModel.setSelectedEARComponent( earComponent ); - clpModel.setProject( proj ); - - try { - int jarManipulationType = model.getIntProperty(JARDependencyDataModelProperties.JAR_MANIPULATION_TYPE); - switch (jarManipulationType) { - case JARDependencyDataModelProperties.JAR_MANIPULATION_ADD : - { - List jarList = (List) model.getNestedModel(NESTED_MODEL_UPDATE_MAINFEST).getProperty(UpdateManifestDataModelProperties.JAR_LIST); - if (!jarList.isEmpty()) { - for (int i = 0; i < jarList.size(); i++) { - String jarName = (String) jarList.get(i); - clpModel.selectDependencyIfNecessary(jarName); - } - } else { - IProject refproj = ProjectUtilities.getProject(model.getStringProperty(JARDependencyDataModelProperties.REFERENCED_PROJECT_NAME)); - clpModel.selectDependencyIfNecessary( refproj ); - } - } - break; - - case JARDependencyDataModelProperties.JAR_MANIPULATION_REMOVE : - { - List jarList = (List) model.getNestedModel(NESTED_MODEL_UPDATE_MAINFEST).getProperty(UpdateManifestDataModelProperties.JAR_LIST); - for (int i = 0; i < jarList.size(); i++) { - String jarName = (String) jarList.get(i); - clpModel.removeDependency(jarName); - } - } - break; - - case JARDependencyDataModelProperties.JAR_MANIPULATION_INVERT : - { - IProject refproj = ProjectUtilities.getProject(model.getStringProperty(JARDependencyDataModelProperties.REFERENCED_PROJECT_NAME)); - IProject oppositeProject = ProjectUtilities.getProject(model.getStringProperty(JARDependencyDataModelProperties.OPPOSITE_PROJECT_NAME)); - clpModel.getClassPathSelection().invertClientJARSelection( refproj, oppositeProject ); - } - break; - - } - if (clpModel.isDirty()) - try { - saveModel(clpModel, monitor); - } catch (InvocationTargetException e) { - Logger.getLogger().logError(e); - } catch (InterruptedException e) { - Logger.getLogger().logError(e); - } catch (CoreException e) { - Logger.getLogger().logError(e); - } - } finally { - if (clpModel != null) - clpModel.dispose(); - if (monitor != null) - monitor.done(); - } - return OK_STATUS; - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/JavaModelUtil.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/JavaModelUtil.java deleted file mode 100644 index 1d147df0e..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/JavaModelUtil.java +++ /dev/null @@ -1,897 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Apr 30, 2004 - * - * To change the template for this generated file go to - * Window - Preferences - Java - Code Generation - Code and Comments - */ -package org.eclipse.jst.j2ee.internal.common.operations; - - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Map; - -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.Assert; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; -import org.eclipse.jdt.core.ClasspathContainerInitializer; -import org.eclipse.jdt.core.Flags; -import org.eclipse.jdt.core.IClassFile; -import org.eclipse.jdt.core.IClasspathContainer; -import org.eclipse.jdt.core.IClasspathEntry; -import org.eclipse.jdt.core.ICodeAssist; -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IField; -import org.eclipse.jdt.core.IJavaElement; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.IMember; -import org.eclipse.jdt.core.IMethod; -import org.eclipse.jdt.core.IOpenable; -import org.eclipse.jdt.core.IPackageFragment; -import org.eclipse.jdt.core.IPackageFragmentRoot; -import org.eclipse.jdt.core.IParent; -import org.eclipse.jdt.core.ISourceReference; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.ITypeHierarchy; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.Signature; -import org.eclipse.jdt.core.WorkingCopyOwner; -import org.eclipse.jdt.core.compiler.CharOperation; -import org.eclipse.jdt.launching.IVMInstall; -import org.eclipse.jdt.launching.IVMInstall2; -import org.eclipse.jdt.launching.JavaRuntime; - -//TODO this is a copy of the class in org.eclipse.jdt.ui and should be deleted once bugzilla 60567 -// is addressed -/** - * - * @author jsholl - * - * To change the template for this generated type comment go to Window - Preferences - Java - Code - * Generation - Code and Comments - */ -/** - * Utility methods for the Java Model. - */ -public final class JavaModelUtil { - - /** - * Only use this suffix for creating new .java files. - * In general, use one of the three *JavaLike*(..) methods in JavaCore or create - * a name from an existing compilation unit with {@link #getRenamedCUName(ICompilationUnit, String)} - * <p> - * Note: Unlike {@link JavaCore#getJavaLikeExtensions()}, this suffix includes a leading ".". - * </p> - * - * @see JavaCore#getJavaLikeExtensions() - * @see JavaCore#isJavaLikeFileName(String) - * @see JavaCore#removeJavaLikeExtension(String) - * @see #getRenamedCUName(ICompilationUnit, String) - */ - public static final String DEFAULT_CU_SUFFIX= ".java"; //$NON-NLS-1$ - - /** - * Finds a type by its qualified type name (dot separated). - * @param jproject The java project to search in - * @param fullyQualifiedName The fully qualified name (type name with enclosing type names and package (all separated by dots)) - * @return The type found, or null if not existing - */ - public static IType findType(IJavaProject jproject, String fullyQualifiedName) throws JavaModelException { - //workaround for bug 22883 - IType type= jproject.findType(fullyQualifiedName); - if (type != null) - return type; - IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots(); - for (int i= 0; i < roots.length; i++) { - IPackageFragmentRoot root= roots[i]; - type= findType(root, fullyQualifiedName); - if (type != null && type.exists()) - return type; - } - return null; - } - - /** - * Finds a type by its qualified type name (dot separated). - * @param jproject The java project to search in - * @param fullyQualifiedName The fully qualified name (type name with enclosing type names and package (all separated by dots)) - * @param owner the working copy owner - * @return The type found, or null if not existing - */ - public static IType findType(IJavaProject jproject, String fullyQualifiedName, WorkingCopyOwner owner) throws JavaModelException { - //workaround for bug 22883 - IType type= jproject.findType(fullyQualifiedName, owner); - if (type != null) - return type; - IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots(); - for (int i= 0; i < roots.length; i++) { - IPackageFragmentRoot root= roots[i]; - type= findType(root, fullyQualifiedName); - if (type != null && type.exists()) - return type; - } - return null; - } - - - - private static IType findType(IPackageFragmentRoot root, String fullyQualifiedName) throws JavaModelException{ - IJavaElement[] children= root.getChildren(); - for (int i= 0; i < children.length; i++) { - IJavaElement element= children[i]; - if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT){ - IPackageFragment pack= (IPackageFragment)element; - if (! fullyQualifiedName.startsWith(pack.getElementName())) - continue; - IType type= findType(pack, fullyQualifiedName); - if (type != null && type.exists()) - return type; - } - } - return null; - } - - private static IType findType(IPackageFragment pack, String fullyQualifiedName) throws JavaModelException{ - ICompilationUnit[] cus= pack.getCompilationUnits(); - for (int i= 0; i < cus.length; i++) { - ICompilationUnit unit= cus[i]; - IType type= findType(unit, fullyQualifiedName); - if (type != null && type.exists()) - return type; - } - return null; - } - - private static IType findType(ICompilationUnit cu, String fullyQualifiedName) throws JavaModelException{ - IType[] types= cu.getAllTypes(); - for (int i= 0; i < types.length; i++) { - IType type= types[i]; - if (getFullyQualifiedName(type).equals(fullyQualifiedName)) - return type; - } - return null; - } - - /** - * Finds a type container by container name. - * The returned element will be of type <code>IType</code> or a <code>IPackageFragment</code>. - * <code>null</code> is returned if the type container could not be found. - * @param jproject The Java project defining the context to search - * @param typeContainerName A dot separated name of the type container - * @see #getTypeContainerName(IType) - */ - public static IJavaElement findTypeContainer(IJavaProject jproject, String typeContainerName) throws JavaModelException { - // try to find it as type - IJavaElement result= jproject.findType(typeContainerName); - if (result == null) { - // find it as package - IPath path= new Path(typeContainerName.replace('.', '/')); - result= jproject.findElement(path); - if (!(result instanceof IPackageFragment)) { - result= null; - } - - } - return result; - } - - /** - * Finds a type in a compilation unit. Typical usage is to find the corresponding - * type in a working copy. - * @param cu the compilation unit to search in - * @param typeQualifiedName the type qualified name (type name with enclosing type names (separated by dots)) - * @return the type found, or null if not existing - */ - public static IType findTypeInCompilationUnit(ICompilationUnit cu, String typeQualifiedName) throws JavaModelException { - IType[] types= cu.getAllTypes(); - for (int i= 0; i < types.length; i++) { - String currName= getTypeQualifiedName(types[i]); - if (typeQualifiedName.equals(currName)) { - return types[i]; - } - } - return null; - } - - /** - * Returns the element of the given compilation unit which is "equal" to the - * given element. Note that the given element usually has a parent different - * from the given compilation unit. - * - * @param cu the cu to search in - * @param element the element to look for - * @return an element of the given cu "equal" to the given element - */ - public static IJavaElement findInCompilationUnit(ICompilationUnit cu, IJavaElement element) { - IJavaElement[] elements= cu.findElements(element); - if (elements != null && elements.length > 0) { - return elements[0]; - } - return null; - } - - /** - * Returns the qualified type name of the given type using '.' as separators. - * This is a replace for IType.getTypeQualifiedName() - * which uses '$' as separators. As '$' is also a valid character in an id - * this is ambiguous. JavaCore PR: 1GCFUNT - */ - public static String getTypeQualifiedName(IType type) { - try { - if (type.isBinary() && !type.isAnonymous()) { - IType declaringType= type.getDeclaringType(); - if (declaringType != null) { - return getTypeQualifiedName(declaringType) + '.' + type.getElementName(); - } - } - } catch (JavaModelException e) { - // ignore - } - return type.getTypeQualifiedName('.'); - } - - /** - * Returns the fully qualified name of the given type using '.' as separators. - * This is a replace for IType.getFullyQualifiedTypeName - * which uses '$' as separators. As '$' is also a valid character in an id - * this is ambiguous. JavaCore PR: 1GCFUNT - */ - public static String getFullyQualifiedName(IType type) { - try { - if (type.isBinary() && !type.isAnonymous()) { - IType declaringType= type.getDeclaringType(); - if (declaringType != null) { - return getFullyQualifiedName(declaringType) + '.' + type.getElementName(); - } - } - } catch (JavaModelException e) { - // ignore - } - return type.getFullyQualifiedName('.'); - } - - /** - * Returns the fully qualified name of a type's container. (package name or enclosing type name) - */ - public static String getTypeContainerName(IType type) { - IType outerType= type.getDeclaringType(); - if (outerType != null) { - return getFullyQualifiedName(outerType); - } else { - return type.getPackageFragment().getElementName(); - } - } - - - /** - * Concatenates two names. Uses a dot for separation. - * Both strings can be empty or <code>null</code>. - */ - public static String concatenateName(String name1, String name2) { - StringBuffer buf= new StringBuffer(); - if (name1 != null && name1.length() > 0) { - buf.append(name1); - } - if (name2 != null && name2.length() > 0) { - if (buf.length() > 0) { - buf.append('.'); - } - buf.append(name2); - } - return buf.toString(); - } - - /** - * Concatenates two names. Uses a dot for separation. - * Both strings can be empty or <code>null</code>. - */ - public static String concatenateName(char[] name1, char[] name2) { - StringBuffer buf= new StringBuffer(); - if (name1 != null && name1.length > 0) { - buf.append(name1); - } - if (name2 != null && name2.length > 0) { - if (buf.length() > 0) { - buf.append('.'); - } - buf.append(name2); - } - return buf.toString(); - } - - /** - * Evaluates if a member (possible from another package) is visible from - * elements in a package. - * @param member The member to test the visibility for - * @param pack The package in focus - */ - public static boolean isVisible(IMember member, IPackageFragment pack) throws JavaModelException { - - int type= member.getElementType(); - if (type == IJavaElement.INITIALIZER || (type == IJavaElement.METHOD && member.getElementName().startsWith("<"))) { //$NON-NLS-1$ - return false; - } - - int otherflags= member.getFlags(); - IType declaringType= member.getDeclaringType(); - if (Flags.isPublic(otherflags) || (declaringType != null && isInterfaceOrAnnotation(declaringType))) { - return true; - } else if (Flags.isPrivate(otherflags)) { - return false; - } - - IPackageFragment otherpack= (IPackageFragment) member.getAncestor(IJavaElement.PACKAGE_FRAGMENT); - return (pack != null && otherpack != null && isSamePackage(pack, otherpack)); - } - - /** - * Evaluates if a member in the focus' element hierarchy is visible from - * elements in a package. - * @param member The member to test the visibility for - * @param pack The package of the focus element focus - */ - public static boolean isVisibleInHierarchy(IMember member, IPackageFragment pack) throws JavaModelException { - int type= member.getElementType(); - if (type == IJavaElement.INITIALIZER || (type == IJavaElement.METHOD && member.getElementName().startsWith("<"))) { //$NON-NLS-1$ - return false; - } - - int otherflags= member.getFlags(); - - IType declaringType= member.getDeclaringType(); - if (Flags.isPublic(otherflags) || Flags.isProtected(otherflags) || (declaringType != null && isInterfaceOrAnnotation(declaringType))) { - return true; - } else if (Flags.isPrivate(otherflags)) { - return false; - } - - IPackageFragment otherpack= (IPackageFragment) member.getAncestor(IJavaElement.PACKAGE_FRAGMENT); - return (pack != null && pack.equals(otherpack)); - } - - - /** - * Returns the package fragment root of <code>IJavaElement</code>. If the given - * element is already a package fragment root, the element itself is returned. - */ - public static IPackageFragmentRoot getPackageFragmentRoot(IJavaElement element) { - return (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); - } - - /** - * Finds a method in a type. - * This searches for a method with the same name and signature. Parameter types are only - * compared by the simple name, no resolving for the fully qualified type name is done. - * Constructors are only compared by parameters, not the name. - * @param name The name of the method to find - * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code> - * @param isConstructor If the method is a constructor - * @return The first found method or <code>null</code>, if nothing found - */ - public static IMethod findMethod(String name, String[] paramTypes, boolean isConstructor, IType type) throws JavaModelException { - IMethod[] methods= type.getMethods(); - for (int i= 0; i < methods.length; i++) { - if (isSameMethodSignature(name, paramTypes, isConstructor, methods[i])) { - return methods[i]; - } - } - return null; - } - - /** - * @deprecated use {@link #findMethodInHierarchy(ITypeHierarchy, IType, String, String[], boolean)} - */ - public static IMethod findMethodImplementationInHierarchy(ITypeHierarchy hierarchy, IType type, String name, String[] paramTypes, boolean isConstructor) throws JavaModelException { - return findMethodInHierarchy(hierarchy, type, name, paramTypes, isConstructor); - } - - /** - * Finds a method in a type and all its super types. The super class hierarchy is searched first, then the super interfaces. - * This searches for a method with the same name and signature. Parameter types are only - * compared by the simple name, no resolving for the fully qualified type name is done. - * Constructors are only compared by parameters, not the name. - * NOTE: For finding overridden methods or for finding the declaring method, use {@link MethodOverrideTester} - * @param hierarchy The hierarchy containing the type - * @param type The type to start the search from - * @param name The name of the method to find - * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code> - * @param isConstructor If the method is a constructor - * @return The first found method or <code>null</code>, if nothing found - */ - public static IMethod findMethodInHierarchy(ITypeHierarchy hierarchy, IType type, String name, String[] paramTypes, boolean isConstructor) throws JavaModelException { - IMethod method= findMethod(name, paramTypes, isConstructor, type); - if (method != null) { - return method; - } - IType superClass= hierarchy.getSuperclass(type); - if (superClass != null) { - IMethod res= findMethodInHierarchy(hierarchy, superClass, name, paramTypes, isConstructor); - if (res != null) { - return res; - } - } - if (!isConstructor) { - IType[] superInterfaces= hierarchy.getSuperInterfaces(type); - for (int i= 0; i < superInterfaces.length; i++) { - IMethod res= findMethodInHierarchy(hierarchy, superInterfaces[i], name, paramTypes, false); - if (res != null) { - return res; - } - } - } - return method; - } - - - /** - * Tests if a method equals to the given signature. - * Parameter types are only compared by the simple name, no resolving for - * the fully qualified type name is done. Constructors are only compared by - * parameters, not the name. - * @param name Name of the method - * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code> - * @param isConstructor Specifies if the method is a constructor - * @return Returns <code>true</code> if the method has the given name and parameter types and constructor state. - */ - public static boolean isSameMethodSignature(String name, String[] paramTypes, boolean isConstructor, IMethod curr) throws JavaModelException { - if (isConstructor || name.equals(curr.getElementName())) { - if (isConstructor == curr.isConstructor()) { - String[] currParamTypes= curr.getParameterTypes(); - if (paramTypes.length == currParamTypes.length) { - for (int i= 0; i < paramTypes.length; i++) { - String t1= Signature.getSimpleName(Signature.toString(paramTypes[i])); - String t2= Signature.getSimpleName(Signature.toString(currParamTypes[i])); - if (!t1.equals(t2)) { - return false; - } - } - return true; - } - } - } - return false; - } - - /** - * Tests if two <code>IPackageFragment</code>s represent the same logical java package. - * @return <code>true</code> if the package fragments' names are equal. - */ - public static boolean isSamePackage(IPackageFragment pack1, IPackageFragment pack2) { - return pack1.getElementName().equals(pack2.getElementName()); - } - - /** - * Checks whether the given type has a valid main method or not. - */ - public static boolean hasMainMethod(IType type) throws JavaModelException { - IMethod[] methods= type.getMethods(); - for (int i= 0; i < methods.length; i++) { - if (methods[i].isMainMethod()) { - return true; - } - } - return false; - } - - /** - * Checks if the field is boolean. - */ - public static boolean isBoolean(IField field) throws JavaModelException{ - return field.getTypeSignature().equals(Signature.SIG_BOOLEAN); - } - - /** - * @return <code>true</code> iff the type is an interface or an annotation - */ - public static boolean isInterfaceOrAnnotation(IType type) throws JavaModelException { - return type.isInterface(); - } - - /** - * Resolves a type name in the context of the declaring type. - * - * @param refTypeSig the type name in signature notation (for example 'QVector') this can also be an array type, but dimensions will be ignored. - * @param declaringType the context for resolving (type where the reference was made in) - * @return returns the fully qualified type name or build-in-type name. if a unresolved type couldn't be resolved null is returned - */ - public static String getResolvedTypeName(String refTypeSig, IType declaringType) throws JavaModelException { - int arrayCount= Signature.getArrayCount(refTypeSig); - char type= refTypeSig.charAt(arrayCount); - if (type == Signature.C_UNRESOLVED) { - String name= ""; //$NON-NLS-1$ - int bracket= refTypeSig.indexOf(Signature.C_GENERIC_START, arrayCount + 1); - if (bracket > 0) - name= refTypeSig.substring(arrayCount + 1, bracket); - else { - int semi= refTypeSig.indexOf(Signature.C_SEMICOLON, arrayCount + 1); - if (semi == -1) { - throw new IllegalArgumentException(); - } - name= refTypeSig.substring(arrayCount + 1, semi); - } - String[][] resolvedNames= declaringType.resolveType(name); - if (resolvedNames != null && resolvedNames.length > 0) { - return JavaModelUtil.concatenateName(resolvedNames[0][0], resolvedNames[0][1]); - } - return null; - } else { - return Signature.toString(refTypeSig.substring(arrayCount)); - } - } - - /** - * Returns if a CU can be edited. - */ - public static boolean isEditable(ICompilationUnit cu) { - Assert.isNotNull(cu); - IResource resource= cu.getPrimary().getResource(); - return (resource.exists() && !resource.getResourceAttributes().isReadOnly()); - } - - /** - * Returns the original if the given member. If the member is already - * an original the input is returned. The returned member might not exist - * - * @deprecated Replace by IMember#getPrimaryElement() if <code>member</code> is not part - * of a shared working copy owner. Also have a look at http://bugs.eclipse.org/bugs/show_bug.cgi?id=18568 - */ - public static IMember toOriginal(IMember member) { - if (member instanceof IMethod) - return toOriginalMethod((IMethod)member); - - // TODO: remove toOriginalMethod(IMethod) - - return (IMember) member.getPrimaryElement(); - /*ICompilationUnit cu= member.getCompilationUnit(); - if (cu != null && cu.isWorkingCopy()) - return (IMember)cu.getOriginal(member); - return member;*/ - } - - /* - * TODO remove if toOriginal(IMember) can be removed - * XXX workaround for bug 18568 - * http://bugs.eclipse.org/bugs/show_bug.cgi?id=18568 - * to be removed once the bug is fixed - */ - private static IMethod toOriginalMethod(IMethod method) { - ICompilationUnit cu= method.getCompilationUnit(); - if (cu == null || isPrimary(cu)) { - return method; - } - try{ - //use the workaround only if needed - if (! method.getElementName().equals(method.getDeclaringType().getElementName())) - return (IMethod) method.getPrimaryElement(); - - IType originalType = (IType) toOriginal(method.getDeclaringType()); - IMethod[] methods = originalType.findMethods(method); - boolean isConstructor = method.isConstructor(); - for (int i=0; i < methods.length; i++) { - if (methods[i].isConstructor() == isConstructor) - return methods[i]; - } - return null; - } catch (JavaModelException e){ - return null; - } - } - - /** - * Returns true if a cu is a primary cu (original or shared working copy) - */ - public static boolean isPrimary(ICompilationUnit cu) { - return cu.getOwner() == null; - } - - /* - * http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253 - * - * Reconciling happens in a separate thread. This can cause a situation where the - * Java element gets disposed after an exists test has been done. So we should not - * log not present exceptions when they happen in working copies. - */ - public static boolean isExceptionToBeLogged(CoreException exception) { - if (!(exception instanceof JavaModelException)) - return true; - JavaModelException je= (JavaModelException)exception; - if (!je.isDoesNotExist()) - return true; - IJavaElement[] elements= je.getJavaModelStatus().getElements(); - for (int i= 0; i < elements.length; i++) { - IJavaElement element= elements[i]; - // if the element is already a compilation unit don't log - // does not exist exceptions. See bug - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=75894 - // for more details - if (element.getElementType() == IJavaElement.COMPILATION_UNIT) - continue; - ICompilationUnit unit= (ICompilationUnit)element.getAncestor(IJavaElement.COMPILATION_UNIT); - if (unit == null) - return true; - if (!unit.isWorkingCopy()) - return true; - } - return false; - } - - public static boolean isSuperType(ITypeHierarchy hierarchy, IType possibleSuperType, IType type) { - // filed bug 112635 to add this method to ITypeHierarchy - IType superClass= hierarchy.getSuperclass(type); - if (superClass != null && (possibleSuperType.equals(superClass) || isSuperType(hierarchy, possibleSuperType, superClass))) { - return true; - } - if (Flags.isInterface(hierarchy.getCachedFlags(possibleSuperType))) { - IType[] superInterfaces= hierarchy.getSuperInterfaces(type); - for (int i= 0; i < superInterfaces.length; i++) { - IType curr= superInterfaces[i]; - if (possibleSuperType.equals(curr) || isSuperType(hierarchy, possibleSuperType, curr)) { - return true; - } - } - } - return false; - } - - public static boolean isExcludedPath(IPath resourcePath, IPath[] exclusionPatterns) { - char[] path = resourcePath.toString().toCharArray(); - for (int i = 0, length = exclusionPatterns.length; i < length; i++) { - char[] pattern= exclusionPatterns[i].toString().toCharArray(); - if (CharOperation.pathMatch(pattern, path, true, '/')) { - return true; - } - } - return false; - } - - - /* - * Returns whether the given resource path matches one of the exclusion - * patterns. - * - * @see IClasspathEntry#getExclusionPatterns - */ - public final static boolean isExcluded(IPath resourcePath, char[][] exclusionPatterns) { - if (exclusionPatterns == null) return false; - char[] path = resourcePath.toString().toCharArray(); - for (int i = 0, length = exclusionPatterns.length; i < length; i++) - if (CharOperation.pathMatch(exclusionPatterns[i], path, true, '/')) - return true; - return false; - } - - - /** - * Force a reconcile of a compilation unit. - * @param unit - */ - public static void reconcile(ICompilationUnit unit) throws JavaModelException { - unit.reconcile( - ICompilationUnit.NO_AST, - false /* don't force problem detection */, - null /* use primary owner */, - null /* no progress monitor */); - } - - /** - * Helper method that tests if an classpath entry can be found in a - * container. <code>null</code> is returned if the entry can not be found - * or if the container does not allows the configuration of source - * attachments - * @param jproject The container's parent project - * @param containerPath The path of the container - * @param libPath The path of the library to be found - * @return IClasspathEntry A classpath entry from the container of - * <code>null</code> if the container can not be modified. - */ - public static IClasspathEntry getClasspathEntryToEdit(IJavaProject jproject, IPath containerPath, IPath libPath) throws JavaModelException { - IClasspathContainer container= JavaCore.getClasspathContainer(containerPath, jproject); - ClasspathContainerInitializer initializer= JavaCore.getClasspathContainerInitializer(containerPath.segment(0)); - if (container != null && initializer != null && initializer.canUpdateClasspathContainer(containerPath, jproject)) { - IClasspathEntry[] entries= container.getClasspathEntries(); - for (int i= 0; i < entries.length; i++) { - IClasspathEntry curr= entries[i]; - IClasspathEntry resolved= JavaCore.getResolvedClasspathEntry(curr); - if (resolved != null && libPath.equals(resolved.getPath())) { - return curr; // return the real entry - } - } - } - return null; // attachment not possible - } - - /** - * Get all compilation units of a selection. - * @param javaElements the selected java elements - * @return all compilation units containing and contained in elements from javaElements - * @throws JavaModelException - */ - public static ICompilationUnit[] getAllCompilationUnits(IJavaElement[] javaElements) throws JavaModelException { - HashSet result= new HashSet(); - for (int i= 0; i < javaElements.length; i++) { - addAllCus(result, javaElements[i]); - } - return (ICompilationUnit[]) result.toArray(new ICompilationUnit[result.size()]); - } - - private static void addAllCus(HashSet/*<ICompilationUnit>*/ collector, IJavaElement javaElement) throws JavaModelException { - switch (javaElement.getElementType()) { - case IJavaElement.JAVA_PROJECT: - IJavaProject javaProject= (IJavaProject) javaElement; - IPackageFragmentRoot[] packageFragmentRoots= javaProject.getPackageFragmentRoots(); - for (int i= 0; i < packageFragmentRoots.length; i++) - addAllCus(collector, packageFragmentRoots[i]); - return; - - case IJavaElement.PACKAGE_FRAGMENT_ROOT: - IPackageFragmentRoot packageFragmentRoot= (IPackageFragmentRoot) javaElement; - if (packageFragmentRoot.getKind() != IPackageFragmentRoot.K_SOURCE) - return; - IJavaElement[] packageFragments= packageFragmentRoot.getChildren(); - for (int j= 0; j < packageFragments.length; j++) - addAllCus(collector, packageFragments[j]); - return; - - case IJavaElement.PACKAGE_FRAGMENT: - IPackageFragment packageFragment= (IPackageFragment) javaElement; - collector.addAll(Arrays.asList(packageFragment.getCompilationUnits())); - return; - - case IJavaElement.COMPILATION_UNIT: - collector.add(javaElement); - return; - - default: - IJavaElement cu= javaElement.getAncestor(IJavaElement.COMPILATION_UNIT); - if (cu != null) - collector.add(cu); - } - } - - - /** - * Sets all compliance settings in the given map to 5.0 - */ - public static void set50CompilanceOptions(Map map) { - setCompilanceOptions(map, JavaCore.VERSION_1_5); - } - - public static void setCompilanceOptions(Map map, String compliance) { - if (JavaCore.VERSION_1_6.equals(compliance)) { - map.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_6); - map.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_6); - map.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_6); - map.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaCore.ERROR); - map.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, JavaCore.ERROR); - } else if (JavaCore.VERSION_1_5.equals(compliance)) { - map.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_5); - map.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_5); - map.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_5); - map.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaCore.ERROR); - map.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, JavaCore.ERROR); - } else if (JavaCore.VERSION_1_4.equals(compliance)) { - map.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_4); - map.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_3); - map.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_2); - map.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaCore.WARNING); - map.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, JavaCore.WARNING); - } else if (JavaCore.VERSION_1_3.equals(compliance)) { - map.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_3); - map.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_3); - map.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_1); - map.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaCore.IGNORE); - map.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, JavaCore.IGNORE); - } else { - throw new IllegalArgumentException("Unsupported compliance: " + compliance); //$NON-NLS-1$ - } - } - - /** - * @return returns if version 1 is less than version 2. - */ - public static boolean isVersionLessThan(String version1, String version2) { - return version1.compareTo(version2) < 0; - } - - public static boolean is50OrHigher(String compliance) { - return !isVersionLessThan(compliance, JavaCore.VERSION_1_5); - } - - public static boolean is50OrHigher(IJavaProject project) { - return is50OrHigher(project.getOption(JavaCore.COMPILER_COMPLIANCE, true)); - } - - public static boolean is50OrHigherJRE(IJavaProject project) throws CoreException { - IVMInstall vmInstall= JavaRuntime.getVMInstall(project); - if (!(vmInstall instanceof IVMInstall2)) - return true; // assume 5.0. - - String compliance= getCompilerCompliance((IVMInstall2) vmInstall, null); - if (compliance == null) - return true; // assume 5.0 - return compliance.startsWith(JavaCore.VERSION_1_5) || compliance.startsWith(JavaCore.VERSION_1_6); - } - - public static String getCompilerCompliance(IVMInstall2 vMInstall, String defaultCompliance) { - String version= vMInstall.getJavaVersion(); - if (version == null) { - return defaultCompliance; - } else if (version.startsWith(JavaCore.VERSION_1_6)) { - return JavaCore.VERSION_1_6; - } else if (version.startsWith(JavaCore.VERSION_1_5)) { - return JavaCore.VERSION_1_5; - } else if (version.startsWith(JavaCore.VERSION_1_4)) { - return JavaCore.VERSION_1_4; - } else if (version.startsWith(JavaCore.VERSION_1_3)) { - return JavaCore.VERSION_1_3; - } else if (version.startsWith(JavaCore.VERSION_1_2)) { - return JavaCore.VERSION_1_3; - } else if (version.startsWith(JavaCore.VERSION_1_1)) { - return JavaCore.VERSION_1_3; - } - return defaultCompliance; - } - - /** - * Compute a new name for a compilation unit, given the name of the new main type. - * This query tries to maintain the existing extension (e.g. ".java"). - * - * @param cu a compilation unit - * @param newMainName the new name of the cu's main type (without extension) - * @return the new name for the compilation unit - */ - public static String getRenamedCUName(ICompilationUnit cu, String newMainName) { - String oldName = cu.getElementName(); - int i = oldName.lastIndexOf('.'); - if (i != -1) { - return newMainName + oldName.substring(i); - } else { - return newMainName; - } - } - - public static boolean isImplicitImport(String qualifier, ICompilationUnit cu) { - if ("java.lang".equals(qualifier)) { //$NON-NLS-1$ - return true; - } - String packageName= cu.getParent().getElementName(); - if (qualifier.equals(packageName)) { - return true; - } - String typeName= JavaCore.removeJavaLikeExtension(cu.getElementName()); - String mainTypeName= JavaModelUtil.concatenateName(packageName, typeName); - return qualifier.equals(mainTypeName); - } - - /** - * If <code>true</code>, then element can safely be cast to any of - * {@link IParent}, {@link IOpenable}, {@link ISourceReference}, or {@link ICodeAssist}. - * @param element - * @return <code>true</code> iff element is an {@link ICompilationUnit} or an {@link IClassFile} - */ - public static boolean isTypeContainerUnit(IJavaElement element) { - // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=125504 - return element instanceof ICompilationUnit || element instanceof IClassFile; - } - - public static IJavaElement getTypeContainerUnit(IMember member) { - ICompilationUnit cu= member.getCompilationUnit(); - if (cu != null) - return cu; - else - return member.getClassFile(); - } -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/Method.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/Method.java deleted file mode 100644 index ddfcfcc39..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/Method.java +++ /dev/null @@ -1,117 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 SAP AG and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Kaloyan Raev, kaloyan.raev@sap.com - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.operations; - -import java.util.Collection; - -public interface Method { - - /** - * Returns the signature of the method. - * - * @return a String representation of the method signature. - */ - public String getSignature(); - - /** - * Returns the name of the method. - * - * @return a String representation of the method name. - */ - public String getName(); - - /** - * Returns the unqualified name of the Java class that contains the method. - * - * @return a String representation of the containing class name. - */ - public String getContainingJavaClass(); - - /** - * Returns the unqualified name of the method's return type. - * - * @return a String representation of the return type. - */ - public String getReturnType(); - - /** - * Returns the default return value for the method. - * - * <p> - * If the method return type is <code>void</code>, then this method - * returns <code>null</code>. - * </p> - * - * <p> - * If the method return type is <code>boolean</code>, then this method - * returns <code>"false"</code>. - * </p> - * - * <p> - * For any other return type that is primitive this method returns - * <code>"0"</code>. - * </p> - * - * <p> - * If the method return type is non-primitive, then this method returns - * <code>"null"</code>. - * </p> - * - * @return a String representation of the default return type value. - */ - public String getDefaultReturnValue(); - - /** - * Returns a collection of all types that should be imported so this method - * declaration can be resolved. - * - * <p> - * The types are represented by their fully qualified names. - * </p> - * - * @return a <code>Collection</code> of String representation of types to - * be imported. - */ - public Collection<String> getReturnTypeImports(); - - /** - * Returns the list of method's parameters in a format that is - * convenient for usage in a Javadoc <b>@see</b> annotation. - * - * @return a String representation of the parameters list. - */ - public String getParamsForJavadoc(); - - /** - * Returns the list of method's parameters in a format that is - * convenient for usage in a method declaration. - * - * @return a String representation of the parameters list. - */ - public String getParamsForDeclaration(); - - /** - * Returns the list of method's parameters in a format that is - * convenient for usage in a method call. - * - * @return a String representation of the parameters list. - */ - public String getParamsForCall(); - - /** - * Returns the list of all non-primitive method's parameter types. - * - * @return a <code>List</code> of String representation of the parameter - * types. - */ - public Collection<String> getParameterImports(); - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/NewJavaClassDataModelProvider.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/NewJavaClassDataModelProvider.java deleted file mode 100644 index 68a88465c..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/NewJavaClassDataModelProvider.java +++ /dev/null @@ -1,567 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.operations; - -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.ABSTRACT_METHODS; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.CLASS_NAME; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.CONSTRUCTOR; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.INTERFACES; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.JAVA_PACKAGE; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.JAVA_PACKAGE_FRAGMENT_ROOT; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.JAVA_SOURCE_FOLDER; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.MAIN_METHOD; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.MODIFIER_ABSTRACT; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.MODIFIER_FINAL; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.MODIFIER_PUBLIC; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.OPEN_IN_EDITOR; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.PROJECT; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.QUALIFIED_CLASS_NAME; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.SOURCE_FOLDER; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.SUPERCLASS; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.GENERATE_DD; - -import java.lang.reflect.Modifier; -import java.net.URI; -import java.util.Set; - -import org.eclipse.core.filesystem.EFS; -import org.eclipse.core.filesystem.IFileStore; -import org.eclipse.core.resources.IFolder; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Path; -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.IPackageFragment; -import org.eclipse.jdt.core.IPackageFragmentRoot; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.JavaConventions; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jem.util.logger.proxy.Logger; -import org.eclipse.jem.workbench.utility.JemProjectUtilities; -import org.eclipse.jst.j2ee.internal.common.J2EECommonMessages; -import org.eclipse.jst.j2ee.internal.project.J2EEProjectUtilities; -import org.eclipse.osgi.util.NLS; -import org.eclipse.wst.common.componentcore.internal.operation.ArtifactEditOperationDataModelProvider; -import org.eclipse.wst.common.frameworks.datamodel.IDataModelOperation; -import org.eclipse.wst.common.frameworks.internal.plugin.WTPCommonPlugin; - -/** - * This data model provider is a subclass of AbstractDataModelProvider and follows the - * IDataModelOperation and Data Model Wizard frameworks. - * - * @see org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelProvider - * - * This data model provider extends the ArtifactEditOperationDataModelProvider to get project name - * and artifact edit information that during the operation, the artifact edit model can be used to - * save changes. - * @see org.eclipse.wst.common.componentcore.internal.operation.ArtifactEditOperationDataModelProvider - * - * The NewJavaClassDataModelProvider is used to store all the base properties which would be needed - * to generate a new instance of a java class. Validations for these properties such as class name, - * package name, superclass, and modifiers are also provided. - * - * The INewJavaClassDataModelProperties is implemented to store all of the property names. - * @see org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties - * - * Clients must subclass this data model provider and the properties interface to use it and to - * cache and provide their own specific attributes. They should also provide their own validation - * methods and default values for the properties they add. - * - * The use of this class is EXPERIMENTAL and is subject to substantial changes. - */ -public class NewJavaClassDataModelProvider extends ArtifactEditOperationDataModelProvider { - - /** - * Subclasses may extend this method to perform their own validation. This method should not - * return null. It does not accept null as a parameter. - * - * @see NewJavaClassDataModelProvider#validate(String) - * - * @param folderFullPath - * @return IStatus - */ - protected IStatus validateJavaSourceFolder(String folderFullPath) { - // Ensure that the source folder path is not empty - if (folderFullPath == null || folderFullPath.length() == 0) { - String msg = J2EECommonMessages.ERR_JAVA_CLASS_FOLDER_NAME_EMPTY; - return WTPCommonPlugin.createErrorStatus(msg); - } - // Ensure that the source folder path is absolute - else if (!new Path(folderFullPath).isAbsolute()) { - String msg = J2EECommonMessages.ERR_JAVA_CLASS_FOLDER_NOT_ABSOLUTE; - return WTPCommonPlugin.createErrorStatus(msg); - } - IProject project = getTargetProject(); - // Ensure project is not closed - if (project == null) { - String msg = J2EECommonMessages.ERR_JAVA_CLASS_FOLDER_NOT_EXIST; - return WTPCommonPlugin.createErrorStatus(msg); - } - // Ensure project is accessible. - if (!project.isAccessible()) { - String msg = J2EECommonMessages.ERR_JAVA_CLASS_FOLDER_NOT_EXIST; - return WTPCommonPlugin.createErrorStatus(msg); - } - // Ensure the project is a java project. - try { - if (!project.hasNature(JavaCore.NATURE_ID)) { - String msg = J2EECommonMessages.ERR_JAVA_CLASS_NOT_JAVA_PROJECT; - return WTPCommonPlugin.createErrorStatus(msg); - } - } catch (CoreException e) { - Logger.getLogger().log(e); - } - // Ensure the selected folder is a valid java source folder for the component - IFolder sourcefolder = getJavaSourceFolder(); - if (sourcefolder == null || (sourcefolder != null && !sourcefolder.getFullPath().equals(new Path(folderFullPath)))) { - String msg = J2EECommonMessages.getResourceString(J2EECommonMessages.ERR_JAVA_CLASS_FOLDER_NOT_SOURCE, new String[]{folderFullPath}); - return WTPCommonPlugin.createErrorStatus(msg); - } - // Valid source is selected - return WTPCommonPlugin.OK_STATUS; - } - - /** - * Subclasses may extend this method to perform their own retrieval of a default java source - * folder. This implementation returns the first source folder in the project for the component. - * This method may return null. - * - * @return IFolder instance of default java source folder - */ - protected IFolder getDefaultJavaSourceFolder() { - IProject project = getTargetProject(); - if (project == null) - return null; - IPackageFragmentRoot[] sources = J2EEProjectUtilities.getSourceContainers(project); - // Try and return the first source folder - if (sources.length > 0) { - try { - return (IFolder) sources[0].getCorrespondingResource(); - } catch (Exception e) { - return null; - } - } - return null; - } - - /** - * Subclasses may extend this method to create their own specialized default WTP operation. This - * implementation creates an instance of the NewJavaClassOperation to create a new java class. - * This method will not return null. - * - * @see WTPOperationDataModel#getDefaultOperation() - * @see NewJavaClassOperation - * - * @return WTPOperation - */ - public IDataModelOperation getDefaultOperation() { - return new NewJavaClassOperation(getDataModel()); - } - - /** - * Subclasses may extend this method to add their own data model's properties as valid base - * properties. - * - * @see org.eclipse.wst.common.frameworks.datamodel.IDataModelProvider#getPropertyNames() - */ - public Set getPropertyNames() { - Set propertyNames = super.getPropertyNames(); - propertyNames.add(SOURCE_FOLDER); - propertyNames.add(JAVA_PACKAGE); - propertyNames.add(CLASS_NAME); - propertyNames.add(SUPERCLASS); - propertyNames.add(MODIFIER_PUBLIC); - propertyNames.add(MODIFIER_ABSTRACT); - propertyNames.add(MODIFIER_FINAL); - propertyNames.add(INTERFACES); - propertyNames.add(MAIN_METHOD); - propertyNames.add(CONSTRUCTOR); - propertyNames.add(ABSTRACT_METHODS); - propertyNames.add(OPEN_IN_EDITOR); - propertyNames.add(JAVA_PACKAGE_FRAGMENT_ROOT); - propertyNames.add(JAVA_SOURCE_FOLDER); - propertyNames.add(PROJECT); - propertyNames.add(QUALIFIED_CLASS_NAME); - propertyNames.add(GENERATE_DD); - return propertyNames; - } - - /** - * Subclasses may extend this method to add the default values for their own specific data model - * properties. This declares the default values for the new java class. This method does not - * accept null. It may return null. - * - * @see org.eclipse.wst.common.frameworks.datamodel.IDataModelProvider#getDefaultProperty(String) - * - * @param propertyName - * @return default object value of the property - */ - public Object getDefaultProperty(String propertyName) { - // Get the default source folder for the project - if (propertyName.equals(SOURCE_FOLDER)) { - IFolder sourceFolder = getDefaultJavaSourceFolder(); - if (sourceFolder != null && sourceFolder.exists()) - return sourceFolder.getFullPath().toOSString(); - } - // Use Object as the default superclass if one is not specified - else if (propertyName.equals(SUPERCLASS)) - return new String("java.lang.Object"); //$NON-NLS-1$ - // Use public as default visibility - else if (propertyName.equals(MODIFIER_PUBLIC)) - return Boolean.TRUE; - // Generate constructors from the superclass by default - else if (propertyName.equals(CONSTRUCTOR)) - return Boolean.TRUE; - // Generate unimplemented methods from declared interfaces by default - else if (propertyName.equals(ABSTRACT_METHODS)) - return Boolean.TRUE; - // Open the generated java class in the editor by default - else if (propertyName.equals(OPEN_IN_EDITOR)) - return Boolean.TRUE; - else if (propertyName.equals(PROJECT)) - return getTargetProject(); - else if (propertyName.equals(JAVA_SOURCE_FOLDER)) - return getJavaSourceFolder(); - else if (propertyName.equals(JAVA_PACKAGE_FRAGMENT_ROOT)) - return getJavaPackageFragmentRoot(); - else if (propertyName.equals(QUALIFIED_CLASS_NAME)) - return getQualifiedClassName(); - else if (GENERATE_DD.equals(propertyName)) - return Boolean.FALSE; - return super.getDefaultProperty(propertyName); - } - - /** - * This method will return the qualified java class name as specified by the class name and - * package name properties in the data model. This method should not return null. - * - * @see #CLASS_NAME - * @see #JAVA_PACKAGE - * - * @return String qualified java classname - */ - private String getQualifiedClassName() { - // Use the java package name and unqualified class name to create a qualified java class - // name - String packageName = getStringProperty(JAVA_PACKAGE); - String className = getStringProperty(CLASS_NAME); - // Ensure the class is not in the default package before adding package name to qualified - // name - if (packageName != null && packageName.trim().length() > 0) - return packageName + "." + className; //$NON-NLS-1$ - return className; - } - - /** - * Subclasses may override this method to provide their own validation of any of the data - * model's properties. This implementation ensures that a java class can be properly generated - * from the values as specified. This method will not return null. This method will not accept - * null as a parameter. - * - * @see org.eclipse.wst.common.frameworks.datamodel.IDataModelProvider#validate(java.lang.String) - * - * @param propertyName - * @return IStatus of the validity of the specifiec property - */ - public IStatus validate(String propertyName) { - IStatus result = super.validate(propertyName); - if (result != null && !result.isOK()) - return result; - if (propertyName.equals(SOURCE_FOLDER)) - return validateJavaSourceFolder(getStringProperty(propertyName)); - if (propertyName.equals(JAVA_PACKAGE)) - return validateJavaPackage(getStringProperty(propertyName)); - if (propertyName.equals(CLASS_NAME)) { - result = validateJavaClassName(getStringProperty(propertyName)); - if (result.getSeverity() != IStatus.ERROR) { - IStatus existsStatus = canCreateTypeInClasspath(getStringProperty(CLASS_NAME)); - if (existsStatus.matches(IStatus.ERROR | IStatus.WARNING)) - result = existsStatus; - } - } - if (propertyName.equals(SUPERCLASS)) - return validateSuperclass(getStringProperty(propertyName)); - if (propertyName.equals(MODIFIER_ABSTRACT) || propertyName.equals(MODIFIER_FINAL)) - return validateModifier(propertyName, getBooleanProperty(propertyName)); - - if (result == null) { - result = WTPCommonPlugin.OK_STATUS; - } - return result; - } - - /** - * This method will validate whether the specified package name is a valid java package name. It - * will be called during the doValidateProperty(String). This method will accept null. It will - * not return null. - * - * @see NewJavaClassDataModelProvider#validate(String) - * - * @param packName -- - * the package name - * @return IStatus of if the package name is valid - */ - private IStatus validateJavaPackage(String packName) { - if (packName != null && packName.trim().length() > 0) { - // Use standard java conventions to validate the package name - IStatus javaStatus = JavaConventions.validatePackageName(packName); - if (javaStatus.getSeverity() == IStatus.ERROR) { - String msg = J2EECommonMessages.ERR_JAVA_PACAKGE_NAME_INVALID + javaStatus.getMessage(); - return WTPCommonPlugin.createErrorStatus(msg); - } else if (javaStatus.getSeverity() == IStatus.WARNING) { - String msg = J2EECommonMessages.ERR_JAVA_PACKAGE_NAME_WARNING + javaStatus.getMessage(); - return WTPCommonPlugin.createWarningStatus(msg); - } - } - // java package name is valid - return WTPCommonPlugin.OK_STATUS; - } - - /** - * Subclasses may override this method to provide their own validation of the class name. This - * implementation will verify if the specified class name is a valid UNQUALIFIED java class - * name. This method will not accept null. It will not return null. - * - * @see NewJavaClassDataModelProvider#validate(String) - * - * @param className - * @return IStatus of if java class name is valid - */ - protected IStatus validateJavaClassName(String className) { - // Ensure the class name is not empty - if (className == null || className.trim().length() == 0) { - String msg = J2EECommonMessages.ERR_JAVA_CLASS_NAME_EMPTY; - return WTPCommonPlugin.createErrorStatus(msg); - } - // Do not allow qualified name - if (className.lastIndexOf('.') != -1) { - String msg = J2EECommonMessages.ERR_JAVA_CLASS_NAME_QUALIFIED; - return WTPCommonPlugin.createErrorStatus(msg); - } - // Check Java class name by standard java conventions - IStatus javaStatus = JavaConventions.validateJavaTypeName(className); - if (javaStatus.getSeverity() == IStatus.ERROR) { - String msg = J2EECommonMessages.ERR_JAVA_CLASS_NAME_INVALID + javaStatus.getMessage(); - return WTPCommonPlugin.createErrorStatus(msg); - } else if (javaStatus.getSeverity() == IStatus.WARNING) { - String msg = J2EECommonMessages.ERR_JAVA_CLASS_NAME_WARNING + javaStatus.getMessage(); - return WTPCommonPlugin.createWarningStatus(msg); - } - return WTPCommonPlugin.OK_STATUS; - } - - /** - * This method will verify the specified superclass can be subclassed. It ensures the superclass - * is a valid java class, that it exists, and that it is not final. This method will accept - * null. It will not return null. - * - * @see NewJavaClassDataModelProvider#validate(String) - * - * @param superclassName - * @return IStatus of if the superclass can be subclassed - */ - private IStatus validateSuperclass(String superclassName) { - // Ensure the superclass name is not empty - if (superclassName == null || superclassName.trim().length() == 0) { - String msg = J2EECommonMessages.ERR_JAVA_CLASS_NAME_EMPTY; - return WTPCommonPlugin.createErrorStatus(msg); - } - // In default case of Object, return OK right away - if (superclassName.equals("java.lang.Object")) //$NON-NLS-1$ - return WTPCommonPlugin.OK_STATUS; - // Ensure the unqualified java class name of the superclass is valid - String className = superclassName; - int index = superclassName.lastIndexOf("."); //$NON-NLS-1$ - if (index != -1) { - className = superclassName.substring(index + 1); - } - IStatus status = validateJavaClassName(className); - // If unqualified super class name is valid, ensure validity of superclass itself - if (status.getSeverity() != IStatus.ERROR) { - // If the superclass does not exist, throw an error - IJavaProject javaProject = JemProjectUtilities.getJavaProject(getTargetProject()); - IType supertype = null; - try { - supertype = javaProject.findType(superclassName); - } catch (Exception e) { - // Just throw error below - } - if (supertype == null) { - String msg = J2EECommonMessages.ERR_JAVA_CLASS_SUPERCLASS_NOT_EXIST; - return WTPCommonPlugin.createErrorStatus(msg); - } - // Ensure the superclass is not final - int flags = -1; - try { - flags = supertype.getFlags(); - if (Modifier.isFinal(flags)) { - String msg = J2EECommonMessages.ERR_JAVA_CLASS_SUPERCLASS_FINAL; - return WTPCommonPlugin.createErrorStatus(msg); - } - } catch (Exception e) { - Logger.getLogger().log(e); - } - } - // Return status of specified superclass - return status; - } - - /** - * This method will ensure that if the abstract modifier is set, that final is not set, and - * vice-versa, as this is not supported either way. This method will not accept null. It will - * not return null. - * - * @see NewJavaClassDataModelProvider#validate(String) - * - * @param prop - * @return IStatus of whether abstract value is valid - */ - private IStatus validateModifier(String propertyName, boolean prop) { - // Throw an error if both Abstract and Final are checked - if (prop) { - // Ensure final is not also checked - if (propertyName.equals(MODIFIER_ABSTRACT) && getBooleanProperty(MODIFIER_FINAL)) { - String msg = J2EECommonMessages.ERR_BOTH_FINAL_AND_ABSTRACT; - return WTPCommonPlugin.createErrorStatus(msg); - } - // Ensure abstract is not also checked - if (propertyName.equals(MODIFIER_FINAL) && getBooleanProperty(MODIFIER_ABSTRACT)) { - String msg = J2EECommonMessages.ERR_BOTH_FINAL_AND_ABSTRACT; - return WTPCommonPlugin.createErrorStatus(msg); - } - } - // Abstract and final settings are valid - return WTPCommonPlugin.OK_STATUS; - } - - /** - * This method is intended for internal use only. This will check the java model for the - * specified javaproject in the data model for the existence of the passed in qualified - * classname. This method does not accept null. It may return null. - * - * @see NewJavaClassDataModelProvider#getTargetProject() - * @see JavaModelUtil#findType(IJavaProject, String) - * - * @param fullClassName - * @return IType for the specified classname - */ - protected IStatus canCreateTypeInClasspath(String className) { - String packageName = getStringProperty(JAVA_PACKAGE); - return canCreateTypeInClasspath(packageName, className); - } - - protected IStatus canCreateTypeInClasspath(String packageName, String typeName) { - IPackageFragment pack = getJavaPackageFragmentRoot().getPackageFragment(packageName); - if (pack != null) { - ICompilationUnit cu = pack.getCompilationUnit(typeName + JavaModelUtil.DEFAULT_CU_SUFFIX); - String fullyQualifiedName = JavaModelUtil.getFullyQualifiedName(cu.getType(typeName)); - - IResource resource = cu.getResource(); - if (resource.exists()) { - String message = NLS.bind( - J2EECommonMessages.ERR_TYPE_ALREADY_EXIST, - new Object[] { fullyQualifiedName }); - return WTPCommonPlugin.createErrorStatus(message); - } - - URI location = resource.getLocationURI(); - if (location != null) { - try { - IFileStore store= EFS.getStore(location); - if (store.fetchInfo().exists()) { - String message = NLS.bind( - J2EECommonMessages.ERR_TYPE_DIFFERENT_CASE_EXIST, - new Object[] { fullyQualifiedName }); - return WTPCommonPlugin.createErrorStatus(message); - } - } catch (CoreException e) { - Logger.getLogger().log(e); - } - } - } - - return WTPCommonPlugin.OK_STATUS; - } - - /** - * This will return the IFolder instance for the specified folder name in the data model. This - * method may return null. - * - * @see #SOURCE_FOLDER - * @see NewJavaClassDataModelProvider#getAllSourceFolders() - * - * @return IFolder java source folder - */ - protected final IFolder getJavaSourceFolder() { - IPackageFragmentRoot[] sources = J2EEProjectUtilities.getSourceContainers(getTargetProject()); - // Ensure there is valid source folder(s) - if (sources == null || sources.length == 0) - return null; - String folderFullPath = getStringProperty(SOURCE_FOLDER); - // Get the source folder whose path matches the source folder name value in the data model - for (int i = 0; i < sources.length; i++) { - if (sources[i].getPath().equals(new Path(folderFullPath))) { - try { - return (IFolder) sources[i].getCorrespondingResource(); - } catch (Exception e) { - break; - } - } - } - return null; - } - - /** - * Subclasses may extend this method to perform their own retrieval mechanism. This - * implementation simply returns the JDT package fragment root for the selected source folder. - * This method may return null. - * - * @see IJavaProject#getPackageFragmentRoot(org.eclipse.core.resources.IResource) - * - * @return IPackageFragmentRoot - */ - protected IPackageFragmentRoot getJavaPackageFragmentRoot() { - IProject project = getTargetProject(); - if (project != null) { - IJavaProject aJavaProject = JemProjectUtilities.getJavaProject(project); - // Return the source folder for the java project of the selected project - if (aJavaProject != null) { - IFolder sourcefolder = (IFolder) getProperty(JAVA_SOURCE_FOLDER); - if (sourcefolder != null) - return aJavaProject.getPackageFragmentRoot(sourcefolder); - } - } - return null; - } - - /** - * This method ensures the source folder is updated if the component is changed. - * - * @see org.eclipse.wst.common.frameworks.datamodel.IDataModelProvider#propertySet(String, - * Object) - * - * @return boolean if property set successfully - */ - public boolean propertySet(String propertyName, Object propertyValue) { - boolean result = super.propertySet(propertyName, propertyValue); - if (result) { - if (COMPONENT_NAME.equals(propertyName)){ - if( getDefaultJavaSourceFolder() != null ){ - setProperty(SOURCE_FOLDER, getDefaultJavaSourceFolder().getFullPath().toOSString()); - } - } - } - return result; - } -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/NewJavaClassOperation.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/NewJavaClassOperation.java deleted file mode 100644 index cd67bea12..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/NewJavaClassOperation.java +++ /dev/null @@ -1,887 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.operations; - -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.ABSTRACT_METHODS; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.CLASS_NAME; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.CONSTRUCTOR; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.INTERFACES; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.JAVA_PACKAGE; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.JAVA_PACKAGE_FRAGMENT_ROOT; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.MODIFIER_ABSTRACT; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.MODIFIER_FINAL; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.MODIFIER_PUBLIC; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.SOURCE_FOLDER; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.SUPERCLASS; - -import java.io.ByteArrayInputStream; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.core.commands.operations.AbstractOperation; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IFolder; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Path; -import org.eclipse.jdt.core.Flags; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.IMethod; -import org.eclipse.jdt.core.IPackageFragment; -import org.eclipse.jdt.core.IPackageFragmentRoot; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.ITypeHierarchy; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.Signature; -import org.eclipse.jem.util.emf.workbench.ProjectUtilities; -import org.eclipse.jem.util.logger.proxy.Logger; -import org.eclipse.jem.workbench.utility.JemProjectUtilities; -import org.eclipse.wst.common.componentcore.internal.operation.IArtifactEditOperationDataModelProperties; -import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelOperation; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; - -/** - * NewJavaClassOperation is a data model operation that is used to create a default instance of a new java class - * based on the input and properties set in the NewJavaClassDataModelProvider. - * @see org.eclipse.jst.j2ee.internal.common.operations.NewJavaClassDataModelProvider - * - * It is a subclass of ArtifactEditProviderOperation and clients can invoke this operation as is or it may be subclassed to - * add additional or modify behaviour. The execute() method can be extended to drive this behaviour. - * @see org.eclipse.wst.common.componentcore.internal.operation.ArtifactEditProviderOperation - * - * The new java class is generated through the use of adding a series of static tokens defined within to - * an ongoing string buffer. - * - * The use of this class is EXPERIMENTAL and is subject to substantial changes. - * - * This needs to be removed as it is legacy inherited from another team - */ -public class NewJavaClassOperation extends AbstractDataModelOperation { - - // Tokens for string buffer creation of default java class - protected static final String EMPTY_STRING = ""; //$NON-NLS-1$ - protected static final String TAB = "\t"; //$NON-NLS-1$ - protected static final String SPACE = " "; //$NON-NLS-1$ - protected static final String DOT = "."; //$NON-NLS-1$ - protected static final String COMMA = ","; //$NON-NLS-1$ - protected static final String SEMICOLON = ";"; //$NON-NLS-1$ - protected static final String POUND = "#"; //$NON-NLS-1$ - protected static final String OPEN_PAR = "("; //$NON-NLS-1$ - protected static final String CLOSE_PAR = ")"; //$NON-NLS-1$ - protected static final String OPEN_BRA = "{"; //$NON-NLS-1$ - protected static final String CLOSE_BRA = "}"; //$NON-NLS-1$ - protected static final String lineSeparator = System.getProperty("line.separator"); //$NON-NLS-1$ - - protected static final String JAVA_LANG_OBJECT = "java.lang.Object"; //$NON-NLS-1$ - protected static final String PACKAGE = "package "; //$NON-NLS-1$ - protected static final String CLASS = "class "; //$NON-NLS-1$ - protected static final String IMPORT = "import "; //$NON-NLS-1$ - protected static final String EXTENDS = "extends "; //$NON-NLS-1$ - protected static final String IMPLEMENTS = "implements "; //$NON-NLS-1$ - protected static final String THROWS = "throws "; //$NON-NLS-1$ - protected static final String SUPER = "super"; //$NON-NLS-1$ - protected static final String PUBLIC = "public "; //$NON-NLS-1$ - protected static final String PROTECTED = "protected "; //$NON-NLS-1$ - protected static final String PRIVATE = "private "; //$NON-NLS-1$ - protected static final String STATIC = "static "; //$NON-NLS-1$ - protected static final String ABSTRACT = "abstract "; //$NON-NLS-1$ - protected static final String FINAL = "final "; //$NON-NLS-1$ - protected static final String VOID = "void"; //$NON-NLS-1$ - protected static final String INT = "int"; //$NON-NLS-1$ - protected static final String BOOLEAN = "boolean"; //$NON-NLS-1$ - protected static final String MAIN_METHOD = "\tpublic static void main(String[] args) {"; //$NON-NLS-1$ - protected static final String TODO_COMMENT = "\t\t// TODO Auto-generated method stub"; //$NON-NLS-1$ - protected static final String RETURN_NULL = "\t\treturn null;"; //$NON-NLS-1$ - protected static final String RETURN_0 = "\t\treturn 0;"; //$NON-NLS-1$ - protected static final String RETURN_FALSE = "\t\treturn false;"; //$NON-NLS-1$ - - /** - * This is a list of all the calculated import statements that will need to be added - */ - private List importStatements; - - /** - * This is a NewJavaClassOperation constructor. Data models passed in should be instances - * of NewJavaClassDataModel. This method does not accept null. It will not return null. - * @see NewJavaClassDataModelProvider - * - * @param dataModel - * @return NewJavaClassOperation - */ - public NewJavaClassOperation(IDataModel dataModel) { - super(dataModel); - importStatements = new ArrayList(); - } - - /** - * Subclasses may extend this method to add their own actions during execution. - * The implementation of the execute method drives the running of the operation. This - * method will create the source folder, the java package, and then create the java file. - * This method will accept null. - * @see AbstractOperation#execute(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.core.runtime.IAdaptable) - * - * @param monitor ProgressMonitor - * @throws CoreException - * @throws InterruptedException - * @throws InvocationTargetException - */ - public IStatus doExecute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { - // Ensure source folder exists - IFolder sourceFolder = createJavaSourceFolder(); - // Ensure java package exists - IPackageFragment pack = createJavaPackage(); - // Create java class - createJavaFile(sourceFolder, pack); - return OK_STATUS; - } - - /** - * This method will return the java source folder as specified in the java class data model. - * It will create the java source folder if it does not exist. This method may return null. - * @see #SOURCE_FOLDER - * @see IFolder#create(boolean, boolean, org.eclipse.core.runtime.IProgressMonitor) - * - * @return IFolder the java source folder - */ - protected final IFolder createJavaSourceFolder() { - // Get the source folder name from the data model - String folderFullPath = model.getStringProperty(SOURCE_FOLDER); - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - IFolder folder = root.getFolder(new Path(folderFullPath)); - // If folder does not exist, create the folder with the specified path - if (!folder.exists()) { - try { - folder.create(true, true, null); - } catch (CoreException e) { - Logger.getLogger().log(e); - } - } - // Return the source folder - return folder; - } - - /** - * This method will return the java package as specified by the new java class data model. - * If the package does not exist, it will create the package. This method should not return - * null. - * @see #JAVA_PACKAGE - * @see IPackageFragmentRoot#createPackageFragment(java.lang.String, boolean, org.eclipse.core.runtime.IProgressMonitor) - * - * @return IPackageFragment the java package - */ - protected final IPackageFragment createJavaPackage() { - // Retrieve the package name from the java class data model - String packageName = model.getStringProperty(JAVA_PACKAGE); - IPackageFragmentRoot packRoot = (IPackageFragmentRoot) model.getProperty(JAVA_PACKAGE_FRAGMENT_ROOT); - IPackageFragment pack = packRoot.getPackageFragment(packageName); - // Handle default package - if (pack == null) { - pack = packRoot.getPackageFragment(""); //$NON-NLS-1$ - } - // Create the package fragment if it does not exist - if (!pack.exists()) { - String packName = pack.getElementName(); - try { - pack = packRoot.createPackageFragment(packName, true, null); - } catch (JavaModelException e) { - Logger.getLogger().log(e); - } - } - // Return the package - return pack; - } - - /** - * Subclasses may extend this method to provide their own java file creation path. - * This implementation will use the properties specified in the data model to create - * a default java class. The class will be built using pre-defined tokens and will be - * built up using a string buffer. The method getJavaFileContent will handle the building - * of the string buffer while this method will write those contents to the file. - * This method does not accept null parameters. - * @see #CLASS_NAME - * @see NewJavaClassOperation#getJavaFileContent(IPackageFragment, String) - * - * @param sourceFolder - * @param pack - */ - protected void createJavaFile(IFolder sourceFolder, IPackageFragment pack) { - // Retrieve properties from the java class data model - String packageName = model.getStringProperty(JAVA_PACKAGE); - String className = model.getStringProperty(CLASS_NAME); - String fileName = className + ".java"; //$NON-NLS-1$ - //ICompilationUnit cu = null; - try { - // Get the java file content from the string buffer - String content = getJavaFileContent(pack, className); - // Create the compilation unit - pack.createCompilationUnit(fileName, content, true, null); - byte[] contentBytes = content.getBytes(); - IPath packageFullPath = new Path(packageName.replace('.', IPath.SEPARATOR)); - IPath javaFileFullPath = packageFullPath.append(fileName); - IFile file = sourceFolder.getFile(javaFileFullPath); - // Set the contents in the file if it already exists - if (file != null && file.exists()) { - file.setContents(new ByteArrayInputStream(contentBytes), false, true, null); - } // If the file does not exist, create it with the contents - else if (file != null) { - file.create(new ByteArrayInputStream(contentBytes), false, null); - } - // editModel.getWorkingCopy(cu, true); //Track CU. - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - /** - * This is intended for internal use only. This is where the string buffer for the contents - * of the java file is built up using the properties in the data model and the predefined tokens. - * This method will not accept null parameters. It will not return null. - * @see NewJavaClassDataModelProvider - * @see NewJavaClassOperation#createJavaFile(IFolder, IPackageFragment) - * - * @param pack - * @param className - * @return String java file contents - */ - private String getJavaFileContent(IPackageFragment pack, String className) { - // Create the superclass name - String superclassName = model.getStringProperty(SUPERCLASS); - List interfaces = (List) model.getProperty(INTERFACES); - String packageStatement = getPackageStatement(pack); - // Create the import statements - setupImportStatements(pack, superclassName, interfaces); - // Create the class declaration - String classDeclaration = getClassDeclaration(superclassName, className, interfaces); - // Create the fields - String fields = getFields(); - // Create the methods - String methods = getMethodStubs(superclassName, className); - - StringBuffer contents = new StringBuffer(); - // Add the package statement to the buffer - contents.append(packageStatement); - // Add all the import statements to the buffer - for (int i = 0; i < importStatements.size(); i++) { - contents.append(IMPORT + importStatements.get(i) + SEMICOLON); - contents.append(lineSeparator); - } - contents.append(lineSeparator); - // Add the class declaration to the buffer - contents.append(classDeclaration); - // Add the fields to the buffer - contents.append(fields); - // Add the method bodies to the buffer - contents.append(methods); - contents.append(CLOSE_BRA); - // Return the contents of the buffer - return contents.toString(); - } - - /** - * This is intended for internal use only. This method will return a package string for - * the class. It will not accept a null parameter. It will not return null. - * @see NewJavaClassOperation#getJavaFileContent(IPackageFragment, String) - * - * @param pack - * @return String package statement - */ - private String getPackageStatement(IPackageFragment pack) { - StringBuffer sb = new StringBuffer(); - // If it is not default package, add package statement - if (!pack.isDefaultPackage()) { - sb.append(PACKAGE + pack.getElementName() + SEMICOLON); - sb.append(lineSeparator); - sb.append(lineSeparator); - } - // Return contents of buffer - return sb.toString(); - } - - /** - * This method is intended for internal use. It checks to see if the qualified class name - * belongs to the specified package. This method will not accept nulls. It will not return null. - * @see NewJavaClassOperation#setupImportStatements(IPackageFragment, String, List) - * - * @param packageFragment - * @param className - * @return boolean is class in this package? - */ - private boolean isSamePackage(IPackageFragment packageFragment, String className) { - if (className != null && className.length() > 0) { - String sPackageName = packageFragment.getElementName(); - String classPackageName = Signature.getQualifier(className); - // Does the qualified class's package name match the passed in package's name? - if (classPackageName.equals(sPackageName)) - return true; - } - return false; - } - - /** - * This method is intended for internal use only. This method will set up the required import - * statements and cache to the importStatements list. - * This method does not accept null parameters. - * @see NewJavaClassOperation#importStatements - * @see NewJavaClassOperation#getJavaFileContent(IPackageFragment, String) - * - * @param pack - * @param superclassName - * @param interfaces - */ - private void setupImportStatements(IPackageFragment pack, String superclassName, List interfaces) { - // If there is a superclass and it is not in the same package, add an import for it - if (superclassName != null && superclassName.length() > 0) { - if (!superclassName.equals(JAVA_LANG_OBJECT) && !isSamePackage(pack, superclassName)) { - importStatements.add(superclassName); - } - } - // Add an import the list of implemented interfaces - if (interfaces != null && interfaces.size() > 0) { - int size = interfaces.size(); - for (int i = 0; i < size; i++) { - String interfaceName = (String) interfaces.get(i); - if(!interfaceName.equals(JAVA_LANG_OBJECT) && !isSamePackage(pack, interfaceName)){ - importStatements.add(interfaceName); - } - } - } - } - - /** - * This class is intended for internal use only. This will build up the class declartion - * statement based off the properties set in the java class data model. - * This method does not accept null parameters. It will not return null. - * @see NewJavaClassOperation#getJavaFileContent(IPackageFragment, String) - * - * @param superclassName - * @param className - * @param interfaces - * @return String class declaration string - */ - private String getClassDeclaration(String superclassName, String className, List interfaces) { - StringBuffer sb = new StringBuffer(); - // Append appropriate modifiers - if (model.getBooleanProperty(MODIFIER_PUBLIC)) - sb.append(PUBLIC); - if (model.getBooleanProperty(MODIFIER_ABSTRACT)) - sb.append(ABSTRACT); - if (model.getBooleanProperty(MODIFIER_FINAL)) - sb.append(FINAL); - // Add the class token - sb.append(CLASS); - // Add the class name - sb.append(className + SPACE); - // If there is a superclass, add the extends and super class name - if (superclassName != null && superclassName.length() > 0 && !superclassName.equals(JAVA_LANG_OBJECT)) { - int index = superclassName.lastIndexOf(DOT); - if (index != -1) - superclassName = superclassName.substring(index + 1); - sb.append(EXTENDS + superclassName + SPACE); - } - // If there are interfaces, add the implements and then interate over the interface list - if (interfaces != null && interfaces.size() > 0) { - sb.append(IMPLEMENTS); - int size = interfaces.size(); - for (int i = 0; i < size; i++) { - String interfaceName = (String) interfaces.get(i); - int index = interfaceName.lastIndexOf(DOT); - if (index != -1) - interfaceName = interfaceName.substring(index + 1); - sb.append(interfaceName); - if (i < size - 1) - sb.append(COMMA); - sb.append(SPACE); - } - } - sb.append(OPEN_BRA); - sb.append(lineSeparator); - // Return the finished class declaration string - return sb.toString(); - } - - /** - * Subclasses may extend this method to add their own fields. The default implementation - * is not to have any fields. This method will not return null. - * @see NewJavaClassOperation#getJavaFileContent(IPackageFragment, String) - * - * @return String fields string - */ - protected String getFields() { - return EMPTY_STRING; - } - - /** - * This method is intended for internal use only. This will build up a string with the - * contents of all the method stubs for the unimplemented methods defined in the interfaces. - * It will also add inherited constructors from the superclass as appropriate. - * This method does not accept null parameters. It will not return null. - * @see NewJavaClassOperation#getJavaFileContent(IPackageFragment, String) - * - * @param superclassName - * @param className - * @return String method stubs string - */ - private String getMethodStubs(String superclassName, String className) { - StringBuffer sb = new StringBuffer(); - IJavaProject javaProj = JemProjectUtilities.getJavaProject(getTargetProject()); - if (model.getBooleanProperty(INewJavaClassDataModelProperties.MAIN_METHOD)) { - // Add main method - sb.append(MAIN_METHOD); - sb.append(lineSeparator); - sb.append(TODO_COMMENT); - sb.append(lineSeparator); - sb.append(TAB + CLOSE_BRA); - sb.append(lineSeparator); - sb.append(lineSeparator); - } - - IType superClassType = null; - if (model.getBooleanProperty(CONSTRUCTOR) || model.getBooleanProperty(ABSTRACT_METHODS)) { - // Find super class type - try { - superClassType = javaProj.findType(superclassName); - } catch (JavaModelException e) { - Logger.getLogger().log(e); - } - } - if (model.getBooleanProperty(CONSTRUCTOR)) { - // Implement constructors from superclass - try { - if (superClassType != null) { - IMethod[] methods = superClassType.getMethods(); - for (int j = 0; j < methods.length; j++) { - if (methods[j].isConstructor() && !Flags.isPrivate(methods[j].getFlags()) && !hasGenericParams(methods[j])) { - String methodStub = getMethodStub(methods[j], superclassName, className); - sb.append(methodStub); - } - } - } - } catch (JavaModelException e) { - Logger.getLogger().log(e); - } - } - // Add unimplemented methods defined in the interfaces list - if (model.getBooleanProperty(ABSTRACT_METHODS) && superClassType != null) { - String methodStub = getUnimplementedMethodsFromSuperclass(superClassType, className); - if (methodStub != null && methodStub.trim().length() > 0) - sb.append(methodStub); - methodStub = getUnimplementedMethodsFromInterfaces(superClassType, className, javaProj); - if (methodStub != null && methodStub.trim().length() > 0) - sb.append(methodStub); - } - // Add any user defined method stubs - if (superClassType != null) { - String userDefined = getUserDefinedMethodStubs(superClassType); - if (userDefined != null && userDefined.trim().length() > 0) - sb.append(userDefined); - } - // Return the methods string - return sb.toString(); - } - - private boolean hasGenericParams(IMethod method) { - try { - IType parentType = method.getDeclaringType(); - String[] paramTypes = method.getParameterTypes(); - - int nP = paramTypes.length; - for (int i = 0; i < nP; i++) { - String type = paramTypes[i]; - if (!isPrimitiveType(type)) { - type = JavaModelUtil.getResolvedTypeName(type, parentType); - if(type.indexOf(Signature.C_GENERIC_START, 0) != -1){ - return true; - } - } - } - } catch (JavaModelException e) { - Logger.getLogger().log(e); - } - return false; - } - - /** - * This method is intended for internal use only. This will retrieve method stubs for - * unimplemented methods in the superclass that will need to be created in the new class. - * This method does not accept null parameters. It will not return null. - * @see NewJavaClassOperation#getMethodStubs(String, String) - * - * @param superClassType - * @param className - * @return String unimplemented methods defined in superclass - */ - private String getUnimplementedMethodsFromSuperclass(IType superClassType, String className) { - StringBuffer sb = new StringBuffer(); - try { - // Implement abstract methods from superclass - IMethod[] methods = superClassType.getMethods(); - for (int j = 0; j < methods.length; j++) { - IMethod method = methods[j]; - int flags = method.getFlags(); - // Add if the method is abstract, not private or static, and the option is selected in data model - if ((Flags.isAbstract(flags) && !Flags.isStatic(flags) && !Flags.isPrivate(flags)) || implementImplementedMethod(methods[j])) { - String methodStub = getMethodStub(methods[j], superClassType.getFullyQualifiedName(), className); - sb.append(methodStub); - } - } - } catch (JavaModelException e) { - Logger.getLogger().log(e); - } - // Return method stubs string - return sb.toString(); - } - - /** - * This method is intended for internal use only. This will retrieve method stubs for - * unimplemented methods defined in the interfaces that will need to be created in the new class. - * This method does not accept null parameters. It will not return null. - * @see NewJavaClassOperation#getMethodStubs(String, String) - * - * @param superClassType - * @param className - * @param javaProj - * @return String unimplemented methods defined in interfaces - */ - private String getUnimplementedMethodsFromInterfaces(IType superClassType, String className, IJavaProject javaProj) { - StringBuffer sb = new StringBuffer(); - try { - // Implement defined methods from interfaces - List interfaces = (List) model.getProperty(INTERFACES); - if (interfaces != null) { - for (int i = 0; i < interfaces.size(); i++) { - String qualifiedClassName = (String) interfaces.get(i); - IType interfaceType = javaProj.findType(qualifiedClassName); - IMethod[] methodArray = interfaceType.getMethods(); - // Make sure the method isn't already defined in the heirarchy - for (int j = 0; j < methodArray.length; j++) { - if (isMethodImplementedInHierarchy(methodArray[j], superClassType)) - continue; - String methodStub = getMethodStub(methodArray[j], qualifiedClassName, className); - sb.append(methodStub); - } - } - } - } catch (JavaModelException e) { - Logger.getLogger().log(e); - } - // Return method stubs string - return sb.toString(); - } - - /** - * This method is intended for internal use only. Checks to see if the passed type name - * is of a primitive type. This method does not accept null. It will not return null. - * @see Signature#getElementType(java.lang.String) - * - * @param typeName - * @return boolean is type Primitive? - */ - private boolean isPrimitiveType(String typeName) { - char first = Signature.getElementType(typeName).charAt(0); - return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED); - } - - /** - * This method is intended for internal use only. This will add import statements for the specified - * type if it is determined to be necessary. This does accept null parameters. It will not return null. - * @see NewJavaClassOperation#getMethodStub(IMethod, String, String) - * - * @param refTypeSig - * @param declaringType - * @return String type signature - * @throws JavaModelException - */ - private String resolveAndAdd(String refTypeSig, IType declaringType) throws JavaModelException { - if(refTypeSig.indexOf(Signature.C_GENERIC_START, 0) != -1){ - getImportStatements(refTypeSig, declaringType); - } else { - String resolvedTypeName = JavaModelUtil.getResolvedTypeName(refTypeSig, declaringType); - // Could type not be resolved and is import statement missing? - if (resolvedTypeName != null && !importStatements.contains(resolvedTypeName) && !resolvedTypeName.startsWith("java.lang")) { //$NON-NLS-1$ - importStatements.add(resolvedTypeName); - } - } - return Signature.toString(refTypeSig); - } - - private void getImportStatements(String signature, IType declaringType) throws JavaModelException{ - String erasure = Signature.getTypeErasure(signature); - String resolvedTypeName = JavaModelUtil.getResolvedTypeName(erasure, declaringType); - if (resolvedTypeName != null && !importStatements.contains(resolvedTypeName) && !resolvedTypeName.startsWith("java.lang")) { //$NON-NLS-1$ - importStatements.add(resolvedTypeName); - } - String [] params = Signature.getTypeArguments(signature); - for(int i=0;i<params.length; i++){ - getImportStatements(params[i], declaringType); - } - } - - /** - * This method is intended for internal use only. This will use the predefined tokens to generate the - * actual method stubs. This method does not accept null parameters. It will not return null. - * - * @param method - * @param superClassName - * @param className - * @return String method stub - */ - private String getMethodStub(IMethod method, String superClassName, String className) { - StringBuffer sb = new StringBuffer(); - try { - IType parentType = method.getDeclaringType(); - String name = method.getElementName(); - String[] paramTypes = method.getParameterTypes(); - String[] paramNames = method.getParameterNames(); - String[] exceptionTypes = method.getExceptionTypes(); - - // Parameters String - String paramString = EMPTY_STRING; - int nP = paramTypes.length; - for (int i = 0; i < nP; i++) { - String type = paramTypes[i]; - // update import statements - if (!isPrimitiveType(type)) { - type = resolveAndAdd(type, parentType); - } else { - type = Signature.toString(type); - } - - int index = type.lastIndexOf(DOT); - if (index != -1) - type = type.substring(index + 1); - paramString += type + SPACE + paramNames[i]; - if (i < nP - 1) - paramString += COMMA + SPACE; - } - // Java doc - sb.append("\t/* (non-Java-doc)"); //$NON-NLS-1$ - sb.append(lineSeparator); - sb.append("\t * @see "); //$NON-NLS-1$ - sb.append(superClassName + POUND + name + OPEN_PAR); - sb.append(paramString); - sb.append(CLOSE_PAR); - sb.append(lineSeparator); - sb.append("\t */"); //$NON-NLS-1$ - sb.append(lineSeparator); - // access - sb.append(TAB); - if (Flags.isPublic(method.getFlags())) - sb.append(PUBLIC); - else if (Flags.isProtected(method.getFlags())) - sb.append(PROTECTED); - else if (Flags.isPrivate(method.getFlags())) - sb.append(PRIVATE); - String returnType = null; - if (method.isConstructor()) { - sb.append(className); - } else { - // return type - returnType = method.getReturnType(); - if (!isPrimitiveType(returnType)) { - returnType = resolveAndAdd(returnType, parentType); - } else { - returnType = Signature.toString(returnType); - } - int idx = returnType.lastIndexOf(DOT); - if (idx == -1) - sb.append(returnType); - else - sb.append(returnType.substring(idx + 1)); - sb.append(SPACE); - // name - sb.append(name); - } - // Parameters - sb.append(OPEN_PAR + paramString + CLOSE_PAR); - // exceptions - int nE = exceptionTypes.length; - if (nE > 0) { - sb.append(SPACE + THROWS); - for (int i = 0; i < nE; i++) { - String type = exceptionTypes[i]; - if (!isPrimitiveType(type)) { - type = resolveAndAdd(type, parentType); - } else { - type = Signature.toString(type); - } - int index = type.lastIndexOf(DOT); - if (index != -1) - type = type.substring(index + 1); - sb.append(type); - if (i < nE - 1) - sb.append(COMMA + SPACE); - } - } - sb.append(SPACE + OPEN_BRA); - sb.append(lineSeparator); - if (method.isConstructor()) { - sb.append(TAB + TAB + SUPER + OPEN_PAR); - for (int i = 0; i < nP; i++) { - sb.append(paramNames[i]); - if (i < nP - 1) - sb.append(COMMA + SPACE); - } - sb.append(CLOSE_PAR + SEMICOLON); - sb.append(lineSeparator); - } else { - String methodBody = getMethodBody(method, returnType); - sb.append(methodBody); - } - sb.append(TAB + CLOSE_BRA); - sb.append(lineSeparator); - sb.append(lineSeparator); - } catch (JavaModelException e) { - Logger.getLogger().log(e); - } - return sb.toString(); - } - - /** - * This method is intended for internal use only. It checks to see whether or not the - * method is already implemented in the class heirarchy. - * It does not accept null parameters. It will not return null. - * @see NewJavaClassOperation#getUnimplementedMethodsFromInterfaces(IType, String, IJavaProject) - * - * @param method - * @param superClass - * @return boolean is method already in heirarchy? - */ - private boolean isMethodImplementedInHierarchy(IMethod method, IType superClass) { - boolean ret = false; - IMethod foundMethod = findMethodImplementationInHierarchy(method, superClass); - // if the method exists and the property is set on the data model, then return true - if (foundMethod != null && foundMethod.exists() && !implementImplementedMethod(method)) - ret = true; - return ret; - } - - /** - * This method is intended for internal use only. This will recursively check the supertype heirarchy for - * the passed in method. This will not accept null parameters. It will return null if the method does - * not already exist in the heirarchy. - * @see NewJavaClassOperation#isMethodImplementedInHierarchy(IMethod, IType) - * - * @param method - * @param superClass - * @return IMethod the method from the heirarchy - */ - private IMethod findMethodImplementationInHierarchy(IMethod method, IType superClass) { - IMethod implementedMethod = null; - try { - if (superClass != null && superClass.exists()) { - ITypeHierarchy tH = superClass.newSupertypeHierarchy(new NullProgressMonitor()); - implementedMethod = findMethodImplementationInHierarchy(tH, superClass, method.getElementName(), method.getParameterTypes(), method.isConstructor()); - } - } catch (JavaModelException e) { - //Ignore - } - return implementedMethod; - } - - /** - * This method is intended for internal use only. This will recursively check the supertype heirarchy for - * the passed in method. This will not accept null parameters. It will return null if the method does - * not already exist in the heirarchy. - * @see NewJavaClassOperation#findMethodImplementationInHierarchy(IMethod, IType) - * @see JavaModelUtil#findMethodImplementationInHierarchy(ITypeHierarchy, IType, String, String[], boolean) - * - * @param tH - * @param thisType - * @param methodName - * @param parameterTypes - * @param isConstructor - * @return IMethod - * @throws JavaModelException - */ - private IMethod findMethodImplementationInHierarchy(ITypeHierarchy tH, IType thisType, String methodName, String parameterTypes[], boolean isConstructor) throws JavaModelException { - IMethod found = JavaModelUtil.findMethod(methodName, parameterTypes, isConstructor, thisType); - // If method exists make sure it is not abstract - if (found != null && !Flags.isAbstract(found.getFlags())) { - return found; - } - // Check recursively - return JavaModelUtil.findMethodInHierarchy(tH, thisType, methodName, parameterTypes, isConstructor); - } - - /** - * Subclasses may extend this method to provide their own specific method body definitions. - * The default implementation is to add a todo, and to return the appropriate type. - * This method does not accept null parameters. It will not return null. - * @see NewJavaClassOperation#getMethodStub(IMethod, String, String) - * - * @param method - * @param returnType - * @return String method body - */ - protected String getMethodBody(IMethod method, String returnType) { - // Add a todo comment - String body = TODO_COMMENT; - body += lineSeparator; - // Add the appropriate default return type - if (returnType == null || returnType.equals(VOID)) - return body; - if (returnType.equals(INT)) - body += RETURN_0; - else if (returnType.equals(BOOLEAN)) - body += RETURN_FALSE; - else - body += RETURN_NULL; - body += lineSeparator; - // Return the method body - return body; - } - - /** - * Subclasses may extend this method to provide their own user defined method stubs. The - * default implementation to just return an empty string. This method will not accept - * null parameter. It will not return null. - * @see NewJavaClassOperation#getMethodStubs(String, String) - * - * @param superClassType - * @return String user defined methods - */ - protected String getUserDefinedMethodStubs(IType superClassType) { - return EMPTY_STRING; - } - - /** - * Subclasses may extend this method to provide their own specialized return on which nonimplemented - * methods to implement. This does not accept a null parameter. This will not return null. - * The default implementation is to always return false. - * - * @param method - * @return boolean should implement method? - */ - protected boolean implementImplementedMethod(IMethod method) { - return false; - } - - @Override - public IStatus execute(IProgressMonitor monitor, IAdaptable info) - throws ExecutionException { - // TODO Auto-generated method stub - return doExecute(monitor, info); - } - - public IProject getTargetProject() { - String projectName = model.getStringProperty(IArtifactEditOperationDataModelProperties.PROJECT_NAME); - return ProjectUtilities.getProject(projectName); - } -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/NewJavaEEArtifactClassOperation.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/NewJavaEEArtifactClassOperation.java deleted file mode 100644 index e783d130d..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/NewJavaEEArtifactClassOperation.java +++ /dev/null @@ -1,305 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 SAP AG and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Kaloyan Raev, kaloyan.raev@sap.com - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.operations; - -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.JAVA_PACKAGE; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.JAVA_PACKAGE_FRAGMENT_ROOT; -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.SOURCE_FOLDER; -import static org.eclipse.wst.common.componentcore.internal.operation.IArtifactEditOperationDataModelProperties.PROJECT_NAME; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; - -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.core.resources.IFolder; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.FileLocator; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Preferences; -import org.eclipse.emf.codegen.jet.JETException; -import org.eclipse.jdt.core.IJavaModelMarker; -import org.eclipse.jdt.core.IPackageFragment; -import org.eclipse.jdt.core.IPackageFragmentRoot; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jem.util.emf.workbench.ProjectUtilities; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; -import org.eclipse.jst.j2ee.internal.project.WTPJETEmitter; -import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelOperation; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; -import org.eclipse.wst.common.frameworks.internal.WTPPlugin; -import org.eclipse.wst.common.frameworks.internal.enablement.nonui.WFTWrappedException; - -public abstract class NewJavaEEArtifactClassOperation extends AbstractDataModelOperation { - - /** - * The extension name for a java class - */ - protected static final String DOT_JAVA = ".java"; //$NON-NLS-1$ - - /** - * Method name of template implementation classes. - */ - protected static final String GENERATE_METHOD = "generate"; //$NON-NLS-1$ - - public NewJavaEEArtifactClassOperation(IDataModel dataModel) { - super(dataModel); - } - - @Override - public IStatus execute(IProgressMonitor monitor, IAdaptable info) - throws ExecutionException { - return doExecute(monitor, info); - } - - /** - * Subclasses may extend this method to add their own actions during - * execution. The implementation of the execute method drives the running of - * the operation. This implementation will create the java source folder, - * create the java package, and then if using annotations, will use - * templates to generate an annotated web artifact java class, or if it is - * not annotated, the web artifact java class file will be created without - * the annotated tags using templates. Optionally, subclasses may extend the - * generateUsingTemplates or createJavaFile method rather than extend the - * execute method. This method will accept a null parameter. - * - * @see org.eclipse.wst.common.frameworks.internal.operation.WTPOperation#execute(org.eclipse.core.runtime.IProgressMonitor) - * @see NewWebClassOperation#generateUsingTemplates(IProgressMonitor, - * IPackageFragment) - * - * @param monitor - * @throws CoreException - * @throws InterruptedException - * @throws InvocationTargetException - */ - public IStatus doExecute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { - // Create source folder if it does not exist - createJavaSourceFolder(); - // Create java package if it does not exist - IPackageFragment pack = createJavaPackage(); - // Generate using templates - try { - generateUsingTemplates(monitor, pack); - } catch (Exception e) { - return J2EEPlugin.createStatus(IStatus.ERROR, e.getMessage(), e); - } - return OK_STATUS; - } - - protected abstract void generateUsingTemplates(IProgressMonitor monitor, - IPackageFragment fragment) throws WFTWrappedException, - CoreException; - - /** - * This method will return the java package as specified by the new java - * class data model. If the package does not exist, it will create the - * package. This method should not return null. - * - * @see #JAVA_PACKAGE - * @see IPackageFragmentRoot#createPackageFragment(java.lang.String, - * boolean, org.eclipse.core.runtime.IProgressMonitor) - * - * @return IPackageFragment the java package - */ - protected final IPackageFragment createJavaPackage() { - // Retrieve the package name from the java class data model - String packageName = model.getStringProperty(JAVA_PACKAGE); - IPackageFragmentRoot packRoot = (IPackageFragmentRoot) model.getProperty(JAVA_PACKAGE_FRAGMENT_ROOT); - IPackageFragment pack = packRoot.getPackageFragment(packageName); - // Handle default package - if (pack == null) { - pack = packRoot.getPackageFragment(""); //$NON-NLS-1$ - } - // Create the package fragment if it does not exist - if (!pack.exists()) { - String packName = pack.getElementName(); - try { - pack = packRoot.createPackageFragment(packName, true, null); - } catch (JavaModelException e) { - J2EEPlugin.logError(e); - } - } - // Return the package - return pack; - } - - /** - * This method checks the - * {@link J2EEPlugin#DYNAMIC_TRANSLATION_OF_JET_TEMPLATES_PREF_KEY} - * preference to determine the method for generating the source code of the - * Java EE artifact: - * <ul> - * <li>dynamically using the provided JET template file, or</li> - * <li>using the statically build-in template implementation class. </li> - * </ul> - * - * @param plugin - * - the plugin which calls the current method - * @param templateModel - * - a template model that is used by the JET template file or - * the template implementation class - * @param templateFile - * - a Java JET template file - * @param templateImpl - * - a Java JET template implementation class - * @param monitor - * - a monitor to report the progress of the code generation - * @param templateImpl - * - a Java JET template implementation class - * - * @return a String object with the generated source code - * - * @throws JETException - * if a problem occurs in during code generation - * - * @see #generateTemplateSource(WTPPlugin, - * CreateJavaEEArtifactTemplateModel, String, IProgressMonitor) - * @see #generateTemplateSource(CreateJavaEEArtifactTemplateModel, Object) - */ - protected String generateTemplateSource(WTPPlugin plugin, CreateJavaEEArtifactTemplateModel templateModel, String templateFile, Object templateImpl, IProgressMonitor monitor) - throws JETException { - Preferences preferences = J2EEPlugin.getDefault().getPluginPreferences(); - boolean dynamicTranslation = preferences.getBoolean(J2EEPlugin.DYNAMIC_TRANSLATION_OF_JET_TEMPLATES_PREF_KEY); - - if (dynamicTranslation) { - return generateTemplateSource(plugin, templateModel, templateFile, monitor); - } else { - return generateTemplateSource(templateModel, templateImpl); - } - } - - /** - * This method uses the statically built-in template implementation class to - * generate the source code of the Java EE artifact with the given template - * model. - * - * @param templateModel - * - a template model that is used by the template implementation - * class - * @param templateImpl - * - a Java JET template implementation class - * - * @return a String object with the generated source code - * - * @throws JETException - * if a problem occurs in during code generation - */ - protected String generateTemplateSource(CreateJavaEEArtifactTemplateModel templateModel, Object templateImpl) - throws JETException { - try { - Method method = templateImpl.getClass().getMethod(GENERATE_METHOD, new Class[] { Object.class }); - return (String) method.invoke(templateImpl, templateModel); - } catch (SecurityException e) { - throw new JETException(e); - } catch (NoSuchMethodException e) { - throw new JETException(e); - } catch (IllegalArgumentException e) { - throw new JETException(e); - } catch (IllegalAccessException e) { - throw new JETException(e); - } catch (InvocationTargetException e) { - throw new JETException(e); - } - } - - /** - * This method uses the WTPJETEmitter to generate the source code of the - * Java EE artifact with the given template model and template file. - * - * @param plugin - * - the plugin which calls the current method - * @param templateModel - * - a template model that is used by the JET template file - * @param templateFile - * - a Java JET template file - * @param monitor - * - a monitor to report the progress of the code generation - * - * @return a String object with the generated source code - * - * @throws JETException - * if a problem occurs in the JET emitter - */ - protected String generateTemplateSource(WTPPlugin plugin, CreateJavaEEArtifactTemplateModel templateModel, String templateFile, IProgressMonitor monitor) - throws JETException { - URL templateURL = FileLocator.find(plugin.getBundle(), new Path(templateFile), null); - cleanUpOldEmitterProject(); - WTPJETEmitter emitter = new WTPJETEmitter(templateURL.toString(), this.getClass().getClassLoader()); - emitter.setIntelligentLinkingEnabled(true); - emitter.addVariable(J2EEPlugin.getPlugin().getPluginID(), J2EEPlugin.getPlugin().getPluginID()); - emitter.addVariable(plugin.getPluginID(), plugin.getPluginID()); - return emitter.generate(monitor, new Object[] { templateModel }); - } - - protected void cleanUpOldEmitterProject() { - IProject project = ProjectUtilities.getProject(WTPJETEmitter.PROJECT_NAME); - if (project == null || !project.exists()) - return; - try { - IMarker[] markers = project.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ZERO); - for (int i = 0, l = markers.length; i < l; i++) { - if (((Integer) markers[i].getAttribute(IMarker.SEVERITY)).intValue() == IMarker.SEVERITY_ERROR) { - project.delete(true, new NullProgressMonitor()); - break; - } - } - } catch (Exception e) { - J2EEPlugin.logError(e); - } - } - - /** - * This method will return the java source folder as specified in the java - * class data model. It will create the java source folder if it does not - * exist. This method may return null. - * - * @see #SOURCE_FOLDER - * @see IFolder#create(boolean, boolean, - * org.eclipse.core.runtime.IProgressMonitor) - * - * @return IFolder the java source folder - */ - protected final IFolder createJavaSourceFolder() { - // Get the source folder name from the data model - IFolder folder = getSourceFolder(); - // If folder does not exist, create the folder with the specified path - if (!folder.exists()) { - try { - folder.create(true, true, null); - } catch (CoreException e) { - J2EEPlugin.logError(e); - } - } - // Return the source folder - return folder; - } - - public IProject getTargetProject() { - String projectName = model.getStringProperty(PROJECT_NAME); - return ProjectUtilities.getProject(projectName); - } - - protected IFolder getSourceFolder() { - String folderFullPath = model.getStringProperty(SOURCE_FOLDER); - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - return root.getFolder(new Path(folderFullPath)); - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/SourceConstructor.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/SourceConstructor.java deleted file mode 100644 index d143561ef..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/SourceConstructor.java +++ /dev/null @@ -1,119 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 SAP AG and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Kaloyan Raev, kaloyan.raev@sap.com - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.operations; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.jdt.core.dom.ITypeBinding; -import org.eclipse.jdt.core.dom.MethodDeclaration; -import org.eclipse.jdt.core.dom.Modifier; -import org.eclipse.jdt.core.dom.SingleVariableDeclaration; -import org.eclipse.jdt.core.dom.Type; - -public class SourceConstructor implements Constructor { - - private MethodDeclaration method; - - public SourceConstructor(MethodDeclaration method) { - this.method = method; - } - - /** - * @see Constructor#isParameterless() - */ - public boolean isParameterless() { - return method.parameters().size() == 0; - } - - /** - * @see Constructor#isPublic() - */ - public boolean isPublic() { - int modifiers = method.getModifiers(); - return Modifier.isPublic(modifiers); - } - - /** - * @see Constructor#isProtected() - */ - public boolean isProtected() { - int modifiers = method.getModifiers(); - return Modifier.isProtected(modifiers); - } - - /** - * @see Constructor#getParamsForCall() - */ - public String getParamsForCall() { - return this.getParams(false, true); - } - - /** - * @see Constructor#getParamsForDeclaration() - */ - public String getParamsForDeclaration() { - return this.getParams(true, true); - } - - /** - * @see Constructor#getParamsForJavadoc() - */ - public String getParamsForJavadoc() { - return this.getParams(true, false); - } - - /** - * @see Constructor#getNonPrimitiveParameterTypes() - */ - @SuppressWarnings("unchecked") - public List<String> getNonPrimitiveParameterTypes() { - List<String> result = new ArrayList<String>(); - - List<SingleVariableDeclaration> parameters = method.parameters(); - for (SingleVariableDeclaration parameter : parameters) { - Type type = parameter.getType(); - if (!type.isPrimitiveType()) { - ITypeBinding binding = type.resolveBinding(); - if (binding != null) - result.add(binding.getQualifiedName()); - } - } - - return result; - } - - @SuppressWarnings("unchecked") - private String getParams(boolean types, boolean names) { - StringBuilder result = new StringBuilder(); - - Iterator<SingleVariableDeclaration> iterator = method.parameters().iterator(); - while (iterator.hasNext()) { - SingleVariableDeclaration parameter = iterator.next(); - - if (types) - result.append(parameter.getType()); - - if (types && names) - result.append(" "); //$NON-NLS-1$ - - if (names) - result.append(parameter.getName()); - - if (iterator.hasNext()) - result.append(", "); //$NON-NLS-1$ - } - - return result.toString(); - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/SourceMethod.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/SourceMethod.java deleted file mode 100644 index 8d062edcf..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/SourceMethod.java +++ /dev/null @@ -1,240 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 SAP AG and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Kaloyan Raev, kaloyan.raev@sap.com - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.operations; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.jdt.core.Signature; -import org.eclipse.jdt.core.dom.ArrayType; -import org.eclipse.jdt.core.dom.ITypeBinding; -import org.eclipse.jdt.core.dom.MethodDeclaration; -import org.eclipse.jdt.core.dom.ParameterizedType; -import org.eclipse.jdt.core.dom.PrimitiveType; -import org.eclipse.jdt.core.dom.QualifiedType; -import org.eclipse.jdt.core.dom.SingleVariableDeclaration; -import org.eclipse.jdt.core.dom.Type; -import org.eclipse.jdt.core.dom.TypeDeclaration; -import org.eclipse.jdt.core.dom.WildcardType; -import org.eclipse.jdt.core.dom.PrimitiveType.Code; - -public class SourceMethod implements Method { - - private MethodDeclaration method; - - public SourceMethod(MethodDeclaration method) { - this.method = method; - } - - /** - * @see Method#getSignature() - */ - public String getSignature() { - List<SingleVariableDeclaration> parameters = method.parameters(); - List<String> parameterTypesList = new ArrayList<String>(); - for (SingleVariableDeclaration parameter : parameters) { - parameterTypesList.add(parameter.getType().resolveBinding().getQualifiedName()); - } - - String[] parameterTypes = parameterTypesList.toArray(new String[] { }); - String returnType = method.getReturnType2().resolveBinding().getQualifiedName(); - - return Signature.createMethodSignature(parameterTypes, returnType); - } - - /** - * @see Method#getName() - */ - public String getName() { - return method.getName().getIdentifier(); - } - - /** - * @see Method#getContainingJavaClass() - */ - public String getContainingJavaClass() { - TypeDeclaration type = (TypeDeclaration) method.getParent(); - return type.getName().getIdentifier(); - } - - /** - * @see Method#getReturnType() - */ - public String getReturnType() { - return method.getReturnType2().resolveBinding().getName(); - } - - /** - * @see Method#getDefaultReturnValue() - */ - public String getDefaultReturnValue() { - Type returnType = method.getReturnType2(); - if (returnType.isPrimitiveType()) { - Code code = ((PrimitiveType) returnType).getPrimitiveTypeCode(); - if (code == PrimitiveType.VOID) { - return null; - } else if (code == PrimitiveType.BOOLEAN) { - return "false"; - } else { - return "0"; - } - } else { - return "null"; - } - } - - /** - * @see Method#getReturnTypeImports() - */ - public Collection<String> getReturnTypeImports() { - List<String> result = new ArrayList<String>(); - - Type returnType = method.getReturnType2(); - getTypeImports(returnType, result); - - return result; - } - - /** - * @see Method#getParamsForCall() - */ - public String getParamsForCall() { - return this.getParams(false, true); - } - - /** - * @see Method#getParamsForDeclaration() - */ - public String getParamsForDeclaration() { - return this.getParams(true, true); - } - - /** - * @see Method#getParamsForJavadoc() - */ - public String getParamsForJavadoc() { - return this.getParams(true, false); - } - - /** - * @see Method#getParameterImports() - */ - public Collection<String> getParameterImports() { - List<String> result = new ArrayList<String>(); - - List<SingleVariableDeclaration> parameters = method.parameters(); - for (SingleVariableDeclaration parameter : parameters) { - Type type = parameter.getType(); - getTypeImports(type, result); - } - - return result; - } - - /** - * @see Object#equals(Object) - */ - public boolean equals(Object o) { - Method obj = (Method) o; - return this.getName().equals(obj.getName()) && - this.getSignature().equals(obj.getSignature()); - } - - /** - * @see Object#hashCode() - */ - public int hashCode() { - return getName().hashCode() * getSignature().hashCode(); - } - - private String getParams(boolean types, boolean names) { - StringBuilder result = new StringBuilder(); - - Iterator<SingleVariableDeclaration> iterator = method.parameters().iterator(); - while (iterator.hasNext()) { - SingleVariableDeclaration parameter = iterator.next(); - - if (types) - result.append(parameter.getType()); - - if (types && names) - result.append(" "); //$NON-NLS-1$ - - if (names) - result.append(parameter.getName()); - - if (iterator.hasNext()) - result.append(", "); //$NON-NLS-1$ - } - - return result.toString(); - } - - private void getTypeImports(Type type, List<String> result) { - if (type.isArrayType()) { - getArrayTypeImports(type, result); - } else if (type.isParameterizedType()) { - getParameterizedTypeImports(type, result); - } else if (type.isPrimitiveType()) { - getPrimitiveTypeImports(type, result); - } else if (type.isSimpleType()) { - getSimpleTypeImports(type, result); - } else if (type.isQualifiedType()) { - getQualifiedTypeImports(type, result); - } else if (type.isWildcardType()) { - getWildcardTypeImports(type, result); - } - } - - private void getArrayTypeImports(Type type, List<String> result) { - ArrayType arrayType = (ArrayType) type; - Type componentType = arrayType.getComponentType(); - getTypeImports(componentType, result); - } - - private void getParameterizedTypeImports(Type type, List<String> result) { - ParameterizedType parameterizedType = (ParameterizedType) type; - - Type mainType = parameterizedType.getType(); - getTypeImports(mainType, result); - - List<Type> arguments = parameterizedType.typeArguments(); - for (Type argument : arguments) { - getTypeImports(argument, result); - } - } - - private void getPrimitiveTypeImports(Type type, List<String> result) { - // do nothing - no imports required for primitive types - } - - private void getSimpleTypeImports(Type type, List<String> result) { - ITypeBinding binding = type.resolveBinding(); - if (binding != null) - result.add(binding.getQualifiedName()); - } - - private void getQualifiedTypeImports(Type type, List<String> result) { - QualifiedType qualifiedType = (QualifiedType) type; - result.add(qualifiedType.getQualifier() + "." + qualifiedType.getName()); - } - - private void getWildcardTypeImports(Type type, List<String> result) { - WildcardType wildcardType = (WildcardType) type; - Type bound = wildcardType.getBound(); - if (bound != null) { - getTypeImports(bound, result); - } - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/UpdateJavaBuildPathOperation.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/UpdateJavaBuildPathOperation.java deleted file mode 100644 index 9ba62b9f5..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/common/operations/UpdateJavaBuildPathOperation.java +++ /dev/null @@ -1,272 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.common.operations; - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IProjectDescription; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.jdt.core.IClasspathEntry; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jst.j2ee.application.internal.operations.ClassPathSelection; -import org.eclipse.jst.j2ee.application.internal.operations.ClasspathElement; -import org.eclipse.wst.common.frameworks.internal.DoNotUseMeThisWillBeDeletedPost15; -import org.eclipse.wst.common.frameworks.internal.enablement.nonui.WFTWrappedException; -import org.eclipse.wst.common.frameworks.internal.operations.IHeadlessRunnableWithProgress; - -/** - * {@link DoNotUseMeThisWillBeDeletedPost15} - * - * @deprecated This should no longer be necessary because of the new EAR & Web Lib classpath - * containers - */ -public class UpdateJavaBuildPathOperation implements IHeadlessRunnableWithProgress { - protected IJavaProject javaProject; - protected ClassPathSelection classPathSelection; - // All the Java build path entries created by the classpath selection - protected Set allClasspathEntries; - protected List allUnselectedClasspathEntries; - - /** - * UpdateJavaBuildPathOperation constructor comment. - */ - public UpdateJavaBuildPathOperation(IJavaProject aJavaProject, ClassPathSelection aClassPathSelection) { - super(); - javaProject = aJavaProject; - classPathSelection = aClassPathSelection; - allClasspathEntries = new HashSet(); - IClasspathEntry[] classpathEntry = aClassPathSelection.getClasspathEntriesForSelected(); - if (classpathEntry != null) - allClasspathEntries.addAll(Arrays.asList(classpathEntry)); - } - - /** - * UpdateJavaBuildPathOperation constructor comment. - */ - public UpdateJavaBuildPathOperation(IJavaProject aJavaProject, ClassPathSelection selected, ClassPathSelection unselected) { - super(); - javaProject = aJavaProject; - classPathSelection = selected; - allClasspathEntries = new HashSet(); - if (selected != null && !selected.getClasspathElements().isEmpty()) - allClasspathEntries.addAll(Arrays.asList(selected.getClasspathEntriesForSelected())); - - allUnselectedClasspathEntries = new ArrayList(); - if (unselected != null && !unselected.getClasspathElements().isEmpty()) - allUnselectedClasspathEntries.addAll(unselected.getClasspathElements()); - } - - public UpdateJavaBuildPathOperation(IJavaProject aJavaProject, ClassPathSelection selected, List unselected) { - super(); - javaProject = aJavaProject; - classPathSelection = selected; - allClasspathEntries = new HashSet(); - if (selected != null && !selected.getClasspathElements().isEmpty()) - allClasspathEntries.addAll(Arrays.asList(selected.getClasspathEntriesForSelected())); - - allUnselectedClasspathEntries = new ArrayList(); - if (unselected != null && !unselected.isEmpty()) - allUnselectedClasspathEntries.addAll(unselected); - } - - protected void ensureClasspathEntryIsExported(List cp, IClasspathEntry entry) { - if (entry.isExported()) - return; - int index = getIndex(cp, entry); - IClasspathEntry newEntry = null; - switch (entry.getEntryKind()) { - case IClasspathEntry.CPE_PROJECT : - newEntry = JavaCore.newProjectEntry(entry.getPath(), true); - break; - case IClasspathEntry.CPE_LIBRARY : - newEntry = JavaCore.newLibraryEntry(entry.getPath(), entry.getSourceAttachmentPath(), entry.getSourceAttachmentRootPath(), true); - break; - case IClasspathEntry.CPE_VARIABLE : - newEntry = JavaCore.newVariableEntry(entry.getPath(), entry.getSourceAttachmentPath(), entry.getSourceAttachmentRootPath()); - default : - break; - } - if (entry != null) - cp.set(index, newEntry); - } - - protected IClasspathEntry ensureElementInList(List cp, ClasspathElement element, IClasspathEntry predecessor) { - IClasspathEntry addedEntry = null; - // The element might have multiple entries in the case of - // the imported_classes.jar file - IClasspathEntry[] cpEntries = element.newClasspathEntries(); - if (cpEntries == null || cpEntries.length == 0) - // indicates an invalid entry - return null; - - int predecessorPos = predecessor == null ? -1 : getIndex(cp, predecessor); - addedEntry = cpEntries[0]; - // Ensure that the first item is in the list, and follows - // the predecessor if specified; preserve existing items in - // the case of source attachments - int pos = getIndex(cp, addedEntry); - if (pos == -1) { - if (predecessorPos == -1) - cp.add(addedEntry); - else - cp.add(predecessorPos + 1, addedEntry); - } else { - addedEntry = (IClasspathEntry) cp.get(pos); - if (pos < predecessorPos) { - cp.remove(addedEntry); - cp.add(predecessorPos, addedEntry); - } - } - ensureClasspathEntryIsExported(cp, addedEntry); - - // Remove and add so we can ensure the proper order; this - // is the case of the imported_classes.jar; we always want it - // directly after the project - for (int i = 1; i < cpEntries.length; i++) { - int index = getIndex(cp, cpEntries[i]); - if (index != -1) { - addedEntry = (IClasspathEntry) cp.get(index); - cp.remove(index); - } else - addedEntry = cpEntries[i]; - pos = getIndex(cp, cpEntries[0]); - cp.add(pos + 1, addedEntry); - } - return addedEntry; - } - - protected int getIndex(List cp, IClasspathEntry entry) { - for (int i = 0; i < cp.size(); i++) { - IClasspathEntry elmt = (IClasspathEntry) cp.get(i); - if (elmt.getPath().equals(entry.getPath())) - return i; - } - return -1; - } - - protected void ensureElementNotInList(List cp, ClasspathElement element) { - IClasspathEntry[] cpEntries = element.newClasspathEntries(); - if (cpEntries == null || cpEntries.length == 0) - return; - for (int i = 0; i < cpEntries.length; i++) { - if (allClasspathEntries.contains(cpEntries[i])) - // This may be included indirectly by a transitive dependency - continue; - int index = getIndex(cp, cpEntries[i]); - if (index != -1) - cp.remove(index); - } - } - - protected void ensureRemoveElementInList(List cp, ClasspathElement element) { - IClasspathEntry[] cpEntries = element.newClasspathEntries(); - if (cpEntries == null || cpEntries.length == 0) - return; - for (int i = 0; i < cpEntries.length; i++) { - if (cp.contains(cpEntries[i])) { - int index = getIndex(cp, cpEntries[i]); - if (index != -1) - cp.remove(index); - } - } - } - - /** - * Runs this operation. Progress should be reported to the given progress monitor. This method - * is usually invoked by an <code>IRunnableContext</code>'s<code>run</code> method, which - * supplies the progress monitor. A request to cancel the operation should be honored and - * acknowledged by throwing <code>InterruptedException</code>. - * - * @param monitor - * the progress monitor to use to display progress and receive requests for - * cancelation - * @exception InvocationTargetException - * if the run method must propagate a checked exception, it should wrap it inside - * an <code>InvocationTargetException</code>; runtime exceptions are - * automatically wrapped in an <code>InvocationTargetException</code> by the - * calling context - * @exception InterruptedException - * if the operation detects a request to cancel, using - * <code>IProgressMonitor.isCanceled()</code>, it should exit by throwing - * <code>InterruptedException</code> - * - * @see IRunnableContext#run - */ - public void run(org.eclipse.core.runtime.IProgressMonitor monitor) throws java.lang.reflect.InvocationTargetException, InterruptedException { - try { - String[] prevRequiredProjects = javaProject.getRequiredProjectNames(); - List cp = new ArrayList(Arrays.asList(javaProject.getRawClasspath())); - List classpathElements = classPathSelection.getClasspathElements(); - IClasspathEntry predecessor = null; - IClasspathEntry result = null; - for (int i = 0; i < classpathElements.size(); i++) { - ClasspathElement element = (ClasspathElement) classpathElements.get(i); - if (element.isSelected()) { - result = ensureElementInList(cp, element, predecessor); - if (result != null) - predecessor = result; - } else - ensureElementNotInList(cp, element); - } - filterUnselectedEntries(cp); - IClasspathEntry[] newCp = ((IClasspathEntry[]) cp.toArray(new IClasspathEntry[cp.size()])); - javaProject.setRawClasspath(newCp, monitor); - updateRequiredProjects(javaProject, prevRequiredProjects, new SubProgressMonitor(monitor, 1)); - } catch (Exception ex) { - throw new WFTWrappedException(ex); - } - } - - private void filterUnselectedEntries(List cp) { - if (allUnselectedClasspathEntries != null) { - for (int i = 0; i < allUnselectedClasspathEntries.size(); i++) { - ClasspathElement element = (ClasspathElement) allUnselectedClasspathEntries.get(i); - ensureRemoveElementInList(cp, element); - } - } - } - - protected void updateRequiredProjects(IJavaProject jproject, String[] prevRequiredProjects, IProgressMonitor monitor) throws CoreException { - String[] newRequiredProjects = jproject.getRequiredProjectNames(); - - ArrayList prevEntries = new ArrayList(Arrays.asList(prevRequiredProjects)); - ArrayList newEntries = new ArrayList(Arrays.asList(newRequiredProjects)); - - IProject proj = jproject.getProject(); - IProjectDescription projDesc = proj.getDescription(); - - ArrayList newRefs = new ArrayList(); - IProject[] referencedProjects = projDesc.getReferencedProjects(); - for (int i = 0; i < referencedProjects.length; i++) { - String curr = referencedProjects[i].getName(); - if (newEntries.remove(curr) || !prevEntries.contains(curr)) { - newRefs.add(referencedProjects[i]); - } - } - IWorkspaceRoot root = proj.getWorkspace().getRoot(); - for (int i = 0; i < newEntries.size(); i++) { - String curr = (String) newEntries.get(i); - newRefs.add(root.getProject(curr)); - } - projDesc.setReferencedProjects((IProject[]) newRefs.toArray(new IProject[newRefs.size()])); - proj.setDescription(projDesc, monitor); - } -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/DefaultWSDLServiceHelper.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/DefaultWSDLServiceHelper.java deleted file mode 100644 index 6e449ca54..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/DefaultWSDLServiceHelper.java +++ /dev/null @@ -1,147 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Feb 21, 2005 - * - * TODO To change the template for this generated file go to - * Window - Preferences - Java - Code Style - Code Templates - */ -package org.eclipse.jst.j2ee.internal.webservices; - -import java.util.List; -import java.util.Map; - -import org.eclipse.core.resources.IFile; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.resource.Resource; - -/** - * @author cbridgha - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Style - Code Templates - */ -public class DefaultWSDLServiceHelper implements WSDLServiceHelper { - - /** - * - */ - public DefaultWSDLServiceHelper() { - super(); - // TODO Auto-generated constructor stub - } - - /* (non-Javadoc) - * @see org.eclipse.jst.j2ee.internal.webservices.WSDLServiceHelper#getPortName(java.lang.Object) - */ - public String getPortName(Object port) { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.jst.j2ee.internal.webservices.WSDLServiceHelper#getServicePorts(java.lang.Object) - */ - public Map getServicePorts(Object aService) { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.jst.j2ee.internal.webservices.WSDLServiceHelper#getServiceNamespaceURI(java.lang.Object) - */ - public String getServiceNamespaceURI(Object aService) { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.jst.j2ee.internal.webservices.WSDLServiceHelper#getServiceDefinitionLocation(org.eclipse.emf.ecore.EObject) - */ - public Object getServiceDefinitionLocation(EObject aService) { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.jst.j2ee.internal.webservices.WSDLServiceHelper#getPortBindingNamespaceURI(java.lang.Object) - */ - public String getPortBindingNamespaceURI(Object aPort) { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.jst.j2ee.internal.webservices.WSDLServiceHelper#getServiceLocalPart(java.lang.Object) - */ - public String getServiceLocalPart(Object aService) { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.jst.j2ee.internal.webservices.WSDLServiceHelper#getServiceQName(java.lang.Object) - */ - public Object getServiceQName(Object aService) { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.jst.j2ee.internal.webservices.WSDLServiceHelper#getDefinitionServices(java.lang.Object) - */ - public Map getDefinitionServices(Object aDefinition) { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.jst.j2ee.internal.webservices.WSDLServiceHelper#getWSDLDefinition(java.lang.String) - */ - public Object getWSDLDefinition(String wsdlURL) { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.jst.j2ee.internal.webservices.WSDLServiceHelper#getWSDLDefinition(org.eclipse.emf.ecore.resource.Resource) - */ - public Object getWSDLDefinition(Resource wsdlResource) { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.jst.j2ee.internal.webservices.WSDLServiceHelper#getWsdlServicesFromWsilFile(org.eclipse.core.resources.IFile) - */ - public List getWsdlServicesFromWsilFile(IFile wsil) { - // TODO Auto-generated method stub - return null; - } - - public boolean isService(Object aService) { - // TODO Auto-generated method stub - return false; - } - public boolean isWSDLResource(Object aResource) { - // TODO Auto-generated method stub - return false; - } - public boolean isDefinition(Object aDefinition) { - // TODO Auto-generated method stub - return false; - } - - public List get13ServiceRefs(EObject j2eeObject) { - // TODO Auto-generated method stub - return null; - } -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WSDLServiceExtManager.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WSDLServiceExtManager.java deleted file mode 100644 index f6b9b00bd..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WSDLServiceExtManager.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.internal.webservices; - -public class WSDLServiceExtManager { - public static WSDLServiceHelper extension; - - public static WSDLServiceHelper getServiceHelper() { - if (extension == null) { - // Initialize the WSDL Service Registry to register extensions into this manager - WSDLServiceExtensionRegistry.getInstance(); - } - return extension; - } - - public static void registerWSDLServiceHelper(WSDLServiceHelper ext) { - extension = ext; - } - - public static void removeWSDLServiceHelper() { - extension = null; - } - - public WSDLServiceExtManager() { - super(); - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WSDLServiceExtensionRegistry.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WSDLServiceExtensionRegistry.java deleted file mode 100644 index c006c96e5..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WSDLServiceExtensionRegistry.java +++ /dev/null @@ -1,71 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Oct 29, 2003 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package org.eclipse.jst.j2ee.internal.webservices; - -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.jem.util.RegistryReader; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; - -/** - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class WSDLServiceExtensionRegistry extends RegistryReader { - - static final String EXTENSION_NAME = "WSDLServiceHelper"; //$NON-NLS-1$ - static final String ELEMENT_WSDL_HELPER = "wsdlHelper"; //$NON-NLS-1$ - static final String WSDL_HELPER_CLASS = "helperClass"; //$NON-NLS-1$ - private static WSDLServiceExtensionRegistry INSTANCE = null; - - public WSDLServiceExtensionRegistry() { - super(J2EEPlugin.PLUGIN_ID, EXTENSION_NAME); - } - - public static WSDLServiceExtensionRegistry getInstance() { - if (INSTANCE == null) { - INSTANCE = new WSDLServiceExtensionRegistry(); - INSTANCE.readRegistry(); - } - return INSTANCE; - } - - /** - * readElement() - parse and deal w/ an extension like: <earModuleExtension extensionClass = - * "com.ibm.etools.web.plugin.WebModuleExtensionImpl"/> - */ - public boolean readElement(IConfigurationElement element) { - if (!element.getName().equals(ELEMENT_WSDL_HELPER)) - return false; - WSDLServiceHelper extension = null; - try { - extension = (WSDLServiceHelper) element.createExecutableExtension(WSDL_HELPER_CLASS); - } catch (Throwable e) { - //Ignore - } - if (extension != null) - addModuleExtension(extension); - else // Register default do nothing helper...... - addModuleExtension(new DefaultWSDLServiceHelper()); - return true; - } - - - private static void addModuleExtension(WSDLServiceHelper ext) { - WSDLServiceExtManager.registerWSDLServiceHelper(ext); - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WSDLServiceHelper.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WSDLServiceHelper.java deleted file mode 100644 index be9521778..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WSDLServiceHelper.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Feb 21, 2005 - * - * TODO To change the template for this generated file go to - * Window - Preferences - Java - Code Style - Code Templates - */ -package org.eclipse.jst.j2ee.internal.webservices; - -import java.util.List; -import java.util.Map; - -import org.eclipse.core.resources.IFile; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.resource.Resource; - -/** - * @author cbridgha - * - * This interface is intended to expand the visibility of wsdl api, without a direct dependency - */ -public interface WSDLServiceHelper { - - public static final String WSIL_EXT = "wsil"; //$NON-NLS-1$ - - public String getPortName(Object port); - public Map getServicePorts(Object aService); - public String getServiceNamespaceURI(Object aService); - public Object getServiceDefinitionLocation(EObject aService); - public String getPortBindingNamespaceURI(Object aPort); - public String getServiceLocalPart(Object aService); - public Object getServiceQName(Object aService); - public Map getDefinitionServices(Object aDefinition); - public Object getWSDLDefinition(String wsdlURL); - public Object getWSDLDefinition(Resource wsdlResource); - public List getWsdlServicesFromWsilFile(IFile wsil); - public boolean isService(Object aService); - public boolean isWSDLResource(Object aResource); - public boolean isDefinition(Object aDefinition); - public List get13ServiceRefs(EObject j2eeObject); - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WebServiceClientGenerator.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WebServiceClientGenerator.java deleted file mode 100644 index 5797b899e..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WebServiceClientGenerator.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Apr 28, 2004 - */ -package org.eclipse.jst.j2ee.internal.webservices; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jst.j2ee.internal.common.J2EECommonMessages; - - -/** - * Extension for generating web service clients - */ -public abstract class WebServiceClientGenerator { - - public static final String GENERIC_J2EE_CONTAINER = J2EECommonMessages.WebServiceClientGenerator_UI_0; - - private List runtime = null; - - /** - * Generates Web service client artifacts based on information obatined from the dataModel - * (wsdlURL, serviceQName, outputWSDLFilePathName, projectName, shouldDeploy) After generating - * the Web service client artifacts, sets the following on the dataModel: serviceInterfaceName, - * serviceEndpointInterfaceName, didGenDescriptors - * - * @return Status for results - */ - public abstract IStatus genWebServiceClientArtifacts(WebServicesClientDataHelper dataModel); - - public void setRuntime(List serverTargets) { - runtime = serverTargets; - } - - public List getServerTargets() { - if (runtime == null) - runtime = new ArrayList(); - return runtime; - } - - public boolean isRuntimeSupported(String serverTargetID) { - return getServerTargets().contains(serverTargetID); - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WebServicesClientDataHelper.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WebServicesClientDataHelper.java deleted file mode 100644 index 909295edb..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WebServicesClientDataHelper.java +++ /dev/null @@ -1,78 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Apr 26, 2004 - */ -package org.eclipse.jst.j2ee.internal.webservices; - - -/** - * WebServicesClientDataHelper Interface Extension - For use in generating Web Service Clients by - * sharing data between J2EE operations and web services operations - */ -public interface WebServicesClientDataHelper { - - /** - * @return the URL for the associated original WSDL file referenced by the client - */ - public String getWSDLUrl(); - - /** - * @return the QName of form http://someNamespace:someLocalPart for the associated web service - * for the client - */ - public String getServiceQName(); - - /** - * @return the name of the target project for the web service client - */ - public String getProjectName(); - - /** - * @return the URI for the fileName path for the copied WSDL file into the client project - */ - public String getOutputWSDLFileName(); - - /** - * @return the qualified classname of the generated Service Interface - */ - public String getServiceInterfaceName(); - - /** - * @return the qualified classname of the generated Service Endpoint Interface - */ - public String[] getServiceEndpointInterfaceNames(); - - /** - * @return should generate code for deployment? - */ - public boolean shouldDeploy(); - - /** - * @return whether the extension generated the descriptors or not - */ - public boolean shouldGenDescriptors(); - - /** - * Set the SEI classname for the web service client - */ - public void setServiceInterfaceName(String name); - - /** - * Set the SI classname for the web service client - */ - public void setServiceEndpointInterfaceNames(String[] names); - - /** - * Set whether descriptors were generated - */ - public void setDidGenDescriptors(boolean b); -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WebServicesClientDataRegistry.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WebServicesClientDataRegistry.java deleted file mode 100644 index 67160f679..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/internal/webservices/WebServicesClientDataRegistry.java +++ /dev/null @@ -1,86 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Apr 26, 2004 - */ -package org.eclipse.jst.j2ee.internal.webservices; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.jem.util.RegistryReader; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; - -/** - * Read the WebServicesClientDataExtensions - */ -public class WebServicesClientDataRegistry extends RegistryReader { - - private static WebServicesClientDataRegistry INSTANCE = null; - public static final String WS_CLIENT_EXTENSION_POINT = "WebServiceClientGenerator"; //$NON-NLS-1$ - public static final String GENERATOR = "generator"; //$NON-NLS-1$ - public static final String CLASS_NAME = "className"; //$NON-NLS-1$ - public static final String SERVER_TARGET = "serverTarget"; //$NON-NLS-1$ - public static final String RUNTIME = "runtime"; //$NON-NLS-1$ - private List wsClientDataExtensions = null; - - /** - * Default constructor - */ - public WebServicesClientDataRegistry() { - super(J2EEPlugin.PLUGIN_ID, WS_CLIENT_EXTENSION_POINT); - } - - public static WebServicesClientDataRegistry getInstance() { - if (INSTANCE == null) { - INSTANCE = new WebServicesClientDataRegistry(); - INSTANCE.readRegistry(); - } - return INSTANCE; - } - - /** - * @see org.eclipse.wst.common.frameworks.internal.RegistryReader#readElement(org.eclipse.core.runtime.IConfigurationElement) - */ - public boolean readElement(IConfigurationElement element) { - if (!element.getName().equals(GENERATOR)) - return false; - // Get the class specified in the extension point - WebServiceClientGenerator helper = null; - try { - helper = (WebServiceClientGenerator) element.createExecutableExtension(CLASS_NAME); - // get server target runtimes - IConfigurationElement[] runtimes = element.getChildren(RUNTIME); - List runtimeList = new ArrayList(); - for (int i = 0; i < runtimes.length; i++) { - IConfigurationElement runtime = runtimes[i]; - String serverTarget = runtime.getAttribute(SERVER_TARGET); - runtimeList.add(serverTarget); - } - helper.setRuntime(runtimeList); - } catch (Exception e) { - e.printStackTrace(); - } - // Add data helper class to registry extensions list - if (helper != null) { - getWSClientGeneratorExtensions().add(helper); - return true; - } - return false; - } - - public List getWSClientGeneratorExtensions() { - if (wsClientDataExtensions == null) - wsClientDataExtensions = new ArrayList(); - return wsClientDataExtensions; - } -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/IEARModelProvider.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/IEARModelProvider.java deleted file mode 100644 index 098171b31..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/IEARModelProvider.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.model; - - -import org.eclipse.core.resources.IProject; -import org.eclipse.wst.common.componentcore.resources.IVirtualComponent; - -/** - * In progress... Simple interface that serves to unify the various model access api's - * - */ -public interface IEARModelProvider extends IModelProvider { - - /** - * This provides a way to get module URIs from the appropriate model context - */ - public String getModuleURI(IVirtualComponent moduleComp); - - /** - * This method will return the context root in this application for the passed in web project. - * - * @param webProject - * @return contextRoot String - */ - public String getWebContextRoot(IProject webProject); - - /** - * This method will set the context root on the application for the passed in contextRoot. - * - * @param webProject - * @param aContextRoot - */ - public void setWebContextRoot(IProject webProject, String aContextRoot); -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/IModelProvider.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/IModelProvider.java deleted file mode 100644 index b588d0d19..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/IModelProvider.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.model; - -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Path; - -/** - * Simple J2EE model registration interface that serves to unify the various model access api's - * - */ -public interface IModelProvider { - - // Flag used to save in memory model when no file exists. - final static IPath FORCESAVE = new Path("FORCE"); //$NON-NLS-1$ - - /** - * This returns the designated "default" model for the given context - * @return Object - */ - Object getModelObject(); - /** - * This returns the model specifically for a given path within the model context, path can also be used - * to designate the source of the model (xml, java annotations, etc..) - * @param modelPath - * @return Object - */ - Object getModelObject(IPath modelPath); - /** - * The modify method should be used during a write operation on the model. - * The model will be properly accessed, saved and released - * Note: All implementors need to ensure all model access using this instance within the runnable block - * Use a cached/consistent view of the model that is being modified - * This method does not support nested writable views, and should return a RuntimeException if this is detected - * @param runnable {@link Runnable} - User specified code that alters the model. - * @param modelPath {@link IPath} - Optional path to specify which model instance will be modified - */ - void modify(Runnable runnable, IPath modelPath); - - /** - * Validate edit for resource state - * - * @param modelPath - Path of resource verifying, or null if default resource. - * @param context - The context object to help display dialogs etc, or null, then IWorkspace.VALIDATE_PROMPT will be used - * @return IStatus - */ - IStatus validateEdit(IPath modelPath, Object context); - - /** - * Add a listener to listen for model changes. - * @param listener - */ - void addListener(IModelProviderListener listener); - - /** - * Remove a listener from the list of model change listeners - * @param listener - */ - void removeListener(IModelProviderListener listener); -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/IModelProviderEvent.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/IModelProviderEvent.java deleted file mode 100644 index 9cd1ab7c1..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/IModelProviderEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.eclipse.jst.j2ee.model; - -import java.util.Collection; -import java.util.List; - -import org.eclipse.core.resources.IProject; - -public interface IModelProviderEvent { - - // Used when the edit model is saved. - public static final int SAVE = 0x1; - // Used when the command stack becomes dirty. - public static final int DIRTY = 0x2; - // Used when a referenced resource is removed from the ResourceSet. - public static final int REMOVED_RESOURCE = 0x4; - // Used when a referenced resource is added to the ResourceSet. - public static final int ADDED_RESOURCE = 0x8; - // Used when the edit model is disposed - public static final int PRE_DISPOSE = 0x10; - // Used when a Resource is loaded or the first object - // is added to the contents when created. - public static final int LOADED_RESOURCE = 0x20; - // Used when a Resource is unloaded. - public static final int UNLOADED_RESOURCE = 0x40; - // Indicates that the list of known resources managed by the edit model is about to change - public static final int KNOWN_RESOURCES_ABOUT_TO_CHANGE = 0x80; - // Indicates that the list of known resources managed by the edit model has changed - public static final int KNOWN_RESOURCES_CHANGED = 0x100; - - public abstract void addResource(Object aResource); - - public abstract void addResources(Collection<Object> someResources); - - public abstract List<Object> getChangedResources(); - - public abstract IModelProvider getModel(); - - public abstract IProject getProject(); - - public abstract int getEventCode(); - - public abstract void setChangedResources(List<Object> newChangedResources); - - public abstract void setModel(IModelProvider newModel); - - public abstract void setProject(IProject project); - - public abstract void setEventCode(int newEventCode); - -}
\ No newline at end of file diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/IModelProviderFactory.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/IModelProviderFactory.java deleted file mode 100644 index 9539fdc1c..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/IModelProviderFactory.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.model; - -import org.eclipse.core.resources.IProject; -import org.eclipse.wst.common.componentcore.resources.IVirtualComponent; - -/** - * Factory interface for creating IModelProvider instances. - * These factories are registered for a specific model domain/version - * - */ -public interface IModelProviderFactory { - - /** - * @param aProject {@link IProject} - * @return {@link IModelProvider} - */ - IModelProvider create (IProject aProject); - /** - * @param aComponent {@link IVirtualComponent} - * @return {@link IModelProvider} - */ - IModelProvider create (IVirtualComponent aComponent); - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/IModelProviderListener.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/IModelProviderListener.java deleted file mode 100644 index a5b58f2e0..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/IModelProviderListener.java +++ /dev/null @@ -1,19 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.j2ee.model; - - -public interface IModelProviderListener { - /** - * Tell listeners about model changes - */ - public void modelsChanged(IModelProviderEvent event); -}
\ No newline at end of file diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/J2EEModelProviderRegistry.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/J2EEModelProviderRegistry.java deleted file mode 100644 index 2b92311f6..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/J2EEModelProviderRegistry.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Licensed Material - Property of IBM - * (C) Copyright IBM Corp. 2001, 2005 - All Rights Reserved. - * US Government Users Restricted Rights - Use, duplication or disclosure - * restricted by GSA ADP Schedule Contract with IBM Corp. - */ -package org.eclipse.jst.j2ee.model; - -import java.util.StringTokenizer; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.jem.util.RegistryReader; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; -import org.eclipse.wst.common.project.facet.core.IProjectFacet; -import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion; -import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager; - -/** - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class J2EEModelProviderRegistry extends RegistryReader { - - static final String EXTENSION_NAME = "J2EEModelProvider"; //$NON-NLS-1$ - static final String ELEMENT_providers = "provider"; //$NON-NLS-1$ - static final String MODEL_PROVIDER = "modelProvider"; //$NON-NLS-1$ - static final String PROVIDER_FACTORY_CLASS = "factoryClass"; //$NON-NLS-1$ - static final String PROVIDER_PRIORITY = "priority"; //$NON-NLS-1$ - static final String PROVIDER_FACET = "facet"; //$NON-NLS-1$ - static final String PROVIDER_FACET_ID = "id"; //$NON-NLS-1$ - static final String PROVIDER_FACET_VERSION = "versions"; //$NON-NLS-1$ - private static J2EEModelProviderRegistry INSTANCE = null; - - public J2EEModelProviderRegistry() { - super(J2EEPlugin.PLUGIN_ID, EXTENSION_NAME); - } - - public static J2EEModelProviderRegistry getInstance() { - if (INSTANCE == null) { - INSTANCE = new J2EEModelProviderRegistry(); - INSTANCE.readRegistry(); - } - return INSTANCE; - } - - - public boolean readElement(IConfigurationElement element) { - String priority = null; - if (!element.getName().equals(ELEMENT_providers)) - return false; - - IModelProviderFactory factory = null; - IConfigurationElement[] mp = element.getChildren(MODEL_PROVIDER); - try { - factory = (IModelProviderFactory) mp[0].createExecutableExtension(PROVIDER_FACTORY_CLASS); - } catch (CoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - if (factory != null) { //Optionally read priority if to override providers for type - priority = mp[0].getAttribute(PROVIDER_PRIORITY); - } - if (factory != null) { - IConfigurationElement[] facet = element.getChildren(PROVIDER_FACET); - String facetId = facet[0].getAttribute(PROVIDER_FACET_ID); - IProjectFacet pv = ProjectFacetsManager.getProjectFacet(facetId); - if (pv == null) { - System.out.println("Unrecognized facet: " + facetId); - return true; // Unrecognized facet - } - String facetVersions = facet[0].getAttribute(PROVIDER_FACET_VERSION); - StringTokenizer tokens = new StringTokenizer(facetVersions,","); - while (tokens.hasMoreElements()) { - String facetversion = (String) tokens.nextElement(); - IProjectFacetVersion fv = pv.getVersion(facetversion); - if (fv != null) - addModelProvider(factory, fv, priority); - } - - - } - return true; - } - - - private static void addModelProvider(IModelProviderFactory provider, IProjectFacetVersion version, String priority) { - // Check priority of existing provider for override - ModelProviderManager.registerProvider(provider,version,priority); - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/ModelProviderEvent.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/ModelProviderEvent.java deleted file mode 100644 index 350f68d10..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/ModelProviderEvent.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.eclipse.jst.j2ee.model; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.eclipse.core.resources.IProject; - -public class ModelProviderEvent implements IModelProviderEvent { - - private IModelProvider model; - private IProject proj; - private int event; - private List changedResources = new ArrayList(); - - public ModelProviderEvent(int anEventCode, IModelProvider model, IProject proj) { - setEventCode(anEventCode); - setModel(model); - setProject(proj); - } - - public void setProject(IProject project) { - proj = project; - - } - - public void addResource(Object resource) { - changedResources.add(resource); - - } - - public void addResources(Collection<Object> someResources) { - changedResources.addAll(someResources); - - } - - public List<Object> getChangedResources() { - - return changedResources; - } - - public int getEventCode() { - // TODO Auto-generated method stub - return event; - } - - public IModelProvider getModel() { - - return model; - } - - public void setChangedResources(List<Object> newChangedResources) { - changedResources = newChangedResources; - - } - - public void setEventCode(int newEventCode) { - event = newEventCode; - - } - - public void setModel(IModelProvider newModel) { - model = newModel; - - } - - public IProject getProject() { - return proj; - } - -} diff --git a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/ModelProviderManager.java b/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/ModelProviderManager.java deleted file mode 100644 index 6feba9b96..000000000 --- a/plugins/org.eclipse.jst.j2ee/common/org/eclipse/jst/j2ee/model/ModelProviderManager.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Licensed Material - Property of IBM - * (C) Copyright IBM Corp. 2001, 2005 - All Rights Reserved. - * US Government Users Restricted Rights - Use, duplication or disclosure - * restricted by GSA ADP Schedule Contract with IBM Corp. - */ -package org.eclipse.jst.j2ee.model; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.WeakHashMap; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.emf.common.notify.Adapter; -import org.eclipse.emf.common.notify.Notification; -import org.eclipse.emf.common.notify.impl.AdapterImpl; -import org.eclipse.emf.ecore.resource.Resource; -import org.eclipse.emf.ecore.resource.ResourceSet; -import org.eclipse.jem.util.logger.proxy.Logger; -import org.eclipse.jst.j2ee.internal.common.J2EECommonMessages; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; -import org.eclipse.jst.j2ee.internal.project.J2EEProjectUtilities; -import org.eclipse.wst.common.componentcore.resources.IVirtualComponent; -import org.eclipse.wst.common.internal.emf.resource.CompatibilityXMIResource; -import org.eclipse.wst.common.internal.emfworkbench.WorkbenchResourceHelper; -import org.eclipse.wst.common.project.facet.core.IFacetedProject; -import org.eclipse.wst.common.project.facet.core.IProjectFacet; -import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion; -import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager; - -public class ModelProviderManager { - -public static class ModelProviderKey { - - protected IProjectFacetVersion version; - protected int priority; - - public ModelProviderKey() { - super(); - } - public boolean equals(Object aOther){ - if( this == aOther ) - return true; - - ModelProviderKey otherKey = (ModelProviderKey)aOther; - if( version.equals( otherKey.version) ) - return true; - return false; - } - - public int hashCode() { - return version.hashCode(); - } - } -private static class ResourceSetListener extends AdapterImpl { - /* - * @see Adapter#notifyChanged(new ENotificationImpl((InternalEObject)Notifier, - * int,(EStructuralFeature) EObject, Object, Object, int)) - */ - public void notifyChanged(Notification notification) { - switch (notification.getEventType()) { - case Notification.ADD : - addedResource((Resource) notification.getNewValue()); - break; - case Notification.REMOVE : - removedResource((Resource) notification.getOldValue()); - break; - case Notification.REMOVE_MANY : - removedResources((List) notification.getOldValue()); - break; - } - } -} -private static WeakHashMap modelsProviders = new WeakHashMap(); -private static final int DEFAULT_PRIORITY = 100; -private static HashMap providers; -protected static HashMap resourceSetListeners; - - /** - * - * @param - * @param - * @return IModelProvider for the given project of the given version, NULL if no IModelProvider exists for project, version pair - */ - public static IModelProvider getModelProvider(IProject project, IProjectFacetVersion vers) { - - IModelProviderFactory factory = getProvider(vers); - if(factory != null){ - startListeningToResourceSet(project); - return factory.create(project); - } - - String errorMessage = J2EECommonMessages.getResourceString( - J2EECommonMessages.ERR_NO_MODEL_PROVIDER_FOR_PROJECT, new Object[] {project, vers}); - Throwable error = new NullPointerException(errorMessage); - - J2EEPlugin.INSTANCE.getLogger().logError(error); - - return null; - } - - - /** - * - * @param - * @param - * @return IModelProvider for the given component of the given version, NULL if no IModelProvider exists for virtual component/version pair - */ - public static IModelProvider getModelProvider(IVirtualComponent aModule, IProjectFacetVersion vers) { - - IModelProviderFactory factory = getProvider(vers); - if(factory != null){ - IModelProvider mp = factory.create(aModule); - addProvider(mp); - return mp; - } - - String errorMessage = J2EECommonMessages.getResourceString( - J2EECommonMessages.ERR_NO_MODEL_PROVIDER_FOR_PROJECT, new Object[] {aModule, vers}); - Throwable error = new NullPointerException(errorMessage); - - J2EEPlugin.INSTANCE.getLogger().logError(error); - - return null; - } - - - private static void addProvider(IModelProvider mp) { - modelsProviders.put(mp, null); - - } - - /** - * Notify all editModels of the change. - */ - private static void addedResource(Resource addedResource) { - if ((addedResource != null) && (addedResource instanceof CompatibilityXMIResource)) - ((CompatibilityXMIResource) addedResource).setFormat(CompatibilityXMIResource.FORMAT_MOF5); - IProject proj = WorkbenchResourceHelper.getProject(addedResource); - IModelProviderEvent event = new ModelProviderEvent(IModelProviderEvent.ADDED_RESOURCE, null,proj); - event.addResource(addedResource); - notifyModelProviders(event); - - } - /** - * Notify all editModels of the change. - */ - protected static void notifyModelProviders(IModelProviderEvent anEvent) { - if ((anEvent == null) || (modelsProviders.size() == 0)) - return; - List aList = new ArrayList(); - synchronized (modelsProviders) { - aList.addAll(modelsProviders.keySet()); - } - - for (int i = 0; i < aList.size(); i++) { - IModelProvider mod; - mod = (IModelProvider) aList.get(i); - try { - if (mod instanceof IModelProviderListener) - { - ((IModelProviderListener)mod).modelsChanged(anEvent); - } - } catch (Exception e) { - Logger.getLogger().logError(e); - } - } - } - - /** - * Notify all editModels of the change. - */ - private static void removedResource(Resource removedResource) { - IProject proj = WorkbenchResourceHelper.getProject(removedResource); - IModelProviderEvent event = new ModelProviderEvent(IModelProviderEvent.REMOVED_RESOURCE, null,proj); - event.addResource(removedResource); - notifyModelProviders(event); - - } - - /** - * Notify all editModels of the change. - */ - private static void removedResources(List removedResources) { - Resource firstRes = (Resource)removedResources.get(0); - IProject proj = WorkbenchResourceHelper.getProject(firstRes); - IModelProviderEvent event = new ModelProviderEvent(IModelProviderEvent.REMOVED_RESOURCE, null,proj); - event.addResources(removedResources); - notifyModelProviders(event); - - } - - /** - * Used to register an IModelProviderFactory against a facet version - * - * @param providerFactory - * - {@link IModelProviderFactory} - * @param v - * - {@link IProjectFacetVersion} - * @param priority - * - {@link String}- Used to allow multiple instances, the - * highest priority is chosen. Priority '0' is higher that - * priority '1'. If priorities are equal the new providerFactory - * is chosen. - */ - public static void registerProvider(IModelProviderFactory providerFactory, IProjectFacetVersion v, String priority) { - - int newPriority = (priority != null) ? Integer.parseInt(priority) : DEFAULT_PRIORITY; - int currentPriority = getProviderPriority(v); - if (newPriority <= currentPriority) { - ModelProviderKey key = createProviderKey(v, newPriority); - getProviders().put(key, providerFactory); - } - } - - private static IModelProviderFactory getProvider(IProjectFacetVersion v) { - Set<ModelProviderKey> keys = getProviders().keySet(); - for (Iterator iterator = keys.iterator(); iterator.hasNext();) { - ModelProviderKey key = (ModelProviderKey) iterator.next(); - if (key.version.equals(v)) - return (IModelProviderFactory)providers.get(key); - } - return null; - } - private static int getProviderPriority(IProjectFacetVersion v) { - Set<ModelProviderKey> keys = getProviders().keySet(); - for (Iterator iterator = keys.iterator(); iterator.hasNext();) { - ModelProviderKey key = (ModelProviderKey) iterator.next(); - if (key.version.equals(v)) - return key.priority; - } - return DEFAULT_PRIORITY; - } - protected static Adapter getResourceSetListener(IProject project) { - if (resourceSetListeners == null) - resourceSetListeners = new HashMap(); - Adapter listener = (Adapter)resourceSetListeners.get(project); - if (listener == null) { - listener = new ResourceSetListener(); - resourceSetListeners.put(project, listener); - } - return listener; - } - - private static J2EEModelProviderRegistry registry; - - - private static void initProviders() { - providers = new HashMap(); - registry = J2EEModelProviderRegistry.getInstance(); - - } - private static void startListeningToResourceSet(IProject project) { - ResourceSet set = WorkbenchResourceHelper.getResourceSet(project); - Adapter listener = getResourceSetListener(project); - if (set != null && !set.eAdapters().contains(listener)) - set.eAdapters().add(listener); - } - private static ModelProviderKey createProviderKey(IProjectFacetVersion fv, int priority) { - ModelProviderKey key = new ModelProviderKey(); - key.priority = priority; - key.version = fv; - return key; - } - - public static IModelProvider getModelProvider(IProject proj) { - IProjectFacetVersion facetVersion = getDefaultFacet(proj); - return getModelProvider(proj, facetVersion); - - } - - public static IModelProvider getModelProvider(IVirtualComponent aModule) { - IProjectFacetVersion facetVersion = getDefaultFacet(aModule); - return getModelProvider(aModule, facetVersion); - } - - private static IProjectFacetVersion getDefaultFacet(IProject proj) { - String type = J2EEProjectUtilities.getJ2EEProjectType(proj); - IProjectFacet facet = ProjectFacetsManager.getProjectFacet(type); - IFacetedProject fp = null; - try { - fp = ProjectFacetsManager.create(proj); - } catch (CoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - if (fp != null && facet != null) { - return fp.getInstalledVersion(facet); - } - return null; - - } - - private static IProjectFacetVersion getDefaultFacet(IVirtualComponent aModule) { - String type = J2EEProjectUtilities.getJ2EEComponentType(aModule); - IProjectFacet facet = ProjectFacetsManager.getProjectFacet(type); - IFacetedProject fp = null; - try { - if (aModule.isBinary()) - { - - } - else - { - fp = ProjectFacetsManager.create(aModule.getProject()); - } - } catch (CoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - if (fp != null && facet != null) { - return fp.getInstalledVersion(facet); - } - return null; - } - - private static HashMap<ModelProviderKey, IModelProviderFactory> getProviders() { - if (registry == null) - initProviders(); - return providers; - } - -} |