diff options
Diffstat (limited to 'jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards')
22 files changed, 0 insertions, 6101 deletions
diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/DatabaseSchemaWizardPage.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/DatabaseSchemaWizardPage.java deleted file mode 100644 index 4b459e9b19..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/DatabaseSchemaWizardPage.java +++ /dev/null @@ -1,441 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2009 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: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.ui.internal.wizards; - -import java.util.EventListener; -import java.util.Iterator; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.preference.PreferenceDialog; -import org.eclipse.jface.wizard.WizardPage; -import org.eclipse.jpt.core.JpaProject; -import org.eclipse.jpt.db.ConnectionAdapter; -import org.eclipse.jpt.db.ConnectionListener; -import org.eclipse.jpt.db.ConnectionProfile; -import org.eclipse.jpt.db.Schema; -import org.eclipse.jpt.db.SchemaContainer; -import org.eclipse.jpt.ui.internal.JpaHelpContextIds; -import org.eclipse.jpt.ui.internal.JptUiMessages; -import org.eclipse.jpt.ui.internal.properties.JpaProjectPropertiesPage; -import org.eclipse.jpt.utility.internal.ListenerList; -import org.eclipse.jpt.utility.internal.iterators.EmptyIterator; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Link; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.dialogs.PreferencesUtil; - -/** - * Most of the behavior is in DatabaseGroup.... - * - * We open the wizard page with the JPA project's connection profile and - * default schema selected (if possible), but then the selections are driven - * by the user. If the user re-selects the JPA project's connection profile, - * we will pre-select the project's default schema if possible. - */ -public class DatabaseSchemaWizardPage extends WizardPage { - - final JpaProject jpaProject; - - private final ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); - - private DatabaseGroup databaseGroup; - - - public DatabaseSchemaWizardPage(JpaProject jpaProject) { - super("Database Schema"); //$NON-NLS-1$ - if (jpaProject == null) { - throw new NullPointerException(); - } - this.jpaProject = jpaProject; - this.setTitle(JptUiMessages.DatabaseSchemaWizardPage_title); - this.setMessage(JptUiMessages.DatabaseSchemaWizardPage_desc); - } - - public void createControl(Composite parent) { - this.setPageComplete(false); - this.setControl(this.buildTopLevelControl(parent)); - } - - private Control buildTopLevelControl(Composite parent) { - Composite composite = new Composite(parent, SWT.NULL); - composite.setLayout(new GridLayout()); - this.databaseGroup = new DatabaseGroup(composite); - Dialog.applyDialogFont(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, JpaHelpContextIds.PROPERTIES_JAVA_PERSISTENCE_CONNECTION); - return composite; - } - - public ConnectionProfile getJpaProjectConnectionProfile() { - return this.jpaProject.getConnectionProfile(); - } - - public Schema getSelectedSchema() { - return this.databaseGroup.getSelectedSchema(); - } - - @Override - public void dispose() { - this.databaseGroup.dispose(); - super.dispose(); - } - - - // ********** listeners ********** - - public void addListener(Listener listener) { - this.listenerList.add(listener); - } - - public void removeListener(Listener listener) { - this.listenerList.remove(listener); - } - - void fireSchemaChanged(Schema schema) { - this.setPageComplete(schema != null); - for (Listener listener : this.listenerList.getListeners()) { - listener.selectedSchemaChanged(schema); - } - } - - - // ********** listener interface ********** - - /** - * Allows clients to listen for changes to the selected connection profile - * and schema. - */ - public interface Listener extends EventListener { - void selectedSchemaChanged(Schema schema); - } - - - // ********** database group ********** - - /** - * schema combo-box - * add project connection link - * reconnect link - */ - class DatabaseGroup { - - // these are kept in synch with the selection - private Schema selectedSchema; - - private final Combo schemaComboBox; - - private final Link reconnectLink; - - private Link addJpaProjectConnectionLink; - - private final ConnectionListener connectionListener; - - - // ********** construction ********** - - DatabaseGroup(Composite composite) { - super(); - - Group group = new Group(composite, SWT.NONE); - group.setLayout(new GridLayout(2, false)); // false = do not make columns equal width - group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - group.setText(JptUiMessages.DatabaseSchemaWizardPage_schemaSettings); - // TODO PlatformUI.getWorkbench().getHelpSystem().setHelp(this.group, JpaHelpContextIds.XXX); - - // schema combo-box - this.buildLabel(group, 1, JptUiMessages.DatabaseSchemaWizardPage_schema); - this.schemaComboBox = this.buildComboBox(group, this.buildSchemaComboBoxSelectionListener()); - - String message = (this.projectHasAConnection()) ? - JptUiMessages.DatabaseSchemaWizardPage_schemaInfo : - JptUiMessages.DatabaseSchemaWizardPage_connectionInfo; - - this.buildLabel(group, 2, message); - - // add project's connection link - if( ! this.projectHasAConnection()) { - this.addJpaProjectConnectionLink = this.buildLink(group, - JptUiMessages.DatabaseSchemaWizardPage_addConnectionToProject, - this.buildAddJpaProjectConnectionLinkListener()); - } - - // reconnect link - this.reconnectLink = this.buildLink(group, JptUiMessages.DatabaseSchemaWizardPage_connectLink, this.buildReconnectLinkSelectionListener()); - this.reconnectLink.setEnabled(true); - - this.selectedSchema = this.getDefaultSchema(); - - if (this.selectedSchema != null) { - DatabaseSchemaWizardPage.this.fireSchemaChanged(this.selectedSchema); - } - - this.connectionListener = this.buildConnectionListener(); - this.addJpaProjectConnectionProfileListener(this.connectionListener); - - this.updateSchemaComboBox(); - this.updateReconnectLink(); - } - - - // ********** intra-wizard methods ********** - - Schema getSelectedSchema() { - return this.selectedSchema; - } - - void dispose() { - if(this.projectHasAConnection()) { - this.getJpaProjectConnectionProfile().removeConnectionListener(this.connectionListener); - } - } - - - // ********** internal methods ********** - - private void addJpaProjectConnectionListener() { - this.addJpaProjectConnectionProfileListener(this.connectionListener); - } - - - private void addJpaProjectConnectionProfileListener(ConnectionListener listener) { - if(this.projectHasAConnection()) { - this.getJpaProjectConnectionProfile().addConnectionListener(listener); - } - } - - private boolean projectHasAConnection() { - return this.getJpaProjectConnectionProfile() != null; - } - - /** - * this can return null; - * called at start-up and when the selected connection profile changes - */ - private ConnectionProfile getJpaProjectConnectionProfile() { - return DatabaseSchemaWizardPage.this.jpaProject.getConnectionProfile(); - } - - /** - * this can return null; - * called at start-up and when the selected connection profile changes - */ - private Schema getDefaultSchema() { - return DatabaseSchemaWizardPage.this.jpaProject.getDefaultDbSchema(); - } - - /** - * called at start-up and when the selected connection profile changes - */ - private void updateReconnectLink() { - this.reconnectLink.setEnabled(this.reconnectLinkCanBeEnabled()); - } - - private void updateAddJpaProjectConnectionLink() { - this.addJpaProjectConnectionLink.setEnabled(this.addJpaProjectConnectionLinkCanBeEnabled()); - } - - private boolean reconnectLinkCanBeEnabled() { - if(this.projectHasAConnection()) { - return this.getJpaProjectConnectionProfile().isInactive(); - } - return false; - } - - private boolean addJpaProjectConnectionLinkCanBeEnabled() { - return ! this.projectHasAConnection(); - } - - /** - * the schema combo-box is updated at start-up and - * when the selected connection profile changes - */ - private void updateSchemaComboBox() { - this.schemaComboBox.removeAll(); - for (Iterator<String> stream = this.getSchemata(); stream.hasNext(); ) { - this.schemaComboBox.add(stream.next()); - } - // the current schema *should* be in the current connection profile - if (this.selectedSchema != null) { - this.schemaComboBox.select(this.schemaComboBox.indexOf(this.selectedSchema.getIdentifier())); - } - } - - private Iterator<String> getSchemata() { - SchemaContainer sc = DatabaseSchemaWizardPage.this.jpaProject.getDefaultDbSchemaContainer(); - return (sc == null) ? EmptyIterator.<String>instance() : sc.sortedSchemaIdentifiers(); - } - - // ********** listener callbacks ********** - - void selectedSchemaChanged() { - Schema old = this.selectedSchema; - this.selectedSchema = this.getJpaProjectConnectionProfile().getDatabase().getSchemaForIdentifier(this.schemaComboBox.getText()); - if (this.selectedSchema != old) { - DatabaseSchemaWizardPage.this.fireSchemaChanged(this.selectedSchema); - } - } - - void reconnect() { - this.getJpaProjectConnectionProfile().connect(); - // everything should be synchronized when we get the resulting open event - } - - /** - * called when - * - a connection is set to the Jpa project - * - the connection was opened - * - the connection was closed (never happens?) - * we need to update the schema stuff and the reconnect link - */ - void connectionChanged() { - Schema old = this.selectedSchema; - this.selectedSchema = this.getDefaultSchema(); - if (this.selectedSchema != old) { - DatabaseSchemaWizardPage.this.fireSchemaChanged(this.selectedSchema); - } - this.updateSchemaComboBox(); - this.updateReconnectLink(); - } - - - // ********** listeners ********** - - private SelectionListener buildSchemaComboBoxSelectionListener() { - return new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent event) { - // nothing special for "default" (double-click?) - this.widgetSelected(event); - } - public void widgetSelected(SelectionEvent event) { - DatabaseGroup.this.selectedSchemaChanged(); - } - @Override - public String toString() { - return "DatabaseSchemaWizardPage schema combo-box selection listener"; //$NON-NLS-1$ - } - }; - } - - private SelectionListener buildReconnectLinkSelectionListener() { - return new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - DatabaseGroup.this.reconnect(); - } - @Override - public String toString() { - return "DatabaseSchemaWizardPage reconnect link selection listener"; //$NON-NLS-1$ - } - }; - } - - private ConnectionListener buildConnectionListener() { - return new ConnectionAdapter() { - @Override - public void opened(ConnectionProfile cp) { - this.connectionChanged(); - } - @Override // this probably won't ever get called... - public void closed(ConnectionProfile cp) { - this.connectionChanged(); - } - private void connectionChanged() { - Display.getDefault().asyncExec( - new Runnable() { - public void run() { - DatabaseGroup.this.connectionChanged(); - } - } - ); - } - @Override - public String toString() { - return "DatabaseSchemaWizardPage connection listener"; //$NON-NLS-1$ - } - }; - } - - private SelectionListener buildAddJpaProjectConnectionLinkListener() { - return new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - DatabaseGroup.this.promptToConfigJpaProjectConnection(); - - DatabaseGroup.this.addJpaProjectConnectionListener(); - DatabaseGroup.this.updateAddJpaProjectConnectionLink(); - DatabaseGroup.this.connectionChanged(); - } - @Override - public String toString() { - return "DatabaseSchemaWizardPage AddProjectConnection link selection listener"; //$NON-NLS-1$ - } - }; - } - - private void promptToConfigJpaProjectConnection() { - PreferenceDialog dialog = - PreferencesUtil.createPropertyDialogOn( - getShell(), DatabaseSchemaWizardPage.this.jpaProject.getProject(), - JpaProjectPropertiesPage.PROP_ID, - null, - null); - dialog.open(); - } - - // ********** UI components ********** - - /** - * build and return a label - */ - private Label buildLabel(Composite parent, int span, String text) { - Label label = new Label(parent, SWT.NONE); - label.setText(text); - GridData gd = new GridData(); - gd.horizontalSpan = span; - label.setLayoutData(gd); - return label; - } - - /** - * build and return a combo-box - */ - private Combo buildComboBox(Composite parent, SelectionListener listener) { - Combo combo = new Combo(parent, SWT.BORDER | SWT.READ_ONLY); - combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - combo.addSelectionListener(listener); - return combo; - } - - /** - * build and return a link - */ - private Link buildLink(Composite parent, String text, SelectionListener listener) { - Link link = new Link(parent, SWT.NONE); - GridData data = new GridData(GridData.END, GridData.CENTER, false, false); - data.horizontalSpan = 2; - link.setLayoutData(data); - link.setText(text); - link.addSelectionListener(listener); - return link; - } - - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/GenerateEntitiesWizard.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/GenerateEntitiesWizard.java deleted file mode 100644 index d709c7967f..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/GenerateEntitiesWizard.java +++ /dev/null @@ -1,212 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 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: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.ui.internal.wizards; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; - -import org.eclipse.jdt.core.IPackageFragment; -import org.eclipse.jdt.core.IPackageFragmentRoot; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.wizard.Wizard; -import org.eclipse.jpt.core.EntityGeneratorDatabaseAnnotationNameBuilder; -import org.eclipse.jpt.core.JpaProject; -import org.eclipse.jpt.db.Column; -import org.eclipse.jpt.db.ForeignKey; -import org.eclipse.jpt.db.Schema; -import org.eclipse.jpt.db.Table; -import org.eclipse.jpt.gen.internal.EntityGenerator; -import org.eclipse.jpt.gen.internal.PackageGenerator; -import org.eclipse.jpt.ui.internal.JptUiMessages; -import org.eclipse.jpt.utility.internal.CollectionTools; - -/** - * two pages: - * - a Database Schema page that allows the user to select a schema - * - a Generate Entities page that allows the user to select which tables in - * the selected schema are to be used and to configure Entity names - */ -public class GenerateEntitiesWizard extends Wizard { - - private final JpaProject jpaProject; - - private final IStructuredSelection selection; - - private DatabaseSchemaWizardPage dbSchemaPage; - - private GenerateEntitiesWizardPage generateEntitiesPage; - - private final PackageGenerator.Config packageGeneratorConfig; - - private final EntityGenerator.Config entityGeneratorConfig; - - private boolean synchronizePersistenceXml; - - - public GenerateEntitiesWizard(JpaProject jpaProject, IStructuredSelection selection) { - super(); - this.jpaProject = jpaProject; - this.selection = selection; - this.packageGeneratorConfig = new PackageGenerator.Config(); - this.entityGeneratorConfig = new EntityGenerator.Config(); - this.setWindowTitle(JptUiMessages.GenerateEntitiesWizard_generateEntities); - } - - @Override - public void addPages() { - super.addPages(); - this.dbSchemaPage = new DatabaseSchemaWizardPage(this.jpaProject); - this.dbSchemaPage.addListener(new SchemaPageListener()); - this.addPage(this.dbSchemaPage); - - this.generateEntitiesPage = new GenerateEntitiesWizardPage(); - this.addPage(this.generateEntitiesPage); - this.generateEntitiesPage.init(this.selection); - } - - @Override - public boolean canFinish() { - return this.generateEntitiesPage.isPageComplete(); - } - - @Override - public boolean performFinish() { - this.packageGeneratorConfig.setPackageFragment(this.buildPackageFragment()); - - this.entityGeneratorConfig.setConvertToJavaStyleIdentifiers(this.generateEntitiesPage.convertToJavaStyleIdentifiers()); - this.entityGeneratorConfig.setFieldAccessType(this.generateEntitiesPage.fieldAccessType()); - this.entityGeneratorConfig.setCollectionTypeName(this.generateEntitiesPage.getCollectionTypeName()); - this.entityGeneratorConfig.setCollectionAttributeNameSuffix(this.generateEntitiesPage.getCollectionAttributeNameSuffix()); - this.entityGeneratorConfig.setFieldVisibility(this.generateEntitiesPage.getFieldVisibility()); - this.entityGeneratorConfig.setMethodVisibility(this.generateEntitiesPage.getMethodVisibility()); - this.entityGeneratorConfig.setGenerateGettersAndSetters(this.generateEntitiesPage.generateGettersAndSetters()); - this.entityGeneratorConfig.setGenerateDefaultConstructor(this.generateEntitiesPage.generateDefaultConstructor()); - this.entityGeneratorConfig.setSerializable(this.generateEntitiesPage.serializable()); - this.entityGeneratorConfig.setGenerateSerialVersionUID(this.generateEntitiesPage.generateSerialVersionUID()); - this.entityGeneratorConfig.setGenerateEmbeddedIdForCompoundPK(this.generateEntitiesPage.generateEmbeddedIdForCompoundPK()); - this.entityGeneratorConfig.setEmbeddedIdAttributeName(this.generateEntitiesPage.getEmbeddedIdAttributeName()); - this.entityGeneratorConfig.setPrimaryKeyMemberClassName(this.generateEntitiesPage.getPrimaryKeyMemberClassName()); - for (Map.Entry<Table, String> entry : this.generateEntitiesPage.getSelectedTables().entrySet()) { - this.entityGeneratorConfig.addTable(entry.getKey(), entry.getValue()); - } - // the name builder comes from the JPA platform - this.entityGeneratorConfig.setDatabaseAnnotationNameBuilder(this.buildDatabaseAnnotationNameBuilder()); - - this.synchronizePersistenceXml = this.generateEntitiesPage.synchronizePersistenceXml(); - - return true; - } - - private EntityGenerator.DatabaseAnnotationNameBuilder buildDatabaseAnnotationNameBuilder() { - return new LocalDatabaseAnnotationNameBuilder(this.jpaProject.getJpaPlatform().getEntityGeneratorDatabaseAnnotationNameBuilder()); - } - - private IPackageFragment buildPackageFragment() { - IPackageFragmentRoot packageFragmentRoot = this.generateEntitiesPage.getPackageFragmentRoot(); - IPackageFragment packageFragment = this.generateEntitiesPage.getPackageFragment(); - - if (packageFragment == null) { - packageFragment= packageFragmentRoot.getPackageFragment(""); //$NON-NLS-1$ - } - - if (packageFragment.exists()) { - return packageFragment; - } - - try { - return packageFragmentRoot.createPackageFragment(packageFragment.getElementName(), true, null); - } - catch (JavaModelException ex) { - throw new RuntimeException(ex); - } - } - - - // ********** intra-wizard methods ********** - - Collection<Table> getPossibleTables() { - return this.buildTables(this.dbSchemaPage.getSelectedSchema()); - } - - JpaProject getJpaProject() { - return this.jpaProject; - } - - void selectedSchemaChanged(Schema schema) { - this.generateEntitiesPage.setPossibleTables(this.buildTables(schema)); - } - - private Collection<Table> buildTables(Schema schema) { - return (schema == null) ? - Collections.<Table>emptySet() - : - CollectionTools.collection(schema.tables()); - } - - - // ********** public methods - settings ********** - - public PackageGenerator.Config getPackageGeneratorConfig() { - return this.packageGeneratorConfig; - } - - public EntityGenerator.Config getEntityGeneratorConfig() { - return this.entityGeneratorConfig; - } - - public boolean synchronizePersistenceXml(){ - return this.synchronizePersistenceXml; - } - - - // ********** name builder adapter ********** - - /** - * adapt the JPA platform-supplied builder to the builder interface - * expected by the entity generator - */ - static class LocalDatabaseAnnotationNameBuilder implements EntityGenerator.DatabaseAnnotationNameBuilder { - private EntityGeneratorDatabaseAnnotationNameBuilder builder; - LocalDatabaseAnnotationNameBuilder(EntityGeneratorDatabaseAnnotationNameBuilder builder) { - super(); - this.builder = builder; - } - public String buildTableAnnotationName(String entityName, Table table) { - return this.builder.buildTableAnnotationName(entityName, table); - } - public String buildColumnAnnotationName(String attributeName, Column column) { - return this.builder.buildColumnAnnotationName(attributeName, column); - } - public String buildJoinColumnAnnotationName(String attributeName, ForeignKey foreignKey) { - return this.builder.buildJoinColumnAnnotationName(attributeName, foreignKey); - } - public String buildJoinColumnAnnotationName(Column column) { - return this.builder.buildJoinColumnAnnotationName(column); - } - public String buildJoinTableAnnotationName(Table table) { - return this.builder.buildJoinTableAnnotationName(table); - } - } - - - // ********** schema page listener ********** - - /** - * listen for when the Database Connection page changes its selected schema - * so we can keep the Generate Entities page in synch - */ - class SchemaPageListener implements DatabaseSchemaWizardPage.Listener { - public void selectedSchemaChanged(Schema schema) { - GenerateEntitiesWizard.this.selectedSchemaChanged(schema); - } - } -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/GenerateEntitiesWizardPage.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/GenerateEntitiesWizardPage.java deleted file mode 100644 index 45cd92c857..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/GenerateEntitiesWizardPage.java +++ /dev/null @@ -1,549 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 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: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.ui.internal.wizards; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jdt.core.IJavaElement; -import org.eclipse.jdt.ui.wizards.NewTypeWizardPage; -import org.eclipse.jface.viewers.CheckboxTableViewer; -import org.eclipse.jface.viewers.ColumnWeightData; -import org.eclipse.jface.viewers.IBaseLabelProvider; -import org.eclipse.jface.viewers.ICellModifier; -import org.eclipse.jface.viewers.IContentProvider; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredContentProvider; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.ITableLabelProvider; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.TextCellEditor; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerSorter; -import org.eclipse.jpt.db.Table; -import org.eclipse.jpt.gen.internal.EntityGenTools; -import org.eclipse.jpt.gen.internal.EntityGenerator; -import org.eclipse.jpt.ui.internal.JpaHelpContextIds; -import org.eclipse.jpt.ui.internal.JptUiMessages; -import org.eclipse.jpt.ui.internal.util.SWTUtil; -import org.eclipse.jpt.ui.internal.util.TableLayoutComposite; -import org.eclipse.jpt.utility.internal.NameTools; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.KeyAdapter; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.TableColumn; -import org.eclipse.swt.widgets.TableItem; -import org.eclipse.ui.PlatformUI; - -// TODO add numerous settings to UI... -// TODO validate list of user-approved entity names: -// no duplicates (case-sensitive) -// valid Java identifiers @see NameTools.stringConsistsOfJavaIdentifierCharacters(String) -// no Java reserved words @see NameTools.JAVA_RESERVED_WORDS_SET -class GenerateEntitiesWizardPage extends NewTypeWizardPage { - - CheckboxTableViewer tableTable; - Button synchronizeClassesCheckBox; - - // TODO if this flag changes we need to re-calculate the entity names... - // (at the moment, it does not change because it is not visible to the user...) - private boolean convertToJavaStyleIdentifiers = true; - private boolean fieldAccessType = true; - private String collectionTypeName = Set.class.getName(); - private String collectionAttributeNameSuffix = "_collection"; //$NON-NLS-1$ - private int fieldVisibility = EntityGenerator.Config.PRIVATE; - private int methodVisibility = EntityGenerator.Config.PUBLIC; - private boolean generateGettersAndSetters = true; - private boolean generateDefaultConstructor = true; - private boolean serializable = true; - private boolean generateSerialVersionUID = true; - private boolean generateEmbeddedIdForCompoundPK = true; - private String embeddedIdAttributeName = "pk"; //$NON-NLS-1$ - private String primaryKeyMemberClassName = "PK"; //$NON-NLS-1$ - - // key = table; value = entity name - private HashMap<Table, String> entityNames; - - private boolean synchronizePersistenceXml = false; - - static final String[] TABLE_TABLE_COLUMN_PROPERTIES = { "table", "entityName" }; //$NON-NLS-1$ //$NON-NLS-2$ - private static final int TABLE_COLUMN_INDEX = 0; - private static final int ENTITY_NAME_COLUMN_INDEX = 1; - - - GenerateEntitiesWizardPage() { - super(true, "Generate Entities"); //$NON-NLS-1$ - setTitle(JptUiMessages.GenerateEntitiesWizardPage_generateEntities); - setMessage(JptUiMessages.GenerateEntitiesWizardPage_chooseEntityTable); - } - - // -------- Initialization --------- - /** - * The wizard owning this page is responsible for calling this method with the - * current selection. The selection is used to initialize the fields of the wizard - * page. - * - * @param selection used to initialize the fields - */ - void init(IStructuredSelection selection) { - IJavaElement jelem= getInitialJavaElement(selection); - initContainerPage(jelem); - initTypePage(jelem); - doStatusUpdate(); - } - - public void createControl(Composite parent) { - Composite composite = new Composite(parent, SWT.NULL); - int nColumns= 4; - GridLayout layout = new GridLayout(); - layout.numColumns = nColumns; - composite.setLayout(layout); - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, JpaHelpContextIds.DIALOG_GENERATE_ENTITIES); - - createContainerControls(composite, nColumns); - createPackageControls(composite, nColumns); - - this.synchronizeClassesCheckBox = new Button(composite, SWT.CHECK); - synchronizeClassesCheckBox.setText(JptUiMessages.GenerateEntitiesWizardPage_synchronizeClasses); - synchronizeClassesCheckBox.addSelectionListener(this.buildSynchClassesSelectionListener()); - - Group tablesGroup = new Group(composite, SWT.SHADOW_ETCHED_IN); - tablesGroup.setLayout(new GridLayout(2, false)); - tablesGroup.setText(JptUiMessages.GenerateEntitiesWizardPage_tables); - GridData data = new GridData(); - data.horizontalSpan = 4; - data.verticalAlignment = SWT.FILL; - data.horizontalAlignment = SWT.FILL; - data.grabExcessHorizontalSpace = true; - data.grabExcessVerticalSpace = true; - tablesGroup.setLayoutData(data); - - createTablesSelectionControl(tablesGroup); - createButtonComposite(tablesGroup); - - this.initTablesSelectionControl(); - - //set initial selection state of the synchronize classes checkbox - synchronizeClassesCheckBox.setSelection( ! this.getGenEntitiesWizard().getJpaProject().discoversAnnotatedClasses()); - setSynchronizePersistenceXml(synchronizeClassesCheckBox.getSelection()); - - PlatformUI.getWorkbench().getHelpSystem().setHelp(this.tableTable.getControl(), JpaHelpContextIds.DIALOG_GENERATE_ENTITIES_TABLES); - - setControl(composite); - this.setPageComplete(false); - } - - private GenerateEntitiesWizard getGenEntitiesWizard() { - return (GenerateEntitiesWizard) this.getWizard(); - } - - void selectAllTables(){ - this.tableTable.setAllChecked(true); - doStatusUpdate(); - } - - void deselectAllTables(){ - this.tableTable.setAllChecked(false); - doStatusUpdate(); - } - - private void initTablesSelectionControl() { - this.setPossibleTables(this.getGenEntitiesWizard().getPossibleTables()); - } - - void setPossibleTables(Collection<Table> possibleTables) { - if (this.tableTable == null) { - return; // the wizard has called this method before our widgets are built - } - this.entityNames = new HashMap<Table, String>(possibleTables.size()); - for (Table table : possibleTables) { - String tableName = table.getName(); - String entityName = (this.convertToJavaStyleIdentifiers) ? - EntityGenTools.convertToUniqueJavaStyleClassName(tableName, entityNames.values()) - : - NameTools.uniqueNameFor(tableName, entityNames.values()); - this.entityNames.put(table, entityName); - } - this.tableTable.setInput(possibleTables); - } - - private void createTablesSelectionControl(Composite parent) { - TableLayoutComposite layout= new TableLayoutComposite(parent, SWT.NONE); - addColumnLayoutData(layout); - - final org.eclipse.swt.widgets.Table table = new org.eclipse.swt.widgets.Table(layout, SWT.H_SCROLL | SWT.V_SCROLL | SWT.SINGLE | SWT.FULL_SELECTION | SWT.BORDER | SWT.CHECK); - table.setHeaderVisible(true); - table.setLinesVisible(true); - - TableColumn tableNameColumn = new TableColumn(table, SWT.NONE, TABLE_COLUMN_INDEX); - tableNameColumn.setText(JptUiMessages.GenerateEntitiesWizardPage_tableColumn); - tableNameColumn.setResizable(true); - - TableColumn entityNameColumn = new TableColumn(table, SWT.NONE, ENTITY_NAME_COLUMN_INDEX); - entityNameColumn.setText(JptUiMessages.GenerateEntitiesWizardPage_entityNameColumn); - entityNameColumn.setResizable(true); - - GridData gd= new GridData(GridData.FILL_BOTH); - gd.heightHint= SWTUtil.getTableHeightHint(table, 20); - gd.widthHint = 600; - layout.setLayoutData(gd); - - this.tableTable = new CheckboxTableViewer(table); - this.tableTable.setUseHashlookup(true); - this.tableTable.setLabelProvider(this.buildTableTableLabelProvider()); - this.tableTable.setContentProvider(this.buildTableTableContentProvider()); - this.tableTable.setSorter(new ViewerSorter() { - @Override - public int compare(Viewer viewer, Object e1, Object e2) { - return ((Table) e1).getName().compareTo(((Table) e2).getName()); - } - }); - - this.tableTable.addPostSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - handleTablesListSelectionChanged(); - } - }); - - table.addKeyListener(new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - if (e.keyCode == SWT.F2 && e.stateMask == SWT.NONE) { - editEntityNameIfPossible(); - e.doit= false; - } - } - }); - - this.addCellEditors(); - } - - private void createButtonComposite(Group tablesGroup){ - Composite buttonComposite = new Composite(tablesGroup, SWT.NULL); - GridLayout buttonLayout = new GridLayout(1, false); - buttonComposite.setLayout(buttonLayout); - GridData data = new GridData(); - data.horizontalAlignment = GridData.FILL; - data.verticalAlignment = GridData.BEGINNING; - buttonComposite.setLayoutData(data); - - Button selectAllButton = new Button(buttonComposite, SWT.PUSH); - selectAllButton.setText(JptUiMessages.General_selectAll); - GridData gridData = new GridData(); - gridData.horizontalAlignment = GridData.FILL; - selectAllButton.setLayoutData(gridData); - selectAllButton.addSelectionListener(this.buildSelectAllButtonSelectionListener()); - - Button deselectAllButton = new Button(buttonComposite, SWT.PUSH); - deselectAllButton.setText(JptUiMessages.General_deselectAll); - gridData = new GridData(); - gridData.horizontalAlignment = GridData.FILL; - deselectAllButton.setLayoutData(gridData); - deselectAllButton.addSelectionListener(this.buildDeselectAllButtonSelectionListener()); - } - - - private void addColumnLayoutData(TableLayoutComposite layout) { - layout.addColumnData(new ColumnWeightData(50, true)); - layout.addColumnData(new ColumnWeightData(50, true)); - } - - void editEntityNameIfPossible(){ - Object[] selected = ((IStructuredSelection) this.tableTable.getSelection()).toArray(); - if (selected.length == 1) { - this.tableTable.editElement(selected[0], ENTITY_NAME_COLUMN_INDEX); - } - } - - private void addCellEditors() { - this.tableTable.setColumnProperties(TABLE_TABLE_COLUMN_PROPERTIES); - - TextCellEditor[] editors = new TextCellEditor[TABLE_TABLE_COLUMN_PROPERTIES.length]; - editors[ENTITY_NAME_COLUMN_INDEX]= new TextCellEditor(this.tableTable.getTable(), SWT.SINGLE); - - this.tableTable.setCellEditors(editors); - this.tableTable.setCellModifier(this.buildTableTableCellModifier()); - } - - void handleTablesListSelectionChanged() { - this.setPageComplete(true); - if (this.noTablesAreSelected()) { - this.setPageComplete(false); - } - } - - private IBaseLabelProvider buildTableTableLabelProvider() { - return new TableTableLabelProvider(); - } - - private IContentProvider buildTableTableContentProvider() { - return new TableTableContentProvider(); - } - - private ICellModifier buildTableTableCellModifier() { - return new TableTableCellModifier(); - } - - Map<Table, String> getSelectedTables() { - Object[] checkedElements = this.tableTable.getCheckedElements(); - HashMap<Table, String> selectedTables = new HashMap<Table, String>(checkedElements.length); - for (Object checkedElement : checkedElements) { - Table table = (Table) checkedElement; - selectedTables.put(table, this.entityNames.get(table)); - } - return selectedTables; - } - - private boolean noTablesAreSelected() { - return (this.tableTable == null) ? true : (this.tableTable.getCheckedElements().length == 0); - } - - @Override - protected void handleFieldChanged(String fieldName) { - super.handleFieldChanged(fieldName); - - doStatusUpdate(); - } - - private void doStatusUpdate() { - // status of all used components - IStatus[] status= new IStatus[] { - fContainerStatus, - fPackageStatus - }; - // the mode severe status will be displayed and the OK button enabled/disabled. - this.updateStatus(status); - } - - /** - * Update the status line and the OK button according to the given status - */ - @Override - protected void updateStatus(IStatus status) { - super.updateStatus(status); - if (this.isPageComplete() && this.noTablesAreSelected()) { - this.setPageComplete(false); - } - } - - String getEntityName(Table table) { - return this.entityNames.get(table); - } - - /** - * return whether the new entity name is different from the old entity name - */ - boolean setEntityName(Table table, String entityName) { - String old = this.entityNames.put(table, entityName); - return ! entityName.equals(old); - } - - boolean convertToJavaStyleIdentifiers() { - return this.convertToJavaStyleIdentifiers; - } - - boolean fieldAccessType() { - return this.fieldAccessType; - } - - String getCollectionTypeName() { - return this.collectionTypeName; - } - - String getCollectionAttributeNameSuffix() { - return this.collectionAttributeNameSuffix; - } - - int getFieldVisibility() { - return this.fieldVisibility; - } - - int getMethodVisibility() { - return this.methodVisibility; - } - - boolean generateGettersAndSetters() { - return this.generateGettersAndSetters; - } - - boolean generateDefaultConstructor() { - return this.generateDefaultConstructor; - } - - boolean serializable() { - return this.serializable; - } - - boolean generateSerialVersionUID() { - return this.generateSerialVersionUID; - } - - boolean generateEmbeddedIdForCompoundPK() { - return this.generateEmbeddedIdForCompoundPK; - } - - boolean synchronizePersistenceXml() { - return this.synchronizePersistenceXml; - } - - void setSynchronizePersistenceXml(boolean synchronizePersistenceXml){ - this.synchronizePersistenceXml = synchronizePersistenceXml; - } - - String getEmbeddedIdAttributeName() { - return this.embeddedIdAttributeName; - } - - String getPrimaryKeyMemberClassName() { - return this.primaryKeyMemberClassName; - } - - private SelectionListener buildSelectAllButtonSelectionListener() { - return new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent event) { - // nothing special for "default" (double-click?) - this.widgetSelected(event); - } - public void widgetSelected(SelectionEvent event) { - selectAllTables(); - } - }; - } - - private SelectionListener buildDeselectAllButtonSelectionListener() { - return new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent event) { - // nothing special for "default" (double-click?) - this.widgetSelected(event); - } - public void widgetSelected(SelectionEvent event) { - deselectAllTables(); - } - }; - } - - private SelectionListener buildSynchClassesSelectionListener() { - return new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent event) { - // nothing special for "default" (double-click?) - this.widgetSelected(event); - } - public void widgetSelected(SelectionEvent event) { - setSynchronizePersistenceXml(synchronizeClassesCheckBox.getSelection()); - } - }; - } - - - // ********** inner classes ********** - - class TableTableLabelProvider extends LabelProvider implements ITableLabelProvider { - - TableTableLabelProvider() { - super(); - } - - @Override - public String getText(Object element) { - return ((Table) element).getName(); - } - - public Image getColumnImage(Object element, int columnIndex) { - return null; - } - - public String getColumnText(Object element, int columnIndex) { - if (element == null) { - return null; - } - switch (columnIndex) { - case TABLE_COLUMN_INDEX: - return ((Table) element).getName(); - - case ENTITY_NAME_COLUMN_INDEX: - return GenerateEntitiesWizardPage.this.getEntityName((Table) element); - } - throw new IllegalArgumentException("invalid column index: " + columnIndex); //$NON-NLS-1$ - } - - } - - - static class TableTableContentProvider implements IStructuredContentProvider { - - TableTableContentProvider() { - super(); - } - - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - // do nothing - } - - public void dispose() { - // do nothing - } - - public Object[] getElements(Object inputElement) { - return ((Collection<?>) inputElement).toArray(); - } - - } - - - class TableTableCellModifier implements ICellModifier { - - TableTableCellModifier() { - super(); - } - - public boolean canModify(Object element, String property) { - return property.equals(TABLE_TABLE_COLUMN_PROPERTIES[ENTITY_NAME_COLUMN_INDEX]); - } - - public Object getValue(Object element, String property) { - if (property.equals(TABLE_TABLE_COLUMN_PROPERTIES[ENTITY_NAME_COLUMN_INDEX])) { - return GenerateEntitiesWizardPage.this.getEntityName((Table) element); - } - return null; - } - - public void modify(Object element, String property, Object value) { - if (element instanceof TableItem) { - element= ((TableItem) element).getData(); - } - if ( ! (element instanceof Table)) { - return; - } - Table table = (Table) element; - - boolean changed = true; - if (property.equals(TABLE_TABLE_COLUMN_PROPERTIES[ENTITY_NAME_COLUMN_INDEX])) { - changed = GenerateEntitiesWizardPage.this.setEntityName(table, (String) value); - } - if (changed) { - GenerateEntitiesWizardPage.this.tableTable.update(table, new String[] { property }); - } - } - - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/JpaFacetWizardPage.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/JpaFacetWizardPage.java deleted file mode 100644 index dec0687556..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/JpaFacetWizardPage.java +++ /dev/null @@ -1,362 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 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: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.ui.internal.wizards; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jpt.core.internal.facet.JpaFacetDataModelProperties; -import org.eclipse.jpt.db.ConnectionProfile; -import org.eclipse.jpt.db.JptDbPlugin; -import org.eclipse.jpt.db.ui.internal.DTPUiTools; -import org.eclipse.jpt.ui.JptUiPlugin; -import org.eclipse.jpt.ui.internal.JpaHelpContextIds; -import org.eclipse.jpt.ui.internal.JptUiIcons; -import org.eclipse.jpt.ui.internal.JptUiMessages; -import org.eclipse.jst.common.project.facet.core.libprov.LibraryInstallDelegate; -import org.eclipse.jst.common.project.facet.ui.libprov.LibraryProviderFrameworkUi; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Link; -import org.eclipse.ui.PlatformUI; -import org.eclipse.wst.common.frameworks.datamodel.DataModelEvent; -import org.eclipse.wst.common.frameworks.datamodel.IDataModelListener; -import org.eclipse.wst.common.project.facet.core.IFacetedProjectWorkingCopy; -import org.eclipse.wst.common.project.facet.core.events.IFacetedProjectEvent; -import org.eclipse.wst.common.project.facet.core.events.IFacetedProjectListener; -import org.eclipse.wst.common.project.facet.ui.ModifyFacetedProjectWizard; -import org.eclipse.wst.web.ui.internal.wizards.DataModelFacetInstallPage; - -public class JpaFacetWizardPage extends DataModelFacetInstallPage - implements JpaFacetDataModelProperties -{ - - public JpaFacetWizardPage() { - super("jpt.jpa.facet.install.page"); //$NON-NLS-1$ - setTitle(JptUiMessages.JpaFacetWizardPage_title); - setDescription(JptUiMessages.JpaFacetWizardPage_description); - setImageDescriptor(JptUiPlugin.getImageDescriptor(JptUiIcons.JPA_WIZ_BANNER)); - } - - @Override - protected Composite createTopLevelComposite(Composite parent) { - Composite composite = new Composite(parent, SWT.NULL); - GridLayout layout = new GridLayout(); - composite.setLayout(layout); - - new PlatformGroup(composite); - new ClasspathConfigGroup(composite); - new ConnectionGroup(composite); - new PersistentClassManagementGroup(composite); - new OrmXmlGroup(composite); - - setUpRuntimeListener(); - - Dialog.applyDialogFont(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, JpaHelpContextIds.DIALOG_JPA_FACET); - - return composite; - } - - private void setUpRuntimeListener() { - final IFacetedProjectWorkingCopy wc = ( (ModifyFacetedProjectWizard) getWizard() ).getFacetedProjectWorkingCopy(); - // must do it manually the first time - model.setProperty(RUNTIME, wc.getPrimaryRuntime()); - wc.addListener( - new IFacetedProjectListener() { - public void handleEvent( final IFacetedProjectEvent event ) { - model.setProperty(RUNTIME, wc.getPrimaryRuntime()); - } - }, - IFacetedProjectEvent.Type.PRIMARY_RUNTIME_CHANGED - ); - } - - private Button createButton(Composite container, int span, String text, int style) { - Button button = new Button(container, SWT.NONE | style); - button.setText(text); - GridData gd = new GridData(); - gd.horizontalSpan = span; - button.setLayoutData(gd); - return button; - } - - private Combo createCombo(Composite container, int span, boolean fillHorizontal) { - Combo combo = new Combo(container, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY); - GridData gd; - if (fillHorizontal) { - gd = new GridData(GridData.FILL_HORIZONTAL); - } - else { - gd = new GridData(); - } - gd.horizontalSpan = span; - combo.setLayoutData(gd); - return combo; - } - - @Override - protected String[] getValidationPropertyNames() { - return new String[] { - PLATFORM_ID, - CONNECTION, - USER_WANTS_TO_ADD_DB_DRIVER_JARS_TO_CLASSPATH, - DB_DRIVER_NAME, - DB_DRIVER_JARS, - USER_WANTS_TO_OVERRIDE_DEFAULT_SCHEMA, - USER_OVERRIDE_DEFAULT_SCHEMA, - DISCOVER_ANNOTATED_CLASSES, - LIBRARY_PROVIDER_DELEGATE - }; - } - - @Override - public boolean isPageComplete() { - if (! super.isPageComplete()) { - return false; - } - else { - IStatus status =model.validate(); - if( status.getSeverity() == IStatus.ERROR){ - setErrorMessage( status.getMessage() ); - return false; - }; - setErrorMessage(null); - return true; - } - } - - @Override - public void setVisible(boolean visible) { - super.setVisible(visible); - if (visible) { - setErrorMessage(); - } - } - - - private final class PlatformGroup - { - private final Combo platformCombo; - - - public PlatformGroup(Composite composite) { - Group group = new Group(composite, SWT.NONE); - group.setText(JptUiMessages.JpaFacetWizardPage_platformLabel); - group.setLayout(new GridLayout()); - group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - PlatformUI.getWorkbench().getHelpSystem().setHelp(group, JpaHelpContextIds.DIALOG_JPA_PLATFORM); - - platformCombo = createCombo(group, 1, true); - synchHelper.synchCombo(platformCombo, PLATFORM_ID, null); - } - } - - - private final class ClasspathConfigGroup - { - public ClasspathConfigGroup(Composite composite) { - - final LibraryInstallDelegate librariesInstallDelegate - = (LibraryInstallDelegate) getDataModel().getProperty(LIBRARY_PROVIDER_DELEGATE); - - getDataModel().addListener( - new IDataModelListener() { - public void propertyChanged(DataModelEvent event) { - if (event.getPropertyName().equals(JpaFacetDataModelProperties.PLATFORM_ID)) { - librariesInstallDelegate.refresh(); - } - } - }); - - final Composite librariesComposite - = (Composite) LibraryProviderFrameworkUi.createInstallLibraryPanel( - composite, librariesInstallDelegate, - JptUiMessages.JpaFacetWizardPage_jpaImplementationLabel ); - librariesComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - PlatformUI.getWorkbench().getHelpSystem().setHelp(librariesComposite, JpaHelpContextIds.NEW_JPA_PROJECT_CONTENT_PAGE_CLASSPATH); - } - } - - - private final class ConnectionGroup - { - private final Combo connectionCombo; - - private Link connectionLink; - - private Link connectLink; - - private final Button addDriverLibraryButton; - - private final Label driverLibraryLabel; - - private final Combo driverLibraryCombo; - - private final Button overrideDefaultSchemaButton; - - private final Label defaultSchemaLabel; - - private final Combo defaultSchemaCombo; - - - public ConnectionGroup(Composite composite) { - Group group = new Group(composite, SWT.NONE); - group.setText(JptUiMessages.JpaFacetWizardPage_connectionLabel); - group.setLayout(new GridLayout(3, false)); - group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - PlatformUI.getWorkbench().getHelpSystem().setHelp(group, JpaHelpContextIds.NEW_JPA_PROJECT_CONTENT_PAGE_DATABASE); - - connectionCombo = createCombo(group, 3, true); - synchHelper.synchCombo(connectionCombo, CONNECTION, null); - connectionCombo.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - updateConnectLink(); - } - }); - - connectionLink = new Link(group, SWT.NONE); - GridData data = new GridData(GridData.END, GridData.CENTER, false, false); - data.horizontalSpan = 2; - connectionLink.setLayoutData(data); - connectionLink.setText(JptUiMessages.JpaFacetWizardPage_connectionLink); - connectionLink.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - openNewConnectionWizard(); - } - } - ); - - connectLink = new Link(group, SWT.NONE); - data = new GridData(GridData.END, GridData.CENTER, false, false); - data.horizontalSpan = 2; - connectLink.setLayoutData(data); - connectLink.setText(JptUiMessages.JpaFacetWizardPage_connectLink); - connectLink.setEnabled(false); - connectLink.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - openConnectionProfile(); - } - }); - - addDriverLibraryButton = createButton(group, 3, JptUiMessages.JpaFacetWizardPage_addDriverLibraryLabel, SWT.CHECK); - addDriverLibraryButton.setSelection(false); - synchHelper.synchCheckbox(addDriverLibraryButton, USER_WANTS_TO_ADD_DB_DRIVER_JARS_TO_CLASSPATH, null); - - driverLibraryLabel = new Label(group, SWT.LEFT); - driverLibraryLabel.setText(JptUiMessages.JpaFacetWizardPage_driverLibraryLabel); - GridData gd = new GridData(); - gd.horizontalSpan = 1; - driverLibraryLabel.setLayoutData(gd); - - driverLibraryCombo = createCombo(group, 1, true); - synchHelper.synchCombo( - driverLibraryCombo, DB_DRIVER_NAME, - new Control[] {driverLibraryLabel}); - - overrideDefaultSchemaButton = createButton(group, 3, JptUiMessages.JpaFacetWizardPage_overrideDefaultSchemaLabel, SWT.CHECK); - overrideDefaultSchemaButton.setSelection(false); - synchHelper.synchCheckbox(overrideDefaultSchemaButton, USER_WANTS_TO_OVERRIDE_DEFAULT_SCHEMA, null); - - defaultSchemaLabel = new Label(group, SWT.LEFT); - defaultSchemaLabel.setText(JptUiMessages.JpaFacetWizardPage_defaultSchemaLabel); - gd = new GridData(); - gd.horizontalSpan = 1; - defaultSchemaLabel.setLayoutData(gd); - - defaultSchemaCombo = createCombo(group, 1, true); - synchHelper.synchCombo( - defaultSchemaCombo, USER_OVERRIDE_DEFAULT_SCHEMA, - new Control[] {defaultSchemaLabel}); - } - - private void openNewConnectionWizard() { - String connectionName = DTPUiTools.createNewConnectionProfile(); - if (connectionName != null) { - model.setProperty(CONNECTION, connectionName); - } - } - - private void openConnectionProfile() { - ConnectionProfile cp = getConnectionProfile(); - if (cp != null) { - cp.connect(); - model.setBooleanProperty(CONNECTION_ACTIVE, cp.isActive()); - updateConnectLink(); - } - } - - private void updateConnectLink() { - ConnectionProfile cp = this.getConnectionProfile(); - connectLink.setEnabled((cp != null) && cp.isDisconnected()); - addDriverLibraryButton.setEnabled(cp != null); - } - - private ConnectionProfile getConnectionProfile() { - // we just use the connection profile to log in, so go the the db plug-in - return JptDbPlugin.instance().getConnectionProfileFactory().buildConnectionProfile(model.getStringProperty(CONNECTION)); - } - } - - - private final class PersistentClassManagementGroup - { - private final Button discoverClassesButton; - - private final Button listClassesButton; - - - public PersistentClassManagementGroup(Composite composite) { - Group group = new Group(composite, SWT.NONE); - group.setText(JptUiMessages.JpaFacetWizardPage_persistentClassManagementLabel); - group.setLayout(new GridLayout()); - group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - PlatformUI.getWorkbench().getHelpSystem().setHelp(group, JpaHelpContextIds.NEW_JPA_PROJECT_CONTENT_PAGE_CLASSPATH); - - discoverClassesButton = createButton(group, 1, JptUiMessages.JpaFacetWizardPage_discoverClassesButton, SWT.RADIO); - synchHelper.synchRadio(discoverClassesButton, DISCOVER_ANNOTATED_CLASSES, null); - - listClassesButton = createButton(group, 1, JptUiMessages.JpaFacetWizardPage_listClassesButton, SWT.RADIO); - synchHelper.synchRadio(listClassesButton, LIST_ANNOTATED_CLASSES, null); - } - } - - - private final class OrmXmlGroup - { - private final Button createOrmXmlButton; - - - public OrmXmlGroup(Composite composite) { - Composite group = new Composite(composite, SWT.NONE); - group.setLayout(new GridLayout()); - group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - PlatformUI.getWorkbench().getHelpSystem().setHelp(group, JpaHelpContextIds.DIALOG_CREATE_ORM); - - createOrmXmlButton = new Button(group, SWT.CHECK); - createOrmXmlButton.setText(JptUiMessages.JpaFacetWizardPage_createOrmXmlButton); - synchHelper.synchCheckbox(createOrmXmlButton, CREATE_ORM_XML, null); - } - } -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/NewEntityDropDownAction.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/NewEntityDropDownAction.java deleted file mode 100644 index 84be91b428..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/NewEntityDropDownAction.java +++ /dev/null @@ -1,261 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 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 - * Oracle - copied and modified from NewJavaEEDropDownAction and NewTypeDropDownAction - *******************************************************************************/ -package org.eclipse.jpt.ui.internal.wizards; - -import java.util.ArrayList; -import java.util.Arrays; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionPoint; -import org.eclipse.core.runtime.Platform; - -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.Shell; - -import org.eclipse.jem.util.logger.proxy.Logger; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.ActionContributionItem; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.IMenuCreator; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.window.Window; -import org.eclipse.jface.wizard.WizardDialog; -import org.eclipse.ui.INewWizard; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.IWorkbenchWindowPulldownDelegate2; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.plugin.AbstractUIPlugin; - -import org.eclipse.jdt.ui.actions.AbstractOpenWizardAction; -import org.eclipse.jdt.internal.ui.util.CoreUtility; -import org.eclipse.jdt.internal.ui.util.PixelConverter; - - -/** - * A type wizard is added to the type drop down if it has a paramater 'javatype': - * <wizard - * name="My JPT Wizard" - * icon="icons/wiz.gif" - * category="mycategory" - * id="xx.MyWizard"> - * <class class="org.xx.MyWizard"> - * <parameter name="jptartifact" value="true"/> - * </class> - * <description> - * My JPT Wizard - * </description> - * </wizard> - */ -public class NewEntityDropDownAction extends Action implements IMenuCreator, IWorkbenchWindowPulldownDelegate2 { - - public static class OpenJptWizardAction extends AbstractOpenWizardAction implements Comparable<Object> { - - private final static String ATT_NAME = "name";//$NON-NLS-1$ - private final static String ATT_CLASS = "class";//$NON-NLS-1$ - private final static String ATT_ICON = "icon";//$NON-NLS-1$ - private static final String TAG_DESCRIPTION = "description"; //$NON-NLS-1$ - - private IConfigurationElement fConfigurationElement; - private int menuIndex; - - public OpenJptWizardAction(IConfigurationElement element) { - this.fConfigurationElement= element; - setText(element.getAttribute(ATT_NAME)); - - String description= getDescriptionFromConfig(this.fConfigurationElement); - setDescription(description); - setToolTipText(description); - setImageDescriptor(getIconFromConfig(this.fConfigurationElement)); - setMenuIndex(getMenuIndexFromConfig(this.fConfigurationElement)); - } - - private String getDescriptionFromConfig(IConfigurationElement config) { - IConfigurationElement [] children = config.getChildren(TAG_DESCRIPTION); - if (children.length>=1) { - return children[0].getValue(); - } - return ""; //$NON-NLS-1$ - } - - private ImageDescriptor getIconFromConfig(IConfigurationElement config) { - String iconName = config.getAttribute(ATT_ICON); - if (iconName != null) { - return AbstractUIPlugin.imageDescriptorFromPlugin(config.getContributor().getName(), iconName); - } - return null; - } - - private int getMenuIndexFromConfig(IConfigurationElement config) { - IConfigurationElement[] classElements = config.getChildren(TAG_CLASS); - if (classElements.length > 0) { - for (IConfigurationElement classElement : classElements) { - IConfigurationElement[] paramElements = classElement.getChildren(TAG_PARAMETER); - for (IConfigurationElement paramElement : paramElements) { - if (ATT_MENUINDEX.equals(paramElement.getAttribute(TAG_NAME))) { - return Integer.parseInt(paramElement.getAttribute(TAG_VALUE)); - } - } - } - } - return Integer.MAX_VALUE; - } - - @Override - public void run() { - Shell shell = getShell(); - try { - INewWizard wizard = createWizard(); - wizard.init(PlatformUI.getWorkbench(), getSelection()); - - WizardDialog dialog = new WizardDialog(shell, wizard); - PixelConverter converter = new PixelConverter(JFaceResources.getDialogFont()); - dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(70), converter.convertHeightInCharsToPixels(20)); - dialog.create(); - int res = dialog.open(); - - notifyResult(res == Window.OK); - } catch (CoreException e) { - Logger.getLogger().log(e); - } - } - - @Override - protected INewWizard createWizard() throws CoreException { - return (INewWizard) CoreUtility.createExtension(fConfigurationElement, ATT_CLASS); - } - - public int getMenuIndex() { - return this.menuIndex; - } - - public void setMenuIndex(int menuIndex) { - this.menuIndex = menuIndex; - } - - public int compareTo(Object o) { - OpenJptWizardAction action = (OpenJptWizardAction) o; - return getMenuIndex() - action.getMenuIndex(); - } - - } - - - - private final static String TAG_WIZARD = "wizard";//$NON-NLS-1$ - private final static String ATT_JPTARTIFACT = "jptartifact";//$NON-NLS-1$ - - private final static String TAG_PARAMETER = "parameter";//$NON-NLS-1$ - private final static String TAG_NAME = "name";//$NON-NLS-1$ - private final static String TAG_VALUE = "value";//$NON-NLS-1$ - protected final static String ATT_MENUINDEX = "menuIndex";//$NON-NLS-1$ - - private static final String PL_NEW = "newWizards"; //$NON-NLS-1$ - private static final String TAG_CLASS = "class"; //$NON-NLS-1$ - - private Menu fMenu; - - private Shell fWizardShell; - - public NewEntityDropDownAction() { - this.fMenu= null; - setMenuCreator(this); - //PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.OPEN_CLASS_WIZARD_ACTION); - } - - public void dispose() { - if (this.fMenu != null) { - this.fMenu.dispose(); - this.fMenu= null; - } - } - - public Menu getMenu(Menu parent) { - return null; - } - - public Menu getMenu(Control parent) { - if (this.fMenu == null) { - this.fMenu = new Menu(parent); - OpenJptWizardAction[] actions = getActionFromDescriptors(); - for (int i = 0; i < actions.length; i++) { - OpenJptWizardAction curr = actions[i]; - curr.setShell(this.fWizardShell); - ActionContributionItem item = new ActionContributionItem(curr); - item.fill(this.fMenu, -1); - } - - } - return this.fMenu; - } - - @Override - public void run() { - getDefaultAction().run(); - } - - public Action getDefaultAction() { - Action[] actions = getActionFromDescriptors(); - if (actions.length > 0) - return actions[0]; - return null; - } - - public static OpenJptWizardAction[] getActionFromDescriptors() { - ArrayList<OpenJptWizardAction> containers= new ArrayList<OpenJptWizardAction>(); - - IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(PlatformUI.PLUGIN_ID, PL_NEW); - if (extensionPoint != null) { - IConfigurationElement[] elements = extensionPoint.getConfigurationElements(); - for (int i = 0; i < elements.length; i++) { - IConfigurationElement element= elements[i]; - if (element.getName().equals(TAG_WIZARD) && isJptArtifactWizard(element)) { - containers.add(new OpenJptWizardAction(element)); - } - } - } - OpenJptWizardAction[] actions = containers.toArray(new OpenJptWizardAction[containers.size()]); - Arrays.sort(actions); - return actions; - } - - private static boolean isJptArtifactWizard(IConfigurationElement element) { - IConfigurationElement[] classElements= element.getChildren(TAG_CLASS); - if (classElements.length > 0) { - for (int i= 0; i < classElements.length; i++) { - IConfigurationElement[] paramElements= classElements[i].getChildren(TAG_PARAMETER); - for (int k = 0; k < paramElements.length; k++) { - IConfigurationElement curr= paramElements[k]; - if (ATT_JPTARTIFACT.equals(curr.getAttribute(TAG_NAME))) { - return Boolean.valueOf(curr.getAttribute(TAG_VALUE)).booleanValue(); - } - } - } - } - return false; - } - - public void init(IWorkbenchWindow window) { - fWizardShell= window.getShell(); - } - - public void run(IAction action) { - run(); - } - - public void selectionChanged(IAction action, ISelection selection) { - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/NewJpaProjectFirstPage.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/NewJpaProjectFirstPage.java deleted file mode 100644 index 437a2c4b9f..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/NewJpaProjectFirstPage.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 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: Oracle. - initial API and implementation - *******************************************************************************/ -package org.eclipse.jpt.ui.internal.wizards; - -import org.eclipse.jpt.ui.internal.JpaHelpContextIds; -import org.eclipse.jpt.ui.internal.JptUiMessages; -import org.eclipse.jst.j2ee.ui.project.facet.UtilityProjectFirstPage; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; - -public class NewJpaProjectFirstPage extends UtilityProjectFirstPage -{ - public NewJpaProjectFirstPage(IDataModel dataModel, String pageName) { - super(dataModel, pageName); - setTitle(JptUiMessages.NewJpaProjectWizard_firstPage_title); - setDescription(JptUiMessages.NewJpaProjectWizard_firstPage_description); - setInfopopID(JpaHelpContextIds.NEW_JPA_PROJECT); - } -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/NewJpaProjectWizard.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/NewJpaProjectWizard.java deleted file mode 100644 index 53d34954f8..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/NewJpaProjectWizard.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 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: Oracle. - initial API and implementation - *******************************************************************************/ -package org.eclipse.jpt.ui.internal.wizards; - -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.wizard.IWizardPage; -import org.eclipse.jpt.ui.JptUiPlugin; -import org.eclipse.jpt.ui.internal.JptUiIcons; -import org.eclipse.jpt.ui.internal.JptUiMessages; -import org.eclipse.jst.j2ee.ui.project.facet.UtilityProjectWizard; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; -import org.eclipse.wst.common.project.facet.core.IFacetedProjectTemplate; -import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager; - -public class NewJpaProjectWizard extends UtilityProjectWizard { - - public NewJpaProjectWizard() { - super(); - setWindowTitle(JptUiMessages.NewJpaProjectWizard_title); - } - - public NewJpaProjectWizard(IDataModel model) { - super(model); - setWindowTitle(JptUiMessages.NewJpaProjectWizard_title); - } - - // TODO - when we have a data model to add -// protected IDataModel createDataModel() { -// return DataModelFactory.createDataModel(new UtilityProjectCreationDataModelProvider()); -// } - - @Override - protected ImageDescriptor getDefaultPageImageDescriptor() { - return JptUiPlugin.getImageDescriptor(JptUiIcons.JPA_WIZ_BANNER); - } - - @Override - protected IFacetedProjectTemplate getTemplate() { - return ProjectFacetsManager.getTemplate("jpt.jpa.template"); - } - - @Override - protected IWizardPage createFirstPage() { - return new NewJpaProjectFirstPage(model, "first.page"); //$NON-NLS-1$ - } - - @Override - protected String getFinalPerspectiveID() { - return "org.eclipse.jpt.ui.jpaPerspective"; - } -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/AnnotatedEntityTemplate.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/AnnotatedEntityTemplate.java deleted file mode 100644 index 5dfd091bc4..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/AnnotatedEntityTemplate.java +++ /dev/null @@ -1,166 +0,0 @@ -package org.eclipse.jpt.ui.internal.wizards.entity; - -import org.eclipse.jpt.ui.internal.wizards.entity.data.model.*; -import java.util.*; - -public class AnnotatedEntityTemplate -{ - protected static String nl; - public static synchronized AnnotatedEntityTemplate create(String lineSeparator) - { - nl = lineSeparator; - AnnotatedEntityTemplate result = new AnnotatedEntityTemplate(); - nl = null; - return result; - } - - public final String NL = nl == null ? (System.getProperties().getProperty("line.separator")) : nl; - protected final String TEXT_1 = "package "; - protected final String TEXT_2 = ";"; - protected final String TEXT_3 = NL; - protected final String TEXT_4 = NL + "import "; - protected final String TEXT_5 = ";"; - protected final String TEXT_6 = NL + NL + "/**" + NL + " * Entity implementation class for Entity: "; - protected final String TEXT_7 = NL + " *" + NL + " */"; - protected final String TEXT_8 = NL; - protected final String TEXT_9 = "(name=\""; - protected final String TEXT_10 = "\")"; - protected final String TEXT_11 = NL + "@Table(name=\""; - protected final String TEXT_12 = "\")"; - protected final String TEXT_13 = NL; - protected final String TEXT_14 = NL + "@IdClass("; - protected final String TEXT_15 = ".class)"; - protected final String TEXT_16 = NL + "public class "; - protected final String TEXT_17 = " extends "; - protected final String TEXT_18 = " implements "; - protected final String TEXT_19 = ", "; - protected final String TEXT_20 = " {" + NL + "" + NL + "\t"; - protected final String TEXT_21 = " " + NL + "\t@Id"; - protected final String TEXT_22 = NL + "\tprivate "; - protected final String TEXT_23 = " "; - protected final String TEXT_24 = ";"; - protected final String TEXT_25 = NL + "\tprivate static final long serialVersionUID = 1L;" + NL + "" + NL + "\tpublic "; - protected final String TEXT_26 = "() {" + NL + "\t\tsuper();" + NL + "\t}"; - protected final String TEXT_27 = " " + NL + "\t@Id "; - protected final String TEXT_28 = " " + NL + "\tpublic "; - protected final String TEXT_29 = " get"; - protected final String TEXT_30 = "() {" + NL + "\t\treturn this."; - protected final String TEXT_31 = ";" + NL + "\t}" + NL + "" + NL + "\tpublic void set"; - protected final String TEXT_32 = "("; - protected final String TEXT_33 = " "; - protected final String TEXT_34 = ") {" + NL + "\t\tthis."; - protected final String TEXT_35 = " = "; - protected final String TEXT_36 = ";" + NL + "\t}"; - protected final String TEXT_37 = NL + " " + NL + "}"; - protected final String TEXT_38 = NL; - - public String generate(Object argument) - { - final StringBuffer stringBuffer = new StringBuffer(); - CreateEntityTemplateModel model = (CreateEntityTemplateModel) argument; -if (model.getJavaPackageName()!=null && model.getJavaPackageName()!="") { - stringBuffer.append(TEXT_1); - stringBuffer.append(model.getJavaPackageName()); - stringBuffer.append(TEXT_2); - } - stringBuffer.append(TEXT_3); - Collection<String> imports = model.getImports(false); -for (String anImport : imports) { - stringBuffer.append(TEXT_4); - stringBuffer.append(anImport); - stringBuffer.append(TEXT_5); - } - stringBuffer.append(TEXT_6); - stringBuffer.append(model.getEntityName()); - stringBuffer.append(TEXT_7); - stringBuffer.append(TEXT_8); - stringBuffer.append(model.getArtifactType()); - String ENTITY_NAME = model.getEntityName(); -if (model.isEntityNameSet()) { - stringBuffer.append(TEXT_9); - stringBuffer.append(ENTITY_NAME); - stringBuffer.append(TEXT_10); - } - if (model.isTableNameSet()) { - stringBuffer.append(TEXT_11); - stringBuffer.append(model.getTableName()); - stringBuffer.append(TEXT_12); - } - stringBuffer.append(TEXT_13); - stringBuffer.append(model.getInheritanceStrategy()); - if (model.isCompositePK()) { - stringBuffer.append(TEXT_14); - stringBuffer.append(model.getIdClassName()); - stringBuffer.append(TEXT_15); - } - stringBuffer.append(TEXT_16); - stringBuffer.append(model.getClassName()); - String superClass = model.getSuperclassName(); - if (! "".equals(superClass)) { - stringBuffer.append(TEXT_17); - stringBuffer.append(superClass); - } - - List<String> interfaces = model.getInterfaces(); - if (interfaces.size()>0) { - stringBuffer.append(TEXT_18); - } - for (int i=0; i<interfaces.size(); i++) { - String INTERFACE = (String) interfaces.get(i); - if (i>0) { - stringBuffer.append(TEXT_19); - } - stringBuffer.append(INTERFACE); - } - stringBuffer.append(TEXT_20); - List<EntityRow> fields = model.getEntityFields(); - List<String> pkFields = model.getPKFields(); - for (EntityRow entity : fields) { - String NAME = entity.getName(); - if (pkFields.contains(NAME) && model.isFieldAccess()) { - - stringBuffer.append(TEXT_21); - } - stringBuffer.append(TEXT_22); - stringBuffer.append(entity.getType()); - stringBuffer.append(TEXT_23); - stringBuffer.append(entity.getName()); - stringBuffer.append(TEXT_24); - } - stringBuffer.append(TEXT_25); - stringBuffer.append(model.getClassName()); - stringBuffer.append(TEXT_26); - - fields = model.getEntityFields(); - if (fields != null) for (int i=0; i<fields.size(); i++) { - EntityRow field = (EntityRow) fields.get(i); - String TYPE = field.getType(); - String NAME = field.getName(); - String METHOD = NAME.substring(0,1).toUpperCase() + NAME.substring(1); - if (pkFields.contains(NAME) && !model.isFieldAccess()) { - - stringBuffer.append(TEXT_27); - } - stringBuffer.append(TEXT_28); - stringBuffer.append(TYPE); - stringBuffer.append(TEXT_29); - stringBuffer.append(METHOD); - stringBuffer.append(TEXT_30); - stringBuffer.append(NAME); - stringBuffer.append(TEXT_31); - stringBuffer.append(METHOD); - stringBuffer.append(TEXT_32); - stringBuffer.append(TYPE); - stringBuffer.append(TEXT_33); - stringBuffer.append(NAME); - stringBuffer.append(TEXT_34); - stringBuffer.append(NAME); - stringBuffer.append(TEXT_35); - stringBuffer.append(NAME); - stringBuffer.append(TEXT_36); - } - stringBuffer.append(TEXT_37); - stringBuffer.append(TEXT_38); - return stringBuffer.toString(); - } -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityClassWizardPage.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityClassWizardPage.java deleted file mode 100644 index c8961a1a74..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityClassWizardPage.java +++ /dev/null @@ -1,401 +0,0 @@ -/*********************************************************************** - * Copyright (c) 2008 by SAP AG, Walldorf. - * 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: - * SAP AG - initial API and implementation - * Dimiter Dimitrov, d.dimitrov@sap.com - initial API and implementation - ***********************************************************************/ -package org.eclipse.jpt.ui.internal.wizards.entity; - -import java.io.File; -import org.eclipse.core.resources.IContainer; -import org.eclipse.core.resources.IFile; -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.Status; -import org.eclipse.jface.viewers.DecoratingLabelProvider; -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.TreeSelection; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerFilter; -import org.eclipse.jface.window.Window; -import org.eclipse.jpt.core.JptCorePlugin; -import org.eclipse.jpt.core.internal.resource.JpaXmlResourceProviderManager; -import org.eclipse.jpt.core.internal.resource.orm.OrmXmlResourceProvider; -import org.eclipse.jpt.ui.JptUiPlugin; -import org.eclipse.jpt.ui.internal.wizards.entity.data.model.IEntityDataModelProperties; -import org.eclipse.jpt.utility.internal.CollectionTools; -import org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties; -import org.eclipse.jst.j2ee.internal.project.J2EEProjectUtilities; -import org.eclipse.jst.j2ee.internal.wizard.NewJavaClassWizardPage; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; -import org.eclipse.ui.model.WorkbenchContentProvider; -import org.eclipse.ui.model.WorkbenchLabelProvider; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; -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.ProjectFacetsManager; - -public class EntityClassWizardPage extends NewJavaClassWizardPage{ - - private static final String JPA_FACET = "jpt.jpa";//$NON-NLS-1$ - private static final String META_INF = "META-INF";//$NON-NLS-1$ - private static final String EMPTY = "";//$NON-NLS-1$ - private static final char SLASH = '/'; //$NON-NLS-1$ - private static final String SINGLE_TABLE = "SINGLE_TABLE";//$NON-NLS-1$ - private static final String TABLE_PER_CLASS = "TABLE_PER_CLASS";//$NON-NLS-1$ - private static final String JOINED = "JOINED";//$NON-NLS-1$ - private static final String[] INHERITANCE_STRATEGIES = new String[] { - EMPTY, - SINGLE_TABLE, - TABLE_PER_CLASS, - JOINED }; - private Combo inheritanceStrategyCombo; - private Button entityButton; - private Button mapedAsSuperclassButton; - private Button inheritanceButton; - private Label displayNameLabel; - private Button xmlSupportButton; - private boolean isFirstCheck = true; - private Text ormXmlName; - private Button browseButton; - - public EntityClassWizardPage(IDataModel model, String pageName, - String pageDesc, String pageTitle, String moduleType) { - super(model, pageName, pageDesc, pageTitle, moduleType); - } - - - @Override - protected String[] getValidationPropertyNames() { - return CollectionTools.addAll( - super.getValidationPropertyNames(), - new String[] {IEntityDataModelProperties.XML_NAME, IEntityDataModelProperties.XML_SUPPORT}); - } - - /* Create top level composite (class properties) and add the entity's specific inheritance group - * @see org.eclipse.jst.j2ee.internal.wizard.NewJavaClassWizardPage#createTopLevelComposite(org.eclipse.swt.widgets.Composite) - */ - @Override - protected Composite createTopLevelComposite(Composite parent) { - Composite composite = super.createTopLevelComposite(parent); - createInheritanceControl(composite); - inheritanceButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - boolean isChecked = inheritanceButton.getSelection(); - if (isChecked) { - entityButton.setSelection(true); - mapedAsSuperclassButton.setSelection(false); - } - inheritanceStrategyCombo.setEnabled(isChecked); - model.setBooleanProperty(IEntityDataModelProperties.ENTITY, true); - model.setBooleanProperty(IEntityDataModelProperties.MAPPED_AS_SUPERCLASS, false); - entityButton.setEnabled(!isChecked); - mapedAsSuperclassButton.setEnabled(!isChecked); - } - }); - createXMLstorageControl(composite); - xmlSupportButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - boolean isChecked = xmlSupportButton.getSelection(); - enableMappingXMLChooseGroup(isChecked); - if (isFirstCheck) { - ormXmlName.setText(JptCorePlugin.DEFAULT_ORM_XML_FILE_PATH); - isFirstCheck = false; - } - } - }); - return composite; - } - - /** - * Create the inheritance group - * @param parent the main composite - */ - private void createInheritanceControl(Composite parent) { - Group group = createGroup(parent, EntityWizardMsg.INHERITANCE_GROUP); - entityButton = createRadioButton(group, EntityWizardMsg.ENTITY, IEntityDataModelProperties.ENTITY); - mapedAsSuperclassButton = createRadioButton(group, EntityWizardMsg.MAPPED_AS_SUPERCLASS, IEntityDataModelProperties.MAPPED_AS_SUPERCLASS); - inheritanceButton = createCheckButton(group, GridData.HORIZONTAL_ALIGN_FILL, 1/*horizontal span*/, EntityWizardMsg.INHERITANCE_CHECK_BOX, IEntityDataModelProperties.INHERITANCE); - createComboBox(group, IEntityDataModelProperties.INHERITANCE_STRATEGY); - } - - /** - * Create the group, which manage entity mapping registration - * @param parent the main composite - */ - private void createXMLstorageControl(Composite parent) { - Group group = createGroup(parent, EntityWizardMsg.XML_STORAGE_GROUP); - xmlSupportButton = createCheckButton(group, GridData.FILL_HORIZONTAL, 3/*horizontal span*/, EntityWizardMsg.XML_SUPPORT, IEntityDataModelProperties.XML_SUPPORT); - createBrowseGroup(group, EntityWizardMsg.CHOOSE_XML, IEntityDataModelProperties.XML_NAME); - ormXmlName.setEnabled(false); - browseButton.setEnabled(false); - } - - /** - * @param parent the main composite - * @param text the name/title of the group - * @return the created group - */ - private Group createGroup(Composite parent, String text) { - Group group = new Group(parent, SWT.NONE); - GridData groupGridData = new GridData(GridData.FILL_HORIZONTAL); - groupGridData.horizontalSpan = 3; - group.setLayoutData(groupGridData); - group.setLayout(new GridLayout(3, false)); - group.setText(text); - return group; - } - - /** - * Create radio button - * @param parent the main composite - inheritance group - * @param text the label of the button - * @param property the related property to which this button will be synchronized - * @return the created button - */ - private Button createRadioButton(Composite parent, String text, String property) { - Button button = new Button(parent, SWT.RADIO); - GridData groupGridData = new GridData(GridData.FILL_HORIZONTAL); - groupGridData.horizontalSpan = 3; - button.setLayoutData(groupGridData); - button.setText(text); - synchHelper.synchRadio(button, property, /*dependentControls*/ null); - return button; - } - - /** - * Create check button - * @param parent the main composite - inheritance group - * @param text the label of the button - * @param property the related property to which this button will be synchronized - * @return the created button - */ - private Button createCheckButton(Composite parent, int fillStrategy, int horizontalSpan, String text, String property) { - final Button button = new Button(parent, SWT.CHECK); - GridData groupGridData = new GridData(fillStrategy); - groupGridData.horizontalSpan = horizontalSpan; - button.setLayoutData(groupGridData); - button.setText(text); - synchHelper.synchCheckbox(button, property, /*dependentControls*/ null); - return button; - } - - /** - * Create combo box, which presents the set of possible inheritance strategies - * @param parent the main composite - inheritance group - * @param property the related property to which this button will be synchronized - * @return - */ - private Combo createComboBox(Composite parent, String property) { - inheritanceStrategyCombo = new Combo(parent, SWT.BORDER | SWT.READ_ONLY); - GridData groupGridData = new GridData(GridData.FILL_HORIZONTAL); - groupGridData.horizontalSpan = 2; - inheritanceStrategyCombo.setLayoutData(groupGridData); - inheritanceStrategyCombo.setItems(INHERITANCE_STRATEGIES); - synchHelper.synchCombo(inheritanceStrategyCombo, property, /*dependentControls*/ null); - inheritanceStrategyCombo.setEnabled(false); - return inheritanceStrategyCombo; - - } - - /** - * Create XML group - * @param parent the main composite - * @param label the name of the group - * @param property the related property to which this group will be synchronized - * @return the created group - */ - private void createBrowseGroup(Composite parent, String label, String property) { - Composite composite = new Composite(parent, SWT.NULL); - composite.setLayout(new GridLayout(3, false)); - composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - displayNameLabel = new Label(composite, SWT.LEFT); - displayNameLabel.setText(label); - displayNameLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); - ormXmlName = new Text(composite, SWT.SINGLE | SWT.BORDER); - ormXmlName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - browseButton = new Button(composite, SWT.PUSH); - browseButton.setText(EntityWizardMsg.BROWSE_BUTTON_LABEL); - GridData browseButtonData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - browseButtonData.horizontalSpan = 1; - browseButton.setLayoutData(browseButtonData); - browseButton.addSelectionListener(new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - handleChooseXmlButtonPressed(); - } - - public void widgetDefaultSelected(SelectionEvent e) { - // Do nothing - } - }); - synchHelper.synchText(ormXmlName, property, /*dependentControls*/null); - - enableMappingXMLChooseGroup(false); - } - - /** - * Process browsing when the Browse... button have been pressed. Allow choosing of - * XML for entity mapping registration - * - */ - private void handleChooseXmlButtonPressed() { - IProject project = (IProject) getDataModel().getProperty(INewJavaClassDataModelProperties.PROJECT); - if (project == null) { - return; - } - ViewerFilter filter = getDialogViewerFilter(); - ITreeContentProvider contentProvider = new WorkbenchContentProvider(); - ILabelProvider labelProvider = new DecoratingLabelProvider(new WorkbenchLabelProvider(), PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator()); - SelectMappingXMLDialog dialog = new SelectMappingXMLDialog(getShell(), labelProvider, contentProvider); - dialog.setTitle(EntityWizardMsg.MAPPING_XML_TITLE); - dialog.setMessage(EntityWizardMsg.CHOOSE_MAPPING_XML_MESSAGE); - dialog.addFilter(filter); - - IFile rootFolder = project.getFile(J2EEProjectUtilities.getSourceContainers(project)[0].getResource().getName() + SLASH + ormXmlName.getText().trim());//TODO - dialog.setInput(J2EEProjectUtilities.getManifestFile(project).getParent().getParent()); - - if (project != null) - dialog.setInitialSelection(rootFolder); - if (dialog.open() == Window.OK) { - ormXmlName.setText(dialog.getChosenName()); - model.validateProperty(IEntityDataModelProperties.XML_NAME); - } - } - - /** - * This method create filter for the browse/add alternative mapping XML - * @return new instance of viewer filter for the SelectMappingXMLDialog - */ - protected ViewerFilter getDialogViewerFilter() { - return new ViewerFilter() { - @Override - public boolean select(Viewer viewer, Object parent, Object element) { - if (element instanceof IFolder) { - IProject project = (IProject) getDataModel().getProperty(INewJavaClassDataModelProperties.PROJECT); - IFolder folder = (IFolder)element; - if (folder.contains(J2EEProjectUtilities.getManifestFile(project))) { - return true; - } - return false; - } else if (element instanceof IFile) { - IFile file = (IFile) element; - if (JpaXmlResourceProviderManager.instance().getXmlResourceProvider(file) instanceof OrmXmlResourceProvider) { - return true; - } - } - return false; - } - }; - } - - private void enableMappingXMLChooseGroup(boolean enabled) { - displayNameLabel.setEnabled(enabled); - ormXmlName.setEnabled(enabled); - browseButton.setEnabled(enabled); - - } - - /** - * This method is used by the project list initializer. The method checks - * if the specified project is valid to include it in the project list. - * - * <p>Subclasses of this wizard page should override this method to - * adjust filtering of the projects to their needs. </p> - * - * @param project reference to the project to be checked - * - * @return <code>true</code> if the project is valid to be included in - * the project list, <code>false</code> - otherwise. - */ - @Override - protected boolean isProjectValid(IProject project) { - IProjectFacet jpaFacet = ProjectFacetsManager.getProjectFacet(JPA_FACET); - IFacetedProject fProject = null; - try { - fProject = ProjectFacetsManager.create(project); - } catch (CoreException e) { - return false; - } - return (project.isAccessible() && fProject != null && fProject.hasProjectFacet(jpaFacet)); - } - - private class SelectMappingXMLDialog extends ElementTreeSelectionDialog - { - private String xmlName = EMPTY; - - - public SelectMappingXMLDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider) { - super(parent, labelProvider, contentProvider); - } - - - /** - * @return the name of the alternative mapping XML - */ - public String getChosenName() { - String result = EMPTY; - Object element = getFirstResult(); - if (element instanceof IContainer) { - IContainer container = (IContainer) element; - result = container.getFullPath().toString() + File.separatorChar + xmlName; - } else { - IFile f = (IFile) element; - result = f.getFullPath().toOSString(); - } - result = removeRedundantSegmentFromName(result); - return result; - } - - @Override - /* - * @see ElementTreeSelectionDialog#updateOKStatus(Composite) - */ - protected void updateOKStatus() { - super.updateOKStatus(); - TreeSelection selection = (TreeSelection)getTreeViewer().getSelection(); - IResource selectedResource = (IResource) selection.getFirstElement(); - if (selectedResource instanceof IFile) { - updateStatus(new Status(IStatus.OK, JptUiPlugin.PLUGIN_ID, "")); - } - else { - updateStatus(new Status(IStatus.ERROR, JptUiPlugin.PLUGIN_ID, "")); - } - } - - /** - * This method is for internal purposes only - * @param input non formated path to the mapping XML - * @return the formated path to the mapping XML - */ - private String removeRedundantSegmentFromName(String input) { - String output = input.substring(input.indexOf(META_INF)); - output = output.replace(File.separatorChar, SLASH); - return output; - } - } -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityFieldsWizardPage.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityFieldsWizardPage.java deleted file mode 100644 index f169dc6164..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityFieldsWizardPage.java +++ /dev/null @@ -1,224 +0,0 @@ -/*********************************************************************** - * Copyright (c) 2008 by SAP AG, Walldorf. - * 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: - * SAP AG - initial API and implementation - * Dimiter Dimitrov, d.dimitrov@sap.com - initial API and implementation - ***********************************************************************/ -package org.eclipse.jpt.ui.internal.wizards.entity; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jpt.ui.internal.wizards.entity.data.model.IEntityDataModelProperties; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Text; -import org.eclipse.wst.common.componentcore.internal.operation.IArtifactEditOperationDataModelProperties; -import org.eclipse.wst.common.frameworks.datamodel.DataModelEvent; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; -import org.eclipse.wst.common.frameworks.internal.datamodel.ui.DataModelWizardPage; -import org.eclipse.wst.common.frameworks.internal.plugin.WTPCommonPlugin; - -public class EntityFieldsWizardPage extends DataModelWizardPage { - - private Text entityNameText; - private Text tableNameText; - private Button tableNameCheckButton; - private Button fieldAccessButton; - private Button propertyAccessButton; - private boolean isNonEntity = true; - private boolean isButtonsCreated = false; - - public EntityFieldsWizardPage(IDataModel model, String pageName) { - super(model, pageName); - setDescription(EntityWizardMsg.ADD_ENTITY_WIZARD_PAGE_DESCRIPTION); - this.setTitle(EntityWizardMsg.ENTITY_PROPERTIES_TITLE); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jem.util.ui.wizard.WTPWizardPage#getValidationPropertyNames() - */ - @Override - protected String[] getValidationPropertyNames() { - return new String[]{IEntityDataModelProperties.ENTITY_FIELDS}; - } - - /* Create the main composite and add to it the entity properties - * @see org.eclipse.wst.common.frameworks.internal.datamodel.ui.DataModelWizardPage#createTopLevelComposite(org.eclipse.swt.widgets.Composite) - */ - @Override - protected Composite createTopLevelComposite(Composite parent) { - Composite composite = new Composite(parent, SWT.NULL); - composite.setLayout(new GridLayout()); - GridData data = new GridData(GridData.FILL_BOTH); - data.widthHint = 300; - data.heightHint = 450; - composite.setLayoutData(data); - composite.pack(); - - entityNameText = createNameGroup(composite, EntityWizardMsg.ENTITY_NAME, IEntityDataModelProperties.ENTITY_NAME); - Group group = createGroup(composite, EntityWizardMsg.TABLE_NAME_GROUP); - tableNameCheckButton= createCheckButton(group, EntityWizardMsg.USE_DEFAULT, IEntityDataModelProperties.TABLE_NAME_DEFAULT); - tableNameText = createNameGroup(group, EntityWizardMsg.TABLE_NAME, IEntityDataModelProperties.TABLE_NAME); - tableNameText.setEnabled(!tableNameCheckButton.getSelection()); - isButtonsCreated = true; - initNameGroup(); - createEntityFieldsGroup(composite); - - Group accessTypeGroup = createGroup(composite, EntityWizardMsg.ACCESS_TYPE); - fieldAccessButton = createRadioButton(accessTypeGroup, EntityWizardMsg.FIELD_BASED, IEntityDataModelProperties.FIELD_ACCESS_TYPE); - propertyAccessButton = createRadioButton(accessTypeGroup, EntityWizardMsg.PROPERTY_BASED, IEntityDataModelProperties.PROPERTY_ACCESS_TYPE); - - - IStatus projectStatus = validateProjectName(); - if (!projectStatus.isOK()) { - setErrorMessage(projectStatus.getMessage()); - composite.setEnabled(false); - } - Dialog.applyDialogFont(parent); - return composite; - } - - /** - * @return the status of the project name correctness - */ - protected IStatus validateProjectName() { - // check for empty - if (model.getStringProperty(IArtifactEditOperationDataModelProperties.PROJECT_NAME) == null || model.getStringProperty(IArtifactEditOperationDataModelProperties.PROJECT_NAME).trim().length() == 0) { - return WTPCommonPlugin.createErrorStatus(EntityWizardMsg.NO_JPA_PROJECTS); - } - return WTPCommonPlugin.OK_STATUS; - } - - protected void createEntityFieldsGroup(Composite parent) { - Group group = new Group(parent, SWT.NONE); - GridData groupGridData = new GridData(GridData.FILL_BOTH); - groupGridData.horizontalSpan = 3; - group.setLayoutData(groupGridData); - group.setLayout(new GridLayout(3, false)); - group.setText(EntityWizardMsg.ENTITY_FIELDS_GROUP); - new EntityRowTableWizardSection(group, model, IEntityDataModelProperties.ENTITY_FIELDS); - } - - /** - * Create named group - * @param parent the main composite - * @param label the name of the group - * @param property the related property to which this group will be synchronized - * @return the created group - */ - protected Text createNameGroup(Composite parent, String label, String property) { - Composite composite = new Composite(parent, SWT.NULL); - composite.setLayout(new GridLayout(3, false)); - composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - Label displayNameLabel = new Label(composite, SWT.LEFT); - displayNameLabel.setText(label); - displayNameLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); - Text nameText = new Text(composite, SWT.SINGLE | SWT.BORDER); - nameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - synchHelper.synchText(nameText, property, /*dependentControls*/null); - return nameText; - } - - /** - * Create group - * @param parent the main composite - * @param text the name of the group - * @return the created group - */ - private Group createGroup(Composite parent, String text) { - Group group = new Group(parent, SWT.NONE); - GridData groupGridData = new GridData(GridData.FILL_HORIZONTAL); - groupGridData.horizontalSpan = 3; - group.setLayoutData(groupGridData); - group.setLayout(new GridLayout(3, false)); - group.setText(text); - return group; - } - - /** - * Create check button - * @param parent the main composite - inheritance group - * @param text the label of the button - * @param property the related property to which this button will be synchronized - * @return the created button - */ - private Button createCheckButton(Composite parent, String text, String property) { - final Button button = new Button(parent, SWT.CHECK); - GridData groupGridData = new GridData(GridData.FILL_HORIZONTAL); - groupGridData.horizontalSpan = 3; - button.setLayoutData(groupGridData); - button.setText(text); - button.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - boolean isChecked = button.getSelection(); - if (tableNameText != null) { - tableNameText.setEnabled(!isChecked); - } - } - }); - synchHelper.synchCheckbox(button, property, /*dependentControls*/ null); - return button; - } - - /** - * Create radio button - * @param parent the main composite - inheritance group - * @param text the label of the button - * @param property the related property to which this button will be synchronized - * @return the created button - */ - private Button createRadioButton(Composite parent, String text, String property) { - Button button = new Button(parent, SWT.RADIO); - GridData groupGridData = new GridData(GridData.FILL_HORIZONTAL); - groupGridData.horizontalSpan = 3; - button.setLayoutData(groupGridData); - button.setText(text); - synchHelper.synchRadio(button, property, /*dependentControls*/ null); - return button; - } - - /* - * If a property changes that we want to validate, force validation on this page. - * - * @see org.eclipse.wst.common.frameworks.internal.operation.WTPOperationDataModelListener#propertyChanged(java.lang.String, - * java.lang.Object, java.lang.Object) - */ - @Override - public void propertyChanged(DataModelEvent event) { - String propertyName = event.getPropertyName(); - if (IEntityDataModelProperties.MAPPED_AS_SUPERCLASS.equals(propertyName)) { - initNameGroup(); - } - super.propertyChanged(event); - } - - /** - * The methods is for the internal use only. It will set the entity and table name - * group to be disabled if the created artifact is not entity - */ - private void initNameGroup() { - isNonEntity = model.getBooleanProperty(IEntityDataModelProperties.MAPPED_AS_SUPERCLASS); - if (isButtonsCreated) { - entityNameText.setEnabled(!isNonEntity); - tableNameCheckButton.setEnabled(!isNonEntity); - tableNameText.setEnabled(!tableNameCheckButton.getSelection()); - } - } -} - - diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityRowTableWizardSection.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityRowTableWizardSection.java deleted file mode 100644 index 9228e1200f..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityRowTableWizardSection.java +++ /dev/null @@ -1,739 +0,0 @@ -/*********************************************************************** - * Copyright (c) 2008 by SAP AG, Walldorf. - * 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: - * SAP AG - initial API and implementation - * Dimiter Dimitrov, d.dimitrov@sap.com - initial API and implementation - ***********************************************************************/ -package org.eclipse.jpt.ui.internal.wizards.entity; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.eclipse.jdt.core.IPackageFragmentRoot; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.search.IJavaSearchConstants; -import org.eclipse.jdt.core.search.IJavaSearchScope; -import org.eclipse.jdt.internal.ui.dialogs.FilteredTypesSelectionDialog; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.viewers.CheckStateChangedEvent; -import org.eclipse.jface.viewers.CheckboxTableViewer; -import org.eclipse.jface.viewers.DoubleClickEvent; -import org.eclipse.jface.viewers.ICheckStateListener; -import org.eclipse.jface.viewers.IDoubleClickListener; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredContentProvider; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.ITableLabelProvider; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.window.Window; -import org.eclipse.jpt.ui.internal.wizards.entity.data.model.EntityRow; -import org.eclipse.jpt.ui.internal.wizards.entity.data.model.IEntityDataModelProperties; -import org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties; -import org.eclipse.jst.j2ee.internal.dialogs.TypeSearchEngine; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.ControlAdapter; -import org.eclipse.swt.events.ControlEvent; -import org.eclipse.swt.events.ModifyEvent; -import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Table; -import org.eclipse.swt.widgets.TableColumn; -import org.eclipse.swt.widgets.Text; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; - -/** - * The class presents the table with entity fields. In the java file are included also content - * and label provider, add and edit entity dialogs as well as help internal objects - listener - * and callback from the dialog to the main composite (table). - * - */ -public class EntityRowTableWizardSection extends Composite { - - /** - * The possible entity types, mentioned in the specification (Chapter 2.1.1 Persistent Fields and Properties p.20) - */ - protected final static String[] VALID_TYPES = {"int", "long", "short", "char", "boolean", "byte", "double", "float", "java.lang.String", - "byte[]", "char[]", "java.lang.Byte[]", "java.lang.Character[]", "java.math.BigDecimal", "java.math.BigInteger", "java.sql.Date", "java.sql.Time", "java.sql.Timestamp", - "java.util.Date", "java.util.Calendar"}; - - private CheckboxTableViewer mTableViewer = null; - private Table mTableWidget = null; - private final int PK_COLUMN = 0; - private final int NAME_COLUMN = 1; - private final int TYPE_COLUMN = 2; - - - - - private Button addButton; - private Button editButton; - private Button removeButton; - private String title = EntityWizardMsg.ENTITY_FIELDS_DIALOG_TITLE; - private String[] labelsForCombo = VALID_TYPES; - private String[] labelsForText = new String[]{EntityWizardMsg.TYPE_TEXT_FIELD, EntityWizardMsg.NAME_TEXT_FIELD}; - private IDataModel model; - private String propertyName; - private Image labelProviderImage = null; - private DialogCallback callback; - - - /** - * @param parent the main composite - Entity fields page - * @param model the data model representation - * @param propertyName data property name - */ - public EntityRowTableWizardSection(Composite parent, IDataModel model, String propertyName) { - super(parent, SWT.NONE); - this.model = model; - this.propertyName = propertyName; - - GridLayout layout = new GridLayout(2, false); - layout.marginHeight = 4; - layout.marginWidth = 0; - this.setLayout(layout); - this.setLayoutData(new GridData(GridData.FILL_BOTH)); - - mTableWidget = new Table(this, SWT.CHECK | SWT.FULL_SELECTION | SWT.BORDER); - mTableWidget.setHeaderVisible(true); - mTableWidget.setLinesVisible(true); - - mTableViewer = new CheckboxTableViewer(mTableWidget); - GridData data = new GridData(GridData.FILL_BOTH); - data.verticalSpan = 2; - mTableWidget.setLayoutData(data); - mTableViewer.setContentProvider(new EntityRowContentProvider()); - mTableViewer.setLabelProvider(new EntityRowLabelProvider()); - - final Composite buttonComposition = new Composite(this, SWT.NULL); - layout = new GridLayout(); - layout.marginHeight = 0; - buttonComposition.setLayout(layout); - buttonComposition.setLayoutData(new GridData(GridData.FILL_VERTICAL | GridData.VERTICAL_ALIGN_BEGINNING)); - - addButton = new Button(buttonComposition, SWT.PUSH); - addButton.setText(EntityWizardMsg.ADD_BUTTON_LABEL); - addButton.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.HORIZONTAL_ALIGN_FILL)); - addButton.addSelectionListener(new SelectionListener() { - public void widgetSelected(SelectionEvent event) { - handleAddButtonSelected(); - } - public void widgetDefaultSelected(SelectionEvent event) { - //Do nothing - } - }); - - editButton = new Button(buttonComposition, SWT.PUSH); - editButton.setText(EntityWizardMsg.EDIT_BUTTON_LABEL); - editButton.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.HORIZONTAL_ALIGN_FILL)); - editButton.addSelectionListener(new SelectionListener() { - public void widgetSelected(SelectionEvent event) { - handleEditButtonSelected(); - } - public void widgetDefaultSelected(SelectionEvent event) { - //Do nothing - } - }); - editButton.setEnabled(false); - mTableViewer.addDoubleClickListener(new IDoubleClickListener() { - public void doubleClick(DoubleClickEvent event) { - handleEditButtonSelected(); - } - }); - - removeButton = new Button(buttonComposition, SWT.PUSH); - removeButton.setText(EntityWizardMsg.REMOVE_BUTTON_LABEL); - removeButton.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.HORIZONTAL_ALIGN_FILL)); - removeButton.addSelectionListener(new SelectionListener() { - public void widgetSelected(SelectionEvent event) { - handleRemoveButtonSelected(); - } - public void widgetDefaultSelected(SelectionEvent event) { - //Do nothing - } - }); - removeButton.setEnabled(false); - - mTableViewer.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - ISelection selection = event.getSelection(); - if (editButton != null) { - boolean enabled = ((IStructuredSelection) selection).size() == 1; - editButton.setEnabled(enabled); - } - removeButton.setEnabled(!selection.isEmpty()); - } - }); - - - final TableColumn pkColumn = new TableColumn(mTableWidget, SWT.CHECK); - pkColumn.setText(EntityWizardMsg.KEY); - pkColumn.pack(); - pkColumn.setResizable(false); - - TableColumn nameColumn = new TableColumn(mTableWidget, SWT.NONE); - nameColumn.setText(EntityWizardMsg.NAME_COLUMN); - - TableColumn typeColumn = new TableColumn(mTableWidget, SWT.NONE); - typeColumn.setText(EntityWizardMsg.TYPE_COLUMN); - - this.addControlListener(new ControlAdapter() { - @Override - public void controlResized(ControlEvent e) { - Table table = mTableViewer.getTable(); - TableColumn[] columns = table.getColumns(); - Point buttonArea = buttonComposition.computeSize(SWT.DEFAULT, SWT.DEFAULT); - Rectangle area = table.getParent().getClientArea(); - Point preferredSize = mTableViewer.getTable().computeSize(SWT.DEFAULT, SWT.DEFAULT); - int width = area.width - 2 * table.getBorderWidth()- buttonArea.x - columns.length * 2 - pkColumn.getWidth(); - if (preferredSize.y > area.height + table.getHeaderHeight()) { - // Subtract the scrollbar width from the total column width - // if a vertical scrollbar will be required - Point vBarSize = table.getVerticalBar().getSize(); - width -= vBarSize.x; - } - Point oldSize = table.getSize(); - int consumeWidth = 0; - int col = columns.length - 1; - for (int i = 1; i < columns.length; i++) { - if (oldSize.x > area.width) { - // table is getting smaller so make the columns - // smaller first and then resize the table to - // match the client area width - consumeWidth = setColumntWidth(width, columns, consumeWidth, i); - table.setSize(area.width - buttonArea.x - (col * 2 + pkColumn.getWidth()), area.height); - } else { - // table is getting bigger so make the table - // bigger first and then make the columns wider - // to match the client area width - consumeWidth = setColumntWidth(width, columns, consumeWidth, i); - table.setSize(area.width - buttonArea.x - (col * 2 + pkColumn.getWidth()), area.height); - } - } - } - - private int setColumntWidth(int width, TableColumn[] columns, - int consumeWidth, int i) { - if (i < columns.length - 1) { - columns[i].setWidth(width / (columns.length - 1)); - consumeWidth += columns[i].getWidth(); - } else { - columns[i].setWidth(width - consumeWidth); - } - return consumeWidth; - } - }); - - mTableViewer.addCheckStateListener(new PKFieldCheckStateListener()); - callback = new FieldDialogCallback(); - } - - /** - * This method process the Add... button pressed event. It opens dialog to - * add new entity field - */ - private void handleAddButtonSelected() { - AddFieldDialog dialog = new AddFieldDialog(getShell(), title, labelsForCombo, labelsForText); - int result = dialog.open(); - if (result == Window.CANCEL) { - return; - } - EntityRow entityRow = dialog.getEntityRow(); - addEntityRow(entityRow); - if (!entityRow.couldBeKey()) { - mTableViewer.setGrayed(entityRow, true); - } - } - - /** - * Add new entity to the table input - * - * @param entity - * the entity which have to be added to the table - */ - private void addEntityRow(EntityRow entity) { - if (entity == null) - return; - List<EntityRow> valueList = (ArrayList<EntityRow>) mTableViewer.getInput(); - if (valueList == null) - valueList = new ArrayList<EntityRow>(); - valueList.add(entity); - setInput(valueList); - } - - /** - * This method process the Edit... button pressed event. It opens dialog to edit chosen entity field - */ - private void handleEditButtonSelected() { - ISelection s = mTableViewer.getSelection(); - if (!(s instanceof IStructuredSelection)) - return; - IStructuredSelection selection = (IStructuredSelection) s; - if (selection.size() != 1) - return; - - Object selectedObj = selection.getFirstElement(); - EntityRow entityForEdit = (EntityRow) selectedObj; - int index = mTableWidget.getSelectionIndex(); - boolean isChecked = mTableViewer.getChecked(entityForEdit); - - EditFieldDialog dialog = new EditFieldDialog(getShell(), title, labelsForCombo, labelsForText, entityForEdit); - dialog.open(); - EntityRow entityRow = dialog.getEntityRow(); - if (entityRow != null) { - editEntityRow(index, entityRow); - mTableViewer.setChecked(entityRow, isChecked); - if (!entityRow.couldBeKey()) { - mTableViewer.setChecked(entityRow, false); - mTableViewer.setGrayed(entityRow, true); - } else { - mTableViewer.setGrayed(entityRow, false); - } - } - } - - /** - * Edit chosen entity from the table - * @param index the index of the entity in the table - * @param newEntity the edited entity field - */ - private void editEntityRow(int index, EntityRow newEntity) { - if (newEntity == null) - return; - - List<EntityRow> valueList = (ArrayList<EntityRow>) mTableViewer.getInput(); - if (valueList == null) { - valueList = new ArrayList(); - } - - if (index == -1) { - valueList.add(newEntity); - } else { - valueList.set(index, newEntity); - } - - setInput(valueList); - } - - /** - * This method process the Remove button pressed event. - */ - private void handleRemoveButtonSelected() { - ISelection selection = mTableViewer.getSelection(); - if (selection.isEmpty() || !(selection instanceof IStructuredSelection)) - return; - List selectedObject = ((IStructuredSelection) selection).toList(); - removeEntityRow(selectedObject); - } - - /** - * Removes the selected entities from the table - * @param entities list with entities, which should be removed - */ - private void removeEntityRow(Collection entities) { - List<EntityRow> valueList = (ArrayList<EntityRow>) mTableViewer.getInput(); - valueList.removeAll(entities); - setInput(valueList); - } - - /** - * Set the input of the table - * @param input the list with entities which have to be presented in the table - */ - private void setInput(List input) { - mTableViewer.setInput(input); - // Create a new list to trigger property change - ArrayList<EntityRow> newInput = new ArrayList<EntityRow>(); - newInput.addAll(input); - model.setProperty(propertyName, newInput); - } - - /** - * @return the TableViewer of the table - */ - public TableViewer getTableViewer() { - return mTableViewer; - } - - // PROVIDERS FOR THE FIELD TABLE - - /** - * The content provider for the table items - */ - protected class EntityRowContentProvider implements IStructuredContentProvider { - public boolean isDeleted(Object element) { - return false; - } - public Object[] getElements(Object element) { - if (element instanceof List) { - return ((List) element).toArray(); - } - return new Object[0]; - } - public void inputChanged(Viewer aViewer, Object oldInput, Object newInput) { - //Default nothing - } - public void dispose() { - //Default nothing - } - } - - /** - * The label provider for the table items - */ - protected class EntityRowLabelProvider extends LabelProvider implements ITableLabelProvider { - public Image getColumnImage(Object element, int columnIndex) { - if (columnIndex == 0) { - return labelProviderImage; - } - return null; - } - - public String getColumnText(Object element, int columnIndex) { - EntityRow entity = (EntityRow) element; - if (columnIndex == NAME_COLUMN) { - return entity.getName(); - } - if (columnIndex == TYPE_COLUMN) { - return entity.getFqnTypeName(); - } - if (entity.couldBeKey()) { - mTableViewer.setChecked(entity, entity.isKey()); - } - return ""; - } - - @Override - public Image getImage(Object element) { - return labelProviderImage; - } - - @Override - public String getText(Object element) { - String[] array = (String[]) element; - if (array.length > 0) { - return array[0]; - } else { - return super.getText(element); - } - } - } - // END - PROVIDERS FOR THE FIELD TABLE - - /** - * Listener for the Primary Key check box in the table item - */ - private class PKFieldCheckStateListener implements ICheckStateListener { - - public void checkStateChanged(CheckStateChangedEvent event) { - Object[] checkedElements = mTableViewer.getCheckedElements(); - List<String> pkFields = new ArrayList<String>(); - for (Object object : checkedElements) { - EntityRow entity = (EntityRow)object; - if (entity.couldBeKey()) { - pkFields.add(entity.getName()); - } else { - mTableViewer.setChecked(entity, false); - } - } - model.setProperty(IEntityDataModelProperties.PK_FIELDS, pkFields); - } - - } - - // CALLBACK MECHANISM - /** - * Callback interface used by the Add/Edit-FieldDialog classes. - */ - public interface DialogCallback { - - /** - * Validates the text fields. - * <p>Used to decide whether to enable the OK button of the dialog. - * If the method returns <code>true</code> the OK button is enabled, - * otherwise the OK button is disabled.</p> - * @param combo contains the predefined types - * @param texts the name of the entity field - * @return <code>true</code> if the values in the text fields are - * valid, <code>false</code> otherwise. - */ - public boolean validate(Combo combo, Text[] texts); - - /** - * Retrieves the entity presentation object from the fields of the dialog. - * <p>Implementers of the callback can use these method to do some - * preprocessing (like trimming) of the data in the text fields before - * using it. The returned values will be the actual data that will be - * put in the table viewer.</p> - * @param combo contains the predefined types - * @param texts the name of the entity field - * @return the entity presentation object retrieved from the dialog - */ - public EntityRow retrieveResultStrings(Combo combo, Text[] texts); - - } - - /** - * Implementation of the <code>FieldDialogCallback</code> interface for - * both "Name" and "Types" table columns. - */ - public class FieldDialogCallback implements DialogCallback { - - /** - * The first text field should not be empty. - */ - public boolean validate(Combo combo, Text[] texts) { - if (texts.length > 0) { - return texts[0].getText().trim().length() > 0; - } - return true; - } - - /** - * Just retrieves the unmodified values of the text fields as a - * entity field presentation - * @see org.eclipse.jpt.ui.internal.wizards.entity.data.model.EntityRow - */ - public EntityRow retrieveResultStrings(Combo combo, Text[] texts) { - EntityRow entity = new EntityRow(); - entity.setFqnTypeName(combo.getText()); - entity.setName(texts[0].getText()); - return entity; - } - } - - // THE DIALOGS USED FOR ADD/EDIT OF ENTITY FIELDS - BEGIN - - /** - * The dialog which collect the information (name and type) for the new entity field - */ - private class AddFieldDialog extends Dialog implements ModifyListener, SelectionListener { - protected String windowTitle; - protected String[] labelsForCombo; - protected String[] labelsForText; - protected Text[] texts; - protected EntityRow entityRow; - protected Combo combo; - - /** - * Constructs AddFieldDialog - * @param shell - * @param windowTitle dialog label - * @param labelsForCombo the elements for the combo - * @param labelsForText name text - */ - public AddFieldDialog(Shell shell, String windowTitle, String[] labelsForCombo, String[] labelsForText) { - super(shell); - this.windowTitle = windowTitle; - this.labelsForCombo = labelsForCombo; - this.labelsForText = labelsForText; - } - - /* Create the area of dialog - * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) - */ - @Override - public Control createDialogArea(Composite parent) { - - Composite composite = (Composite) super.createDialogArea(parent); - getShell().setText(windowTitle); - - GridLayout layout = new GridLayout(); - layout.numColumns = 4; - composite.setLayout(layout); - GridData data = new GridData(); - data.verticalAlignment = GridData.FILL; - data.horizontalAlignment = GridData.FILL; - data.widthHint = 300; - composite.setLayoutData(data); - - Label label = new Label(composite, SWT.LEFT); - label.setText(labelsForText[0]); - label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); - - - combo = new Combo(composite, SWT.SINGLE | SWT.BORDER);// | SWT.READ_ONLY); - combo.setItems(labelsForCombo); - data = new GridData(GridData.FILL_HORIZONTAL); - data.horizontalSpan = 2; - combo.setLayoutData(data); - - Button browseButton = new Button(composite, SWT.PUSH); - browseButton.setText(EntityWizardMsg.BROWSE_BUTTON_LABEL); - GridData browseButtonData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - browseButtonData.horizontalSpan = 1; - browseButton.setLayoutData(browseButtonData); - browseButton.addSelectionListener(new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - handleChooseEntityTypeButtonPressed(); - } - - public void widgetDefaultSelected(SelectionEvent e) { - // Do nothing - } - }); - - int n = labelsForText.length; - texts = new Text[n-1]; - for (int i = 1; i < n; i++) { - Label labelI = new Label(composite, SWT.LEFT); - labelI.setText(labelsForText[i]); - labelI.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); - texts[i-1] = new Text(composite, SWT.SINGLE | SWT.BORDER); - data = new GridData(GridData.FILL_HORIZONTAL); - data.widthHint = 100; - texts[i-1].setLayoutData(data); - } - - combo.setFocus(); - Dialog.applyDialogFont(parent); - return composite; - } - - /** - * Process browsing when the Browse... button have been pressed. Allow adding of entity field - * with arbitrary type. - * @see org.eclipse.jdt.internal.ui.dialogs.FilteredTypesSelectionDialog - */ - private void handleChooseEntityTypeButtonPressed() { - //getControl().setCursor(new Cursor(getShell().getDisplay(), SWT.CURSOR_WAIT)); - IPackageFragmentRoot packRoot = (IPackageFragmentRoot) model.getProperty(INewJavaClassDataModelProperties.JAVA_PACKAGE_FRAGMENT_ROOT); - if (packRoot == null) { - return; - } - - // this eliminates the non-exported classpath entries - final IJavaSearchScope scope = TypeSearchEngine.createJavaSearchScopeForAProject(packRoot.getJavaProject(), true, true); - - // This includes all entries on the classpath. - FilteredTypesSelectionDialog dialog = new FilteredTypesSelectionDialog(getShell(), false, null/*getWizard().getContainer()*/, scope, IJavaSearchConstants.TYPE); - dialog.setTitle(EntityWizardMsg.TYPE_DIALOG_TITLE); - dialog.setMessage(EntityWizardMsg.TYPE_DIALOG_DESCRIPTION); - - if (dialog.open() == Window.OK) { - IType type = (IType) dialog.getFirstResult(); - String superclassFullPath = IEntityDataModelProperties.EMPTY_STRING; - if (type != null) { - superclassFullPath = type.getFullyQualifiedName(); - } - combo.setText(superclassFullPath); - //getControl().setCursor(null); - return; - } - //getControl().setCursor(null); - } - - - /* Create the content of the dialog - * @see org.eclipse.jface.dialogs.Dialog#createContents(org.eclipse.swt.widgets.Composite) - */ - @Override - protected Control createContents(Composite parent) { - Composite composite = (Composite) super.createContents(parent); - - combo.addSelectionListener(this); - for (int i = 0; i < texts.length; i++) { - texts[i].addModifyListener(this); - } - - updateOKButton(); - - return composite; - } - - /* Processes OK button pressed event. - * @see org.eclipse.jface.dialogs.Dialog#okPressed() - */ - @Override - protected void okPressed() { - entityRow = callback.retrieveResultStrings(combo, texts); - super.okPressed(); - } - - /** - * @return the entity representation with the information collected from the dialog - */ - public EntityRow getEntityRow() { - return entityRow; - } - - /* Processes text modifying event - * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) - */ - public void modifyText(ModifyEvent e) { - updateOKButton(); - } - - /** - * Sets state of the OK button in accordance with validate method of the callback object - * @see DialogCallback - */ - private void updateOKButton() { - getButton(IDialogConstants.OK_ID).setEnabled(callback.validate(combo, texts)); - } - /* (non-Javadoc) - * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent) - */ - public void widgetDefaultSelected(SelectionEvent e) { - // TODO Auto-generated method stub - - } - /* Update OK button when the appropriate event occurs - * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent) - */ - public void widgetSelected(SelectionEvent e) { - updateOKButton(); - } - } - - /** - * Constructs EditFieldDialog - */ - private class EditFieldDialog extends AddFieldDialog { - protected EntityRow entityRow; - /** - * EditFieldDialog constructor comment. - */ - public EditFieldDialog(Shell shell, String windowTitle, String[] labelsForCombo, String[] labelsForText, EntityRow entity) { - super(shell, windowTitle, labelsForCombo, labelsForText); - this.entityRow = entity; - } - - /* Create the area of the dialog - * @see org.eclipse.jpt.ui.internal.wizards.entity.EntityRowTableWizardSection.AddFieldDialog#createDialogArea(org.eclipse.swt.widgets.Composite) - */ - @Override - public Control createDialogArea(Composite parent) { - - Composite composite = (Composite) super.createDialogArea(parent); - - combo.setText(entityRow.getFqnTypeName()); - texts[0].setText(entityRow.getName()); - - return composite; - } - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityTemplate.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityTemplate.java deleted file mode 100644 index a5309c4a95..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityTemplate.java +++ /dev/null @@ -1,126 +0,0 @@ -package org.eclipse.jpt.ui.internal.wizards.entity; - -import org.eclipse.jpt.ui.internal.wizards.entity.data.model.*; -import java.util.*; - -public class EntityTemplate -{ - protected static String nl; - public static synchronized EntityTemplate create(String lineSeparator) - { - nl = lineSeparator; - EntityTemplate result = new EntityTemplate(); - nl = null; - return result; - } - - public final String NL = nl == null ? (System.getProperties().getProperty("line.separator")) : nl; - protected final String TEXT_1 = "package "; - protected final String TEXT_2 = ";"; - protected final String TEXT_3 = NL; - protected final String TEXT_4 = NL + "import "; - protected final String TEXT_5 = ";"; - protected final String TEXT_6 = NL + NL + "/**" + NL + " * Entity implementation class for Entity: "; - protected final String TEXT_7 = NL + " *" + NL + " */" + NL + "public class "; - protected final String TEXT_8 = " extends "; - protected final String TEXT_9 = " implements "; - protected final String TEXT_10 = ", "; - protected final String TEXT_11 = " {" + NL + "" + NL + "\t"; - protected final String TEXT_12 = " " + NL + "\tprivate "; - protected final String TEXT_13 = " "; - protected final String TEXT_14 = ";"; - protected final String TEXT_15 = NL + "\tprivate static final long serialVersionUID = 1L;\t" + NL + "\tpublic "; - protected final String TEXT_16 = "() {" + NL + "\t\tsuper();" + NL + "\t} " + NL + "\t"; - protected final String TEXT_17 = " " + NL + "\tpublic "; - protected final String TEXT_18 = " get"; - protected final String TEXT_19 = "() {" + NL + " \t\treturn this."; - protected final String TEXT_20 = ";" + NL + "\t}" + NL + "" + NL + "\tpublic void set"; - protected final String TEXT_21 = "("; - protected final String TEXT_22 = " "; - protected final String TEXT_23 = ") {" + NL + "\t\tthis."; - protected final String TEXT_24 = " = "; - protected final String TEXT_25 = ";" + NL + "\t}" + NL + "\t"; - protected final String TEXT_26 = NL + " " + NL + "}"; - protected final String TEXT_27 = NL; - - public String generate(Object argument) - { - final StringBuffer stringBuffer = new StringBuffer(); - CreateEntityTemplateModel model = (CreateEntityTemplateModel) argument; -if (model.getJavaPackageName()!=null && model.getJavaPackageName()!="") { - stringBuffer.append(TEXT_1); - stringBuffer.append(model.getJavaPackageName()); - stringBuffer.append(TEXT_2); - } - stringBuffer.append(TEXT_3); - Collection<String> imports = model.getImports(false); -for (String anImport : imports) { - stringBuffer.append(TEXT_4); - stringBuffer.append(anImport); - stringBuffer.append(TEXT_5); - } - stringBuffer.append(TEXT_6); - stringBuffer.append(model.getEntityName()); - stringBuffer.append(TEXT_7); - stringBuffer.append(model.getClassName()); - String superClass = model.getSuperclassName(); - if (! "".equals(superClass)) { - stringBuffer.append(TEXT_8); - stringBuffer.append(superClass); - } - - List<String> interfaces = model.getInterfaces(); - if (interfaces.size()>0) { - stringBuffer.append(TEXT_9); - } - for (int i=0; i<interfaces.size(); i++) { - String INTERFACE = (String) interfaces.get(i); - if (i>0) { - stringBuffer.append(TEXT_10); - } - stringBuffer.append(INTERFACE); - } - stringBuffer.append(TEXT_11); - List<EntityRow> fields = model.getEntityFields(); - for (EntityRow entity : fields) { - - stringBuffer.append(TEXT_12); - stringBuffer.append(entity.getType()); - stringBuffer.append(TEXT_13); - stringBuffer.append(entity.getName()); - stringBuffer.append(TEXT_14); - } - stringBuffer.append(TEXT_15); - stringBuffer.append(model.getClassName()); - stringBuffer.append(TEXT_16); - - fields = model.getEntityFields(); - if (fields != null) for (int i=0; i<fields.size(); i++) { - EntityRow field = (EntityRow) fields.get(i); - String TYPE = field.getType(); - String NAME = field.getName(); - String METHOD = NAME.substring(0,1).toUpperCase() + NAME.substring(1); - - stringBuffer.append(TEXT_17); - stringBuffer.append(TYPE); - stringBuffer.append(TEXT_18); - stringBuffer.append(METHOD); - stringBuffer.append(TEXT_19); - stringBuffer.append(NAME); - stringBuffer.append(TEXT_20); - stringBuffer.append(METHOD); - stringBuffer.append(TEXT_21); - stringBuffer.append(TYPE); - stringBuffer.append(TEXT_22); - stringBuffer.append(NAME); - stringBuffer.append(TEXT_23); - stringBuffer.append(NAME); - stringBuffer.append(TEXT_24); - stringBuffer.append(NAME); - stringBuffer.append(TEXT_25); - } - stringBuffer.append(TEXT_26); - stringBuffer.append(TEXT_27); - return stringBuffer.toString(); - } -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityWizard.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityWizard.java deleted file mode 100644 index e212dbd707..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityWizard.java +++ /dev/null @@ -1,137 +0,0 @@ -/*********************************************************************** - * Copyright (c) 2008 by SAP AG, Walldorf. - * 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: - * SAP AG - initial API and implementation - * Dimiter Dimitrov, d.dimitrov@sap.com - initial API and implementation - ***********************************************************************/ -package org.eclipse.jpt.ui.internal.wizards.entity; - -import static org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties.*; -import java.lang.reflect.InvocationTargetException; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jpt.ui.JptUiPlugin; -import org.eclipse.jpt.ui.internal.JptUiIcons; -import org.eclipse.jpt.ui.internal.wizards.entity.data.model.EntityDataModelProvider; -import org.eclipse.jst.j2ee.internal.plugin.J2EEEditorUtility; -import org.eclipse.jst.j2ee.internal.project.J2EEProjectUtilities; -import org.eclipse.ui.INewWizard; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.ide.IDE; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; -import org.eclipse.wst.common.frameworks.datamodel.IDataModelProvider; -import org.eclipse.wst.common.frameworks.internal.datamodel.ui.DataModelWizard; - -public class EntityWizard extends DataModelWizard implements INewWizard { - - - private static final String PAGE_ONE = "pageOne"; //$NON-NLS-1$ - private static final String PAGE_TWO = "pageTwo"; //$NON-NLS-1$ - - /** - * Constructs the Entity wizard - * @param model the data model - */ - public EntityWizard(IDataModel model) { - super(model); - setWindowTitle(EntityWizardMsg.ENTITY_WIZARD_TITLE); - setDefaultPageImageDescriptor(JptUiPlugin.getImageDescriptor(JptUiIcons.ENTITY_WIZ_BANNER)); - } - - /** - * Empty constructor - */ - public EntityWizard(){ - this(null); - } - - /* Adds the two pages of the entity wizard - * @see org.eclipse.wst.common.frameworks.internal.datamodel.ui.DataModelWizard#doAddPages() - */ - @Override - protected void doAddPages() { - EntityClassWizardPage page1 = new EntityClassWizardPage( - getDataModel(), - PAGE_ONE, - EntityWizardMsg.ADD_ENTITY_WIZARD_PAGE_DESCRIPTION, - EntityWizardMsg.ADD_ENTITY_WIZARD_PAGE_TITLE, - J2EEProjectUtilities.EJB); - addPage(page1); - EntityFieldsWizardPage page2 = new EntityFieldsWizardPage(getDataModel(), PAGE_TWO); - addPage(page2); - } - - /* Return the default data model provider (EntityDataModelProvider in our case) - * @see org.eclipse.wst.common.frameworks.internal.datamodel.ui.DataModelWizard#getDefaultProvider() - */ - @Override - protected IDataModelProvider getDefaultProvider() { - return new EntityDataModelProvider(); - } - - /* Check whether the mandatory information is set and wizard could finish - * @see org.eclipse.wst.common.frameworks.internal.datamodel.ui.DataModelWizard#canFinish() - */ - @Override - public boolean canFinish() { - return getDataModel().isValid(); - } - - /* - * Override the parent method in order to open the generated entity class in java editor - * @see org.eclipse.wst.common.frameworks.internal.datamodel.ui.DataModelWizard#postPerformFinish() - */ - @Override - protected void postPerformFinish() throws InvocationTargetException { - try { - String className = getDataModel().getStringProperty(QUALIFIED_CLASS_NAME); - IProject p = (IProject) getDataModel().getProperty(PROJECT); - IJavaProject javaProject = J2EEEditorUtility.getJavaProject(p); - IFile file = (IFile) javaProject.findType(className).getResource(); - openEditor(file); - } catch (Exception cantOpen) { - JptUiPlugin.log(cantOpen); - } - } - - /** - * This method is intended for internal use only. It will open the file, sent as parameter - * in its own java editor - * @param file who should be opened - */ - private void openEditor(final IFile file) { - if (getDataModel().getBooleanProperty(OPEN_IN_EDITOR)) { - if (file != null) { - getShell().getDisplay().asyncExec(new Runnable() { - public void run() { - try { - IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); - IDE.openEditor(page, file, true); - } - catch (PartInitException e) { - JptUiPlugin.log(e); - } - } - }); - } - } - } - - /* Implement the abstract method from IWorkbenchWizard - * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection) - */ - public void init(IWorkbench workbench, IStructuredSelection selection) { - getDataModel(); - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityWizardMsg.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityWizardMsg.java deleted file mode 100644 index a393ecaba3..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityWizardMsg.java +++ /dev/null @@ -1,123 +0,0 @@ -/*********************************************************************** - * Copyright (c) 2008 by SAP AG, Walldorf. - * 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: - * SAP AG - initial API and implementation - * Dimiter Dimitrov, d.dimitrov@sap.com - initial API and implementation - ***********************************************************************/ -package org.eclipse.jpt.ui.internal.wizards.entity; - -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; -import org.eclipse.osgi.util.NLS; - -public class EntityWizardMsg extends NLS { - - private static final String BUNDLE_NAME = "jpt_ui_entity_wizard";//$NON-NLS-1$ - private static ResourceBundle resourceBundle; - - public static String ENTITY_WIZARD_TITLE; - public static String ADD_ENTITY_WIZARD_PAGE_TITLE; - public static String ADD_ENTITY_WIZARD_PAGE_DESCRIPTION; - public static String DEFAULT_PACKAGE_WARNING; - public static String ENTITY_PROPERTIES_TITLE; - public static String ENTITY_PROPERTIES_DESCRIPTION; - public static String ENTITY; - public static String MAPPED_AS_SUPERCLASS; - public static String INHERITANCE_GROUP; - public static String INHERITANCE_CHECK_BOX; - public static String XML_STORAGE_GROUP; - public static String XML_SUPPORT; - public static String CHOOSE_XML; - public static String MAPPING_XML_TITLE; - public static String XML_NAME_TITLE; - public static String INVALID_XML_NAME; - public static String CHOOSE_MAPPING_XML_MESSAGE; - public static String TYPE_DIALOG_TITLE; - public static String TYPE_DIALOG_DESCRIPTION; - public static String ENTITY_NAME; - public static String TABLE_NAME; - public static String TABLE_NAME_GROUP; - public static String USE_DEFAULT; - public static String ENTITY_FIELDS_DIALOG_TITLE; - public static String ENTITY_FIELDS_GROUP; - public static String KEY; - public static String NAME_COLUMN; - public static String TYPE_COLUMN; - public static String NAME_TEXT_FIELD; - public static String TYPE_TEXT_FIELD; - public static String BROWSE_BUTTON_LABEL; - public static String ADD_BUTTON_LABEL; - public static String EDIT_BUTTON_LABEL; - public static String REMOVE_BUTTON_LABEL; - public static String DUPLICATED_ENTITY_NAMES_MESSAGE; - public static String ACCESS_TYPE; - public static String FIELD_BASED; - public static String PROPERTY_BASED; - public static String NO_JPA_PROJECTS; - public static String APPLY_CHANGES_TO_PERSISTENCE_XML; - public static String ADD_MAPPED_SUPERCLASS_TO_XML; - public static String ADD_ENTITY_TO_XML; - private EntityWizardMsg() { - // prevent instantiation of class - } - - static { - NLS.initializeMessages(BUNDLE_NAME, EntityWizardMsg.class); - } - - /** - * Returns the resource bundle used by all classes in this Project - */ - public static ResourceBundle getResourceBundle() { - try { - return ResourceBundle.getBundle(BUNDLE_NAME);//$NON-NLS-1$ - } catch (MissingResourceException e) { - // does nothing - this method will return null and getString(String) will return - // the key it was called with - } - return null; - } - - /** - * Returns the externalized string, mapped to this key - * @param key - * @return the text mapped to the key parameter - */ - public static String getString(String key) { - if (resourceBundle == null) { - resourceBundle = getResourceBundle(); - } - - if (resourceBundle != null) { - try { - return resourceBundle.getString(key); - } catch (MissingResourceException e) { - //exception during string obtaining - return "-" + key + "-";//$NON-NLS-2$//$NON-NLS-1$ - } - } - //return key, because the relevant string missing in the bundle - return "+" + key + "+";//$NON-NLS-2$//$NON-NLS-1$ - } - - /** - * Returns the formated string, mapped to this key - * @param key - * @param arguments - * @return the formated text, mapped to this key, with substituted arguments - */ - public static String getString(String key, Object[] arguments) { - try { - return MessageFormat.format(getString(key), arguments); - } catch (IllegalArgumentException e) { - return getString(key); - } - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/IdClassTemplate.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/IdClassTemplate.java deleted file mode 100644 index 1ea33feaff..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/IdClassTemplate.java +++ /dev/null @@ -1,255 +0,0 @@ -package org.eclipse.jpt.ui.internal.wizards.entity; - -import org.eclipse.jpt.ui.internal.wizards.entity.data.model.*; -import java.util.*; - -public class IdClassTemplate -{ - protected static String nl; - public static synchronized IdClassTemplate create(String lineSeparator) - { - nl = lineSeparator; - IdClassTemplate result = new IdClassTemplate(); - nl = null; - return result; - } - - public final String NL = nl == null ? (System.getProperties().getProperty("line.separator")) : nl; - protected final String TEXT_1 = "package "; - protected final String TEXT_2 = ";"; - protected final String TEXT_3 = NL; - protected final String TEXT_4 = NL + "import "; - protected final String TEXT_5 = ";"; - protected final String TEXT_6 = NL + NL + "/**" + NL + " * ID class for entity: "; - protected final String TEXT_7 = NL + " *" + NL + " */ " + NL + "public class "; - protected final String TEXT_8 = " "; - protected final String TEXT_9 = " implements "; - protected final String TEXT_10 = ", "; - protected final String TEXT_11 = " { " + NL + " " + NL + "\t"; - protected final String TEXT_12 = " " + NL + "\tprivate "; - protected final String TEXT_13 = " "; - protected final String TEXT_14 = ";"; - protected final String TEXT_15 = NL + "\tprivate static final long serialVersionUID = 1L;" + NL + "" + NL + "\tpublic "; - protected final String TEXT_16 = "() {}" + NL + "" + NL + "\t"; - protected final String TEXT_17 = NL + NL + "\tpublic "; - protected final String TEXT_18 = " get"; - protected final String TEXT_19 = "() {" + NL + "\t\treturn this."; - protected final String TEXT_20 = ";" + NL + "\t}" + NL + "" + NL + "\tpublic void set"; - protected final String TEXT_21 = "("; - protected final String TEXT_22 = " "; - protected final String TEXT_23 = ") {" + NL + "\t\tthis."; - protected final String TEXT_24 = " = "; - protected final String TEXT_25 = ";" + NL + "\t}" + NL + "\t"; - protected final String TEXT_26 = NL + " " + NL + "\t/*" + NL + "\t * @see java.lang.Object#equals(Object)" + NL + "\t */\t" + NL + "\tpublic boolean equals(Object o) {" + NL + "\t\tif (o == this) {" + NL + "\t\t\treturn true;" + NL + "\t\t}" + NL + "\t\tif (!(o instanceof "; - protected final String TEXT_27 = ")) {" + NL + "\t\t\treturn false;" + NL + "\t\t}" + NL + "\t\t"; - protected final String TEXT_28 = " other = ("; - protected final String TEXT_29 = ") o;" + NL + "\t\treturn true"; - protected final String TEXT_30 = NL + "\t\t\t&& "; - protected final String TEXT_31 = "() == other."; - protected final String TEXT_32 = "()"; - protected final String TEXT_33 = NL + "\t\t\t&& (Double.doubleToLongBits("; - protected final String TEXT_34 = "()) == Double.doubleToLongBits(other."; - protected final String TEXT_35 = "()))"; - protected final String TEXT_36 = NL + "\t\t\t&& (Float.floatToIntBits("; - protected final String TEXT_37 = "()) == Float.floatToIntBits(other."; - protected final String TEXT_38 = "()))"; - protected final String TEXT_39 = NL + "\t\t\t&& ("; - protected final String TEXT_40 = "() == null ? other."; - protected final String TEXT_41 = "() == null : "; - protected final String TEXT_42 = "().equals(other."; - protected final String TEXT_43 = "()))"; - protected final String TEXT_44 = ";" + NL + "\t}" + NL + "\t" + NL + "\t/*\t " + NL + "\t * @see java.lang.Object#hashCode()" + NL + "\t */\t" + NL + "\tpublic int hashCode() {" + NL + "\t\tfinal int prime = 31;" + NL + "\t\tint result = 1;"; - protected final String TEXT_45 = NL + "\t\tresult = prime * result + ("; - protected final String TEXT_46 = "() ? 1 : 0);"; - protected final String TEXT_47 = NL + "\t\tresult = prime * result + "; - protected final String TEXT_48 = "();"; - protected final String TEXT_49 = NL + "\t\tresult = prime * result + ((int) "; - protected final String TEXT_50 = "());"; - protected final String TEXT_51 = NL + "\t\tresult = prime * result + ((int) ("; - protected final String TEXT_52 = "() ^ ("; - protected final String TEXT_53 = "() >>> 32)));"; - protected final String TEXT_54 = NL + "\t\tresult = prime * result + ((int) (Double.doubleToLongBits("; - protected final String TEXT_55 = "() ) ^ (Double.doubleToLongBits("; - protected final String TEXT_56 = "()) >>> 32)));"; - protected final String TEXT_57 = NL + "\t\tresult = prime * result + Float.floatToIntBits("; - protected final String TEXT_58 = "());"; - protected final String TEXT_59 = NL + "\t\tresult = prime * result + ("; - protected final String TEXT_60 = "() == null ? 0 : "; - protected final String TEXT_61 = "().hashCode());"; - protected final String TEXT_62 = NL + "\t\treturn result;" + NL + "\t}" + NL + " " + NL + " " + NL + "}"; - protected final String TEXT_63 = NL; - - public String generate(Object argument) - { - final StringBuffer stringBuffer = new StringBuffer(); - CreateEntityTemplateModel model = (CreateEntityTemplateModel) argument; -if (model.getJavaPackageName()!=null && model.getJavaPackageName()!="") { - stringBuffer.append(TEXT_1); - stringBuffer.append(model.getJavaPackageName()); - stringBuffer.append(TEXT_2); - } - stringBuffer.append(TEXT_3); - Collection<String> imports = model.getImports(true); -for (String anImport : imports) { - stringBuffer.append(TEXT_4); - stringBuffer.append(anImport); - stringBuffer.append(TEXT_5); - } - stringBuffer.append(TEXT_6); - stringBuffer.append(model.getClassName()); - stringBuffer.append(TEXT_7); - stringBuffer.append(model.getIdClassName()); - stringBuffer.append(TEXT_8); - List<String> interfaces = model.getInterfaces(); - if (interfaces.size()>0) { - stringBuffer.append(TEXT_9); - } - for (int i=0; i<interfaces.size(); i++) { - String INTERFACE = (String) interfaces.get(i); - if (i>0) { - stringBuffer.append(TEXT_10); - } - stringBuffer.append(INTERFACE); - } - stringBuffer.append(TEXT_11); - List<EntityRow> fields = model.getEntityFields(); - List<String> pkFields = model.getPKFields(); - for (int i=0; i<fields.size(); i++) { - EntityRow entity = (EntityRow) fields.get(i); - if (!pkFields.contains(entity.getName())) { - continue; - } - - stringBuffer.append(TEXT_12); - stringBuffer.append(entity.getType()); - stringBuffer.append(TEXT_13); - stringBuffer.append(entity.getName()); - stringBuffer.append(TEXT_14); - } - stringBuffer.append(TEXT_15); - stringBuffer.append(model.getIdClassName()); - stringBuffer.append(TEXT_16); - - fields = model.getEntityFields(); - if (fields != null) for (int i=0; i<fields.size(); i++) { - EntityRow field = (EntityRow) fields.get(i); - String TYPE = field.getType(); - String NAME = field.getName(); - if (!pkFields.contains(NAME)) { - continue; - } - String METHOD = NAME.substring(0,1).toUpperCase() + NAME.substring(1); - - stringBuffer.append(TEXT_17); - stringBuffer.append(TYPE); - stringBuffer.append(TEXT_18); - stringBuffer.append(METHOD); - stringBuffer.append(TEXT_19); - stringBuffer.append(NAME); - stringBuffer.append(TEXT_20); - stringBuffer.append(METHOD); - stringBuffer.append(TEXT_21); - stringBuffer.append(TYPE); - stringBuffer.append(TEXT_22); - stringBuffer.append(NAME); - stringBuffer.append(TEXT_23); - stringBuffer.append(NAME); - stringBuffer.append(TEXT_24); - stringBuffer.append(NAME); - stringBuffer.append(TEXT_25); - } - stringBuffer.append(TEXT_26); - stringBuffer.append(model.getIdClassName()); - stringBuffer.append(TEXT_27); - stringBuffer.append(model.getIdClassName()); - stringBuffer.append(TEXT_28); - stringBuffer.append(model.getIdClassName()); - stringBuffer.append(TEXT_29); - if (fields != null) for (int i=0; i<fields.size(); i++) { - EntityRow field = (EntityRow) fields.get(i); - String NAME = field.getName(); - if (!pkFields.contains(NAME)) { - continue; - } - String TYPE = field.getType(); - String GET_METHOD = "get" + NAME.substring(0,1).toUpperCase() + NAME.substring(1); - if (TYPE.equals("boolean") || TYPE.equals("byte") || TYPE.equals("char") || TYPE.equals("short") || TYPE.equals("int") || TYPE.equals("long")) { - stringBuffer.append(TEXT_30); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_31); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_32); - } else if (TYPE.equals("double")) { - stringBuffer.append(TEXT_33); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_34); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_35); - } else if (TYPE.equals("float")) { - stringBuffer.append(TEXT_36); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_37); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_38); - } else { - stringBuffer.append(TEXT_39); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_40); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_41); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_42); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_43); - } - } - stringBuffer.append(TEXT_44); - if (fields != null) for (int i=0; i<fields.size(); i++) { - EntityRow field = (EntityRow) fields.get(i); - String NAME = field.getName(); - if (!pkFields.contains(NAME)) { - continue; - } - String TYPE = field.getType(); - String GET_METHOD = "get" + NAME.substring(0,1).toUpperCase() + NAME.substring(1); - if (TYPE.equals("boolean")) { - stringBuffer.append(TEXT_45); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_46); - } else if (TYPE.equals("int")) { - stringBuffer.append(TEXT_47); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_48); - } else if (TYPE.equals("byte") || TYPE.equals("char") || TYPE.equals("short")) { - stringBuffer.append(TEXT_49); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_50); - } else if (TYPE.equals("long")) { - stringBuffer.append(TEXT_51); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_52); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_53); - } else if (TYPE.equals("double")) { - stringBuffer.append(TEXT_54); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_55); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_56); - } else if (TYPE.equals("float")) { - stringBuffer.append(TEXT_57); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_58); - } else { - stringBuffer.append(TEXT_59); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_60); - stringBuffer.append(GET_METHOD); - stringBuffer.append(TEXT_61); - } - } - stringBuffer.append(TEXT_62); - stringBuffer.append(TEXT_63); - return stringBuffer.toString(); - } -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/model/CreateEntityTemplateModel.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/model/CreateEntityTemplateModel.java deleted file mode 100644 index 5937f91978..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/model/CreateEntityTemplateModel.java +++ /dev/null @@ -1,384 +0,0 @@ -/*********************************************************************** - * Copyright (c) 2008 by SAP AG, Walldorf. - * 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: - * SAP AG - initial API and implementation - * Dimiter Dimitrov, d.dimitrov@sap.com - initial API and implementation - ***********************************************************************/ -package org.eclipse.jpt.ui.internal.wizards.entity.data.model; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.TreeSet; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.jdt.core.IPackageFragmentRoot; -import org.eclipse.jdt.core.Signature; -import org.eclipse.jem.util.emf.workbench.ProjectUtilities; -import org.eclipse.jpt.core.JptCorePlugin; -import org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties; -import org.eclipse.jst.j2ee.internal.project.J2EEProjectUtilities; -import org.eclipse.wst.common.componentcore.internal.operation.IArtifactEditOperationDataModelProperties; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; - -public class CreateEntityTemplateModel { - - protected IDataModel dataModel; - - private static final String DOT = "."; //$NON-NLS-1$ - private static final String BRACKET = "["; //$NON-NLS-1$ - private static final String PK_SUFFIX = "PK"; //$NON-NLS-1$ - private static final String QUALIFIED_SERIALIZABLE = "java.io.Serializable"; //$NON-NLS-1$ - private static final String PERSISTENCE_PACKAGE = "javax.persistence.*"; //$NON-NLS-1$ - private static final String ENTITY_ANNOTATION = "@Entity"; //$NON-NLS-1$ - private static final String MAPPED_AS_SUPERCLASS_TYPE = "@MappedSuperclass"; //$NON-NLS-1$ - private static final String INHERITANCE_TYPE = "@Inheritance"; //$NON-NLS-1$ - - /** - * Constructs entity model as expansion of the data model - * @param dataModel - */ - public CreateEntityTemplateModel(IDataModel dataModel) { - this.dataModel = dataModel; - } - - /** - * Returns the necessary imports on depends of entity (primary keys) fields. It is used from - * JET emmiter when it generates entity (IdClass) - * @param isIdClass flag, which indicates the case. When it is false, the result is - * the import list for the entity class, in other case the results is the set for the IdClass - * generation - * @return the imports collection with the imports for the generated java class - */ - public Collection<String> getImports(boolean isIdClass) { - Collection<String> collection = new TreeSet<String>(); - - String className = getClassName(); - String superclassName = getQualifiedSuperclassName(); - - if (superclassName != null && superclassName.length() > 0 && - !equalSimpleNames(className, superclassName)) { - collection.add(superclassName); - } - - List interfaces = getQualifiedInterfaces(); - if (interfaces != null) { - Iterator iterator = interfaces.iterator(); - while (iterator.hasNext()) { - String iface = (String) iterator.next(); - if (!equalSimpleNames(getClassName(), iface)) { - collection.add(iface); - } - } - } - if (isIdClass) { - collection.addAll(getIdClassImportList()); - } else { - collection.add(PERSISTENCE_PACKAGE); - collection.addAll(getFieldImportList()); - - } - return collection; - } - - /** - * @return class name of the entity - */ - public String getClassName() { - return getProperty(INewJavaClassDataModelProperties.CLASS_NAME).trim(); - } - - /** - * @return package name when the entity will be generated - */ - public String getJavaPackageName() { - return getProperty(INewJavaClassDataModelProperties.JAVA_PACKAGE).trim(); - } - - /** - * @return fully qualified java class name - */ - public String getQualifiedJavaClassName() { - if (!getJavaPackageName().equals(IEntityDataModelProperties.EMPTY_STRING)) { - return getJavaPackageName() + DOT + getClassName(); - } - return getClassName(); - } - - /** - * @return the name - */ - public String getSuperclassName() { - String qualified = getQualifiedSuperclassName(); - if (equalSimpleNames(getClassName(), qualified)) { - return qualified; - } else { - return Signature.getSimpleName(qualified); - } - } - - /** - * @return fully qualified name of the entity's super class - */ - public String getQualifiedSuperclassName() { - return getProperty(INewJavaClassDataModelProperties.SUPERCLASS).trim(); - } - - /** - * @return list with the interfaces implemented from entity class - */ - public List<String> getInterfaces() { - List qualifiedInterfaces = getQualifiedInterfaces(); - List<String> interfaces = new ArrayList<String>(qualifiedInterfaces.size()); - - Iterator iter = qualifiedInterfaces.iterator(); - while (iter.hasNext()) { - String qualified = (String) iter.next(); - if (equalSimpleNames(getClassName(), qualified)) { - interfaces.add(qualified); - } else { - interfaces.add(Signature.getSimpleName(qualified)); - } - } - - return interfaces; - } - - /** - * @return list with the interfaces (fully qualified named) implemented from entity class - */ - public List getQualifiedInterfaces() { - List interfaces = (List) this.dataModel.getProperty(INewJavaClassDataModelProperties.INTERFACES); - if (interfaces == null){ - interfaces = new ArrayList(); - } - interfaces.add(QUALIFIED_SERIALIZABLE); - return interfaces; - } - - /** - * Returns the value of the specified string property - * @param propertyName - * @return string value of teh specified propert - */ - protected String getProperty(String propertyName) { - return dataModel.getStringProperty(propertyName); - } - - /** - * This methods is used for the comparison of fully qualified types - * @param name1 first type name - * @param name2 second type name - * @return whether the simple names of the types are equal - */ - protected boolean equalSimpleNames(String name1, String name2) { - String simpleName1 = Signature.getSimpleName(name1); - String simpleName2 = Signature.getSimpleName(name2); - return simpleName1.equals(simpleName2); - } - - /** - * @return the type of the artifact - Entity or Mapped superclass - */ - public String getArtifactType() { - if(dataModel.getBooleanProperty(IEntityDataModelProperties.MAPPED_AS_SUPERCLASS)) { - return MAPPED_AS_SUPERCLASS_TYPE; - } - return ENTITY_ANNOTATION; - } - - /** - * @return whether entity set inheritance strategy - */ - public boolean isInheritanceSet() { - return dataModel.getBooleanProperty(IEntityDataModelProperties.INHERITANCE); - } - - /** - * @return the name of the inheritance strategy, as it is defined in the specification - */ - public String getInheritanceStrategyName() { - return getProperty(IEntityDataModelProperties.INHERITANCE_STRATEGY); - } - - /** - * @return the constructed @Inheritance annotation with the relevant strategy - * if it is chosen - */ - public String getInheritanceStrategy() { - String result = IEntityDataModelProperties.EMPTY_STRING; - if (isInheritanceSet()) { - result = INHERITANCE_TYPE; - if (!getProperty(IEntityDataModelProperties.INHERITANCE_STRATEGY).equals(IEntityDataModelProperties.EMPTY_STRING)) { //$NON-NLS-1$ - result += "(strategy=InheritanceType." + getProperty(IEntityDataModelProperties.INHERITANCE_STRATEGY) + ")"; //$NON-NLS-1$ $NON-NLS-2$ - - } - } - return result; - } - - /** - * @return whether the generated artifact is not entity - */ - public boolean isNonEntitySuperclass() { - return !dataModel.getBooleanProperty(IEntityDataModelProperties.ENTITY); - } - - /** - * @return true the created artifact will be annotated - * @return false the entity mappings will be registered in XML - */ - public boolean isArtifactsAnnotated() { - return !dataModel.getBooleanProperty(IEntityDataModelProperties.XML_SUPPORT); - } - - public boolean isMappingXMLDefault() { - if (getMappingXMLName().equals(IEntityDataModelProperties.EMPTY_STRING)) { - return true; - } - return getMappingXMLName().equals(JptCorePlugin.getDefaultOrmXmlDeploymentURI(getProject())); - } - - public String getMappingXMLName() { - return dataModel.getStringProperty(IEntityDataModelProperties.XML_NAME).trim(); - } - - public IFile getMappingXmlFile() { - IFile ormFile = null; - IProject project = getProject(); - IPackageFragmentRoot[] sourceFragments = J2EEProjectUtilities.getSourceContainers(project); - for (IPackageFragmentRoot packageFragmentRoot : sourceFragments) { - ormFile = project.getFile(packageFragmentRoot.getResource().getName() + File.separator + getMappingXMLName()); - if (ormFile.exists()) { - break; - } - } - return ormFile; - } - - /** - * @return the entity name (could be different from the class name) - * See <code>isEntityNameSet()<code> - */ - public String getEntityName() { - return getProperty(IEntityDataModelProperties.ENTITY_NAME).trim(); - } - - /** - * @return whether the entity name is different than class name - */ - public boolean isEntityNameSet() { - boolean result = false; - if (!getClassName().equals(getEntityName())) { - result = true; - } - return result; - } - - /** - * @return whether the table name is specified explicitly - */ - public boolean isTableNameSet() { - return !dataModel.getBooleanProperty(IEntityDataModelProperties.TABLE_NAME_DEFAULT); - } - - /** - * @return the table name (if it is specified) - * See <code>isTableNameSet()<code> - */ - public String getTableName() { - return getProperty(IEntityDataModelProperties.TABLE_NAME).trim(); - } - - /** - * @return list with the entity fields - */ - public List<EntityRow> getEntityFields() { - ArrayList<EntityRow> fields = (ArrayList<EntityRow>) dataModel.getProperty(IEntityDataModelProperties.ENTITY_FIELDS); - if (fields == null){ - return new ArrayList<EntityRow>(); - } else - return fields; - } - - /** - * @return list with the imports necessary for the entity (based on its fields) - */ - public List<String> getFieldImportList() { - List<String> imports = new ArrayList<String>(); - List<EntityRow> entities = getEntityFields(); - for (EntityRow entityRow : entities) { - if (!imports.contains(entityRow.getFqnTypeName()) && !entityRow.getType().equals(entityRow.getFqnTypeName())) { - String fqnTypeName = entityRow.getFqnTypeName(); - //remove the array brackets [] for the java.lang.Byte[] & java.lang.Character[] - if (fqnTypeName.indexOf(BRACKET) != -1) { - fqnTypeName = fqnTypeName.substring(0, fqnTypeName.indexOf("[")); - } - imports.add(fqnTypeName); - } - } - return imports; - } - /** - * @return list with the imports necessary for the id class (based on its fields - primary keys of the entity) - */ - public List<String> getIdClassImportList() { - List<String> imports = new ArrayList<String>(); - List<EntityRow> entities = getEntityFields(); - List<String> pkFields = getPKFields(); - for (EntityRow entityRow : entities) { - String name = entityRow.getName(); - if (pkFields.contains(name)) { - if (!imports.contains(entityRow.getFqnTypeName()) && !entityRow.getType().equals(entityRow.getFqnTypeName())) { - imports.add(entityRow.getFqnTypeName()); - } - } - } - return imports; - } - - /** - * @return whether the access type is field based - */ - public boolean isFieldAccess() { - return dataModel.getBooleanProperty(IEntityDataModelProperties.FIELD_ACCESS_TYPE); - } - - /** - * @return the primary key is composite (more than one annotated as primary key field) - */ - public boolean isCompositePK() { - return getPKFields().size() > 1; - } - - /** - * @return list with primary key name(s) - */ - public List<String> getPKFields() { - return (ArrayList<String>)dataModel.getProperty(IEntityDataModelProperties.PK_FIELDS); - } - - /** - * @return constructed name of the id class (entity name + PK as suffix) - */ - public String getIdClassName() { - return getClassName() + PK_SUFFIX; - } - - /** - * @return IProject presentation of JPA project - */ - public IProject getProject() { - String projectName = dataModel.getStringProperty(IArtifactEditOperationDataModelProperties.PROJECT_NAME); - return ProjectUtilities.getProject(projectName); - } - - -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/model/EntityDataModelProvider.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/model/EntityDataModelProvider.java deleted file mode 100644 index 96908780f7..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/model/EntityDataModelProvider.java +++ /dev/null @@ -1,243 +0,0 @@ -/*********************************************************************** - * Copyright (c) 2008 by SAP AG, Walldorf. - * 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: - * SAP AG - initial API and implementation - * Dimiter Dimitrov, d.dimitrov@sap.com - initial API and implementation - ***********************************************************************/ -package org.eclipse.jpt.ui.internal.wizards.entity.data.model; - -import java.util.ArrayList; -import java.util.Set; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.jdt.core.JavaConventions; -import org.eclipse.jem.util.emf.workbench.ProjectUtilities; -import org.eclipse.jpt.core.internal.resource.orm.OrmXmlResourceProvider; -import org.eclipse.jpt.core.resource.orm.OrmXmlResource; -import org.eclipse.jpt.ui.JptUiPlugin; -import org.eclipse.jpt.ui.internal.wizards.entity.EntityWizardMsg; -import org.eclipse.jpt.ui.internal.wizards.entity.data.operation.NewEntityClassOperation; -import org.eclipse.jst.j2ee.internal.common.J2EECommonMessages; -import org.eclipse.jst.j2ee.internal.common.operations.NewJavaClassDataModelProvider; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; -import org.eclipse.wst.common.frameworks.datamodel.IDataModelOperation; -import org.eclipse.wst.common.frameworks.internal.plugin.WTPCommonPlugin; - -public class EntityDataModelProvider extends NewJavaClassDataModelProvider implements IEntityDataModelProperties{ - - @Override - public IDataModelOperation getDefaultOperation() { - return new NewEntityClassOperation(getDataModel()); - } - - /** - * Extends: <code>IDataModelProvider#getPropertyNames()</code> - * and add own data model's properties specific for the entity model - * - * @see org.eclipse.wst.common.frameworks.datamodel.IDataModelProvider#getPropertyNames() - */ - @Override - public Set getPropertyNames() { - Set propertyNames = super.getPropertyNames(); - propertyNames.add(INHERITANCE); - propertyNames.add(ENTITY); - propertyNames.add(MAPPED_AS_SUPERCLASS); - propertyNames.add(INHERITANCE_STRATEGY); - propertyNames.add(XML_SUPPORT); - propertyNames.add(XML_NAME); - propertyNames.add(ENTITY_NAME); - propertyNames.add(TABLE_NAME_DEFAULT); - propertyNames.add(TABLE_NAME); - propertyNames.add(ENTITY_FIELDS); - propertyNames.add(PK_FIELDS); - propertyNames.add(FIELD_ACCESS_TYPE); - propertyNames.add(PROPERTY_ACCESS_TYPE); - return propertyNames; - } - - /** - * Returns the default value of the parameter (which should present a valid data model property). - * This method does not accept a null parameter. It may return null. - * - * @see NewJavaClassDataModelProvider#getDefaultProperty(String) - * @see IDataModelProvider#getDefaultProperty(String) - * - * @param propertyName - * @return Object default value of property - */ - @Override - public Object getDefaultProperty(String propertyName) { - if (propertyName.equals(INHERITANCE)) { - return Boolean.FALSE; - } else if (propertyName.equals(ENTITY)) { - return Boolean.TRUE; - } else if (propertyName.equals(MAPPED_AS_SUPERCLASS)) { - return Boolean.FALSE; - } else if (propertyName.equals(XML_SUPPORT)) { - return Boolean.FALSE; - } else if (propertyName.equals(XML_NAME)) { - return EMPTY_STRING; - } else if (propertyName.equals(ENTITY_NAME)) { - return getStringProperty(CLASS_NAME); - } else if (propertyName.equals(TABLE_NAME_DEFAULT)) { - return Boolean.TRUE; - } else if (propertyName.equals(TABLE_NAME)) { - return getStringProperty(CLASS_NAME); - } else if (propertyName.equals(INHERITANCE_STRATEGY)) { - return EMPTY_STRING; - } else if (propertyName.equals(SUPERCLASS)) { - return EMPTY_STRING; - } else if (propertyName.equals(ENTITY_FIELDS)) { - return new ArrayList<EntityRow>(); - } else if (propertyName.equals(PK_FIELDS)) { - return new ArrayList<String>(); - } else if (propertyName.equals(FIELD_ACCESS_TYPE)) { - return Boolean.TRUE; - } else if (propertyName.equals(PROPERTY_ACCESS_TYPE)) { - return Boolean.FALSE; - } - // Otherwise check super for default value for property - return super.getDefaultProperty(propertyName); - } - - @Override - public boolean propertySet(String propertyName, Object propertyValue) { - boolean ok = super.propertySet(propertyName, propertyValue); - if (propertyName.equals(PROJECT_NAME) || propertyName.equals(XML_SUPPORT)) { - this.model.notifyPropertyChange(XML_NAME, IDataModel.VALID_VALUES_CHG); - } - return ok; - } - - /* Adds additional check to the model validation - * @see org.eclipse.jst.j2ee.internal.common.operations.NewJavaClassDataModelProvider#validate(java.lang.String) - */ - @Override - public IStatus validate(String propertyName) { - IStatus result = super.validate(propertyName); - if (propertyName.equals(JAVA_PACKAGE)) { - return validateJavaPackage(getStringProperty(propertyName)); - } - if (propertyName.equals(SUPERCLASS) && EMPTY_STRING.equals(getStringProperty(propertyName))) { - return WTPCommonPlugin.OK_STATUS; - } - if (propertyName.equals(XML_NAME)) { - return validateXmlName(getStringProperty(propertyName)); - } - if (propertyName.equals(ENTITY_FIELDS)) { - return validateFieldsList((ArrayList<EntityRow>) getProperty(propertyName)); - } - return result; - } - - /** - * This method is intended for internal use only. It will be used to validate the correctness of entity package - * in accordance with Java convention requirements. This method will accept a null parameter. - * - * @see NewFilterClassDataModelProvider#validate(String) - * - * @param packName - * @return IStatus is the package name satisfies Java convention requirements - */ - - private IStatus validateJavaPackage(String packName) { - if (packName == null || packName.equals(EMPTY_STRING)) { - return WTPCommonPlugin.createWarningStatus(EntityWizardMsg.DEFAULT_PACKAGE_WARNING); - } - // 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; - } - - /** - * This method is intended for internal use only. It will be used to validate - * the correctness of xml file location. - * This method will accept a null parameter. - * - * @see NewFilterClassDataModelProvider#validate(String) - * - * @param xmlName - * @return IStatus is the package name satisfies Java convention requirements - */ - private IStatus validateXmlName(String xmlName) { - if (getBooleanProperty(XML_SUPPORT)) { - String projectName = model.getStringProperty(PROJECT_NAME); - IProject project = ProjectUtilities.getProject(projectName); - if (project != null) { - OrmXmlResourceProvider modelProvider = OrmXmlResourceProvider.getXmlResourceProvider(project, xmlName); - OrmXmlResource ormResource = modelProvider.getXmlResource(); - if (!ormResource.exists()) { - return new Status( - IStatus.ERROR, JptUiPlugin.PLUGIN_ID, - EntityWizardMsg.INVALID_XML_NAME); - - } - } - } - return Status.OK_STATUS; - } - - - /** - * This method is intended for internal use only. It will be used to validate the entity fields - * list to ensure there are not any duplicates. This method will accept a null parameter. - * - * @see NewFilterClassDataModelProvider#validate(String) - * - * @param entities - * @return IStatus is the fields names are unique - */ - private IStatus validateFieldsList(ArrayList<EntityRow> entities) { - if (entities != null && !entities.isEmpty()) { - // Ensure there are not duplicate entries in the list - boolean dup = hasDuplicatesInEntityFields(entities); - if (dup) { - String msg = EntityWizardMsg.DUPLICATED_ENTITY_NAMES_MESSAGE; - return WTPCommonPlugin.createErrorStatus(msg); - } - } - // Return OK - return WTPCommonPlugin.OK_STATUS; - } - - /** - * This method is intended for internal use only. It provides a simple algorithm for detecting - * if there are duplicate entries in a list. It will accept a null parameter. It will return - * boolean. - * - * @param input - * @return boolean are there duplications in the list - */ - private boolean hasDuplicatesInEntityFields(ArrayList<EntityRow> input) { - if (input == null) { - return false; - } - int n = input.size(); - // nested for loops to check each element to see if other elements are the same - for (int i = 0; i < n; i++) { - EntityRow entity = input.get(i); - for (int j = i + 1; j < n; j++) { - EntityRow intEntity = input.get(j); - if (intEntity.getName().equals(entity.getName())) { - return true; - } - - } - } - return false; - } -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/model/EntityRow.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/model/EntityRow.java deleted file mode 100644 index 52d7b0ddc5..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/model/EntityRow.java +++ /dev/null @@ -1,217 +0,0 @@ -/*********************************************************************** - * Copyright (c) 2008 by SAP AG, Walldorf. - * 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: - * SAP AG - initial API and implementation - * Dimiter Dimitrov, d.dimitrov@sap.com - initial API and implementation - ***********************************************************************/ -package org.eclipse.jpt.ui.internal.wizards.entity.data.model; - -import java.util.Arrays; -import java.util.List; - -public class EntityRow { - - private static final String DOT = "."; - private boolean key = false; - private String name = ""; - private String type = ""; - private String fqnTypeName = ""; - private boolean isSimpleType = false; - - private final static String[] PK_TYPES = {"int", "long", "short", "char", "boolean", "byte", "double", "float", - "java.lang.String", "java.sql.Date", "java.util.Date", "java.lang.Integer", "java.lang.Long", "java.lang.Short", - "java.lang.Character", "java.lang.Boolean", "java.lang.Byte", "java.lang.Double", "java.lang.Float"}; - - private final static List<String> VALID_PK_TYPES = Arrays.asList(PK_TYPES); - - - /** - * Constructs <code>EntityColumn</code>. - */ - public EntityRow() { - super(); - } - - - /** - * - * Constructs <code>EntityColumn</code> with the following parameters - * - * @param fqnTypeName - fully qualified name of the entity field type - * @param name - name of the entity field - * @param isKey - flag which indicates whether the entity field is primary key or part of composite primary key - */ - public EntityRow(String fqnTypeName, String name, boolean isKey) { - super(); - this.fqnTypeName = type; - this.name = name; - this.key = isKey; - if (fqnTypeName.indexOf(DOT) == -1) { - type = fqnTypeName; - isSimpleType = true; - } else { - type = getSimpleName(fqnTypeName); - } - } - - - /** - * @return whether the presented entity field is primary key or part of composite primary key - */ - public boolean isKey() { - return key; - } - - /** - * Sets the presented entity field to be primary key (or part of composite primari key) - * - * @param key - */ - public void setKey(boolean key) { - this.key = key; - } - - /** - * Check whether the type of the entity is allowed to be primary key. - * The limitation in the current implementation is that Embedded PK are not checked - * @return whether the type of field could be used as primary key - */ - public boolean couldBeKey() { - boolean result = false; - result = VALID_PK_TYPES.contains(getFqnTypeName()); - return result; - } - - /** - * @return the name of the entity field - */ - public String getName() { - return name; - } - - /** - * Sets the name of the presented entity field - * @param name - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the type (as a simple name) of the entity field - */ - public String getType() { - return type; - } - - /** - * Sets the type (as a simple name) of the entity field - * - * @param type - */ - public void setType(String type) { - this.type = type; - } - - /** - * @return the type (as fully qualified name) of the entity field - */ - public String getFqnTypeName() { - return fqnTypeName; - } - - /** - * Sets the fully qualified type name of the entity field - * - * @param fqnTypeName - */ - public void setFqnTypeName(String fqnTypeName) { - this.fqnTypeName = fqnTypeName; - if (fqnTypeName.indexOf(DOT) == -1) { - setType(fqnTypeName); - setSimpleType(true); - } else { - setType(getSimpleName(fqnTypeName)); - } - - } - - /** - * @return is the type of the entity field is primitive type - */ - public boolean isSimpleType() { - return isSimpleType; - } - - /** - * Sets the flag which indicate the type of the entity field as primitive type - * - * @param isSimpleType - */ - public void setSimpleType(boolean isSimpleType) { - this.isSimpleType = isSimpleType; - } - - /** - * @return whether the type of the entity field is boolean. The information could be used - * when the name of getter should be constructed - */ - public boolean isBoolean() { - return "boolean".equals(getType()); - } - - /** - * For internal purpose only - * Convert fully qualified name to the simple one - * @param fullyName - * @return the simple name form the fully qualified name parameter(last segment) - */ - private String getSimpleName(String fullyName) { - return fullyName.substring(fullyName.lastIndexOf(DOT) + 1); - - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((fqnTypeName == null) ? 0 : fqnTypeName.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - /* - * Implement equals, depending from name of the entity field and its type. - * The type is presented from the fully qualified name - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final EntityRow other = (EntityRow) obj; - if (fqnTypeName == null) { - if (other.fqnTypeName != null) - return false; - } else if (!fqnTypeName.equals(other.fqnTypeName)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/model/IEntityDataModelProperties.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/model/IEntityDataModelProperties.java deleted file mode 100644 index 9a03daa303..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/model/IEntityDataModelProperties.java +++ /dev/null @@ -1,33 +0,0 @@ -/*********************************************************************** - * Copyright (c) 2008 by SAP AG, Walldorf. - * 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: - * SAP AG - initial API and implementation - * Dimiter Dimitrov, d.dimitrov@sap.com - initial API and implementation - ***********************************************************************/ -package org.eclipse.jpt.ui.internal.wizards.entity.data.model; - -import org.eclipse.jst.j2ee.application.internal.operations.IAnnotationsDataModel; -import org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties; - -public interface IEntityDataModelProperties extends INewJavaClassDataModelProperties, IAnnotationsDataModel { - - public static final String ENTITY = "IEntityDataModelProperties.ENTITY"; //$NON-NLS-1$ - public static final String MAPPED_AS_SUPERCLASS = "IEntityDataModelProperties.MAPPED_AS_SUPERCLASS"; //$NON-NLS-1$ - public static final String INHERITANCE = "IEntityDataModelProperties.INHERITANCE"; //$NON-NLS-1$ - public static final String INHERITANCE_STRATEGY = "IEntityDataModelProperties.INHERITANCE_STRATEGY"; //$NON-NLS-1$ - public static final String XML_SUPPORT = "IEntityDataModelProperties.XML_SUPPORT"; //$NON-NLS-1$XML_SUPPORT - public static final String XML_NAME = "IEntityDataModelProperties.XML_NAME"; //$NON-NLS-1$XML_SUPPORT - public static final String ENTITY_NAME = "IEntityDataModelProperties.ENTITY_NAME"; //$NON-NLS-1$ - public static final String TABLE_NAME_DEFAULT = "IEntityDataModelProperties.TABLE_NAME_DEFAULT"; //$NON-NLS-1$ - public static final String TABLE_NAME = "IEntityDataModelProperties.TABLE_NAME"; //$NON-NLS-1$ - public static final String ENTITY_FIELDS = "IEntityDataModelProperties.ENTITY_FIELDS"; //$NON-NLS-1$ - public static final String PK_FIELDS = "IEntityDataModelProperties.PK_FIELDS"; //$NON-NLS-1$ - public static final String FIELD_ACCESS_TYPE = "IEntityDataModelProperties.FIELD_ACCESS_TYPE"; //$NON-NLS-1$ - public static final String PROPERTY_ACCESS_TYPE = "IEntityDataModelProperties.PROPERTY_ACCESS_TYPE"; //$NON-NLS-1$ - public static final String EMPTY_STRING = ""; //$NON-NLS-1$ -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/operation/NewEntityClassOperation.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/operation/NewEntityClassOperation.java deleted file mode 100644 index 359931186d..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/operation/NewEntityClassOperation.java +++ /dev/null @@ -1,605 +0,0 @@ -/*********************************************************************** - * Copyright (c) 2008 by SAP AG, Walldorf. - * 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: - * SAP AG - initial API and implementation - * Dimiter Dimitrov, d.dimitrov@sap.com - initial API and implementation - ***********************************************************************/ -package org.eclipse.jpt.ui.internal.wizards.entity.data.operation; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.core.resources.IFile; -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.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.emf.codegen.jet.JETEmitter; -import org.eclipse.emf.codegen.jet.JETException; -import org.eclipse.emf.common.util.EList; -import org.eclipse.jdt.core.ICompilationUnit; -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.jem.util.logger.proxy.Logger; -import org.eclipse.jpt.core.JptCorePlugin; -import org.eclipse.jpt.core.internal.resource.orm.OrmXmlResourceProvider; -import org.eclipse.jpt.core.internal.resource.persistence.PersistenceXmlResourceProvider; -import org.eclipse.jpt.core.resource.orm.AccessType; -import org.eclipse.jpt.core.resource.orm.Attributes; -import org.eclipse.jpt.core.resource.orm.Inheritance; -import org.eclipse.jpt.core.resource.orm.InheritanceType; -import org.eclipse.jpt.core.resource.orm.OrmFactory; -import org.eclipse.jpt.core.resource.orm.OrmPackage; -import org.eclipse.jpt.core.resource.orm.OrmXmlResource; -import org.eclipse.jpt.core.resource.orm.XmlEntity; -import org.eclipse.jpt.core.resource.orm.XmlEntityMappings; -import org.eclipse.jpt.core.resource.orm.XmlIdClass; -import org.eclipse.jpt.core.resource.orm.XmlIdImpl; -import org.eclipse.jpt.core.resource.orm.XmlMappedSuperclass; -import org.eclipse.jpt.core.resource.orm.XmlTable; -import org.eclipse.jpt.core.resource.persistence.PersistenceFactory; -import org.eclipse.jpt.core.resource.persistence.PersistenceXmlResource; -import org.eclipse.jpt.core.resource.persistence.XmlJavaClassRef; -import org.eclipse.jpt.core.resource.persistence.XmlMappingFileRef; -import org.eclipse.jpt.core.resource.persistence.XmlPersistence; -import org.eclipse.jpt.core.resource.persistence.XmlPersistenceUnit; -import org.eclipse.jpt.ui.JptUiPlugin; -import org.eclipse.jpt.ui.internal.wizards.entity.AnnotatedEntityTemplate; -import org.eclipse.jpt.ui.internal.wizards.entity.EntityTemplate; -import org.eclipse.jpt.ui.internal.wizards.entity.EntityWizardMsg; -import org.eclipse.jpt.ui.internal.wizards.entity.IdClassTemplate; -import org.eclipse.jpt.ui.internal.wizards.entity.data.model.CreateEntityTemplateModel; -import org.eclipse.jst.common.internal.annotations.controller.AnnotationsController; -import org.eclipse.jst.common.internal.annotations.controller.AnnotationsControllerManager; -import org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties; -import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; -import org.eclipse.jst.j2ee.internal.project.WTPJETEmitter; -import org.eclipse.wst.common.componentcore.internal.operation.ArtifactEditProviderOperation; -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; -import org.eclipse.wst.common.frameworks.internal.enablement.nonui.WFTWrappedException; -import org.eclipse.wst.common.frameworks.internal.plugin.WTPCommonPlugin; - -/** - * The NewEntityClassOperation is IDataModelOperation following the - * IDataModel wizard and operation framework. - * - * @see org.eclipse.wst.common.frameworks.datamodel.IDataModelOperation - * @see org.eclipse.wst.common.frameworks.datamodel.IDataModelProvider - * - * This operation is used to generate java classes for the new JPA entity. It uses - * EntityDataModelProvider to store the appropriate properties required to generate the new entity. - * @see org.eclipse.jpt.ui.internal.wizards.entity.data.modelEntityDataModelProvider - * - * A WTPJetEmitter entity template is used to create the class with the entity template. - * @see org.eclipse.jst.j2ee.internal.project.WTPJETEmitter - * @see org.eclipse.jpt.ui.internal.wizards.entity.data.model.CreateEntityTemplateModel - * - * The use of this class is EXPERIMENTAL and is subject to substantial changes. - */ -public class NewEntityClassOperation extends AbstractDataModelOperation { - - private static final String DOT_JAVA = ".java"; //$NON-NLS-1$ - private static final String SEPARATOR = "/";//$NON-NLS-1$ - private static final String VERSION_STRING = "1.0";//$NON-NLS-1$ - private static final String FIELD = "FIELD";//$NON-NLS-1$ - private static final String PROPERTY = "PROPERTY";//$NON-NLS-1$ - protected static final String WTP_CUSTOMIZATION_PLUGIN = "WTP_CUSTOMIZATION_PLUGIN"; //$NON-NLS-1$ - protected static final String ANNOTATED_ENTITY_TEMPLATE_FILE = "/templates/annotated_entity.javajet"; //$NON-NLS-1$ - protected static final String ENTITY_TEMPLATE_FILE = "/templates/entity.javajet"; //$NON-NLS-1$ - protected static final String IDCLASS_TEMPLATE_FILE = "/templates/idClass.javajet"; //$NON-NLS-1$ - protected static final String BUILDER_ID = "builderId"; //$NON-NLS-1$ - private static final String EMPTY_STRING = "";//$NON-NLS-1$ - private static final String SINGLE_TABLE = "SINGLE_TABLE";//$NON-NLS-1$ - - /** - * Method name of template implementation classes. - */ - protected static final String GENERATE_METHOD = "generate"; //$NON-NLS-1$ - - /** - * This is the constructor which should be used when creating a NewEntityClassOperation. - * An instance of the CreateEntityTemplateModel should be passed in. This does not accept - * null parameter. It will not return null. - * - * @see ArtifactEditProviderOperation#ArtifactEditProviderOperation(IDataModel) - * @see CreateEntityTemplateModel - * - * @param dataModel - * @return NewFilterClassOperation - */ - public NewEntityClassOperation(IDataModel dataModel) { - super(dataModel); - } - - /** - * 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 - * the entity (or mapped as superclass) and ID class files will be created using templates. - * - * @see org.eclipse.wst.common.frameworks.internal.operation.WTPOperation#execute(org.eclipse.core.runtime.IProgressMonitor) - * @see NewEntityClassOperation#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 filter class using templates - try { - generateUsingTemplates(monitor, pack); - } catch (Exception e) { - return WTPCommonPlugin.createErrorStatus(e.toString()); - } - return OK_STATUS; - } - - /** - * 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 INewJavaClassDataModelProperties#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(INewJavaClassDataModelProperties.JAVA_PACKAGE); - IPackageFragmentRoot packRoot = (IPackageFragmentRoot) model - .getProperty(INewJavaClassDataModelProperties.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; - } - - /** - * This implementation uses the creation of a CreateEntityTemplateModel and the WTPJETEmitter - * to create the java class with the annotated tags. This method accepts null for monitor, it does not accept null - * for fragment. If annotations are not being used the tags will be omitted from the class. - * - * @see CreateEntityTemplateModel - * @see NewEntityClassOperation#generateTemplateSource(CreateEntityTemplateModel, - * IProgressMonitor) - * - * @param monitor - * @param fragment - * @throws CoreException - * @throws WFTWrappedException - */ - protected void generateUsingTemplates(IProgressMonitor monitor, IPackageFragment fragment) throws WFTWrappedException, CoreException { - // Create the entity template model - CreateEntityTemplateModel tempModel = createTemplateModel(); - IProject project = getTargetProject(); - String entityClassSource = null; - String idClassSource = null; - // Generate the java source based on the entity template models - try { - if (tempModel.isArtifactsAnnotated()) { - AnnotatedEntityTemplate tempImpl = AnnotatedEntityTemplate.create(null); - entityClassSource = generateTemplateSource(tempModel, ANNOTATED_ENTITY_TEMPLATE_FILE, tempImpl, monitor); - } else { - EntityTemplate tempImpl = EntityTemplate.create(null); - entityClassSource = generateTemplateSource(tempModel, ENTITY_TEMPLATE_FILE, tempImpl, monitor); - } - if (tempModel.isCompositePK()) { - IdClassTemplate tempImpl = IdClassTemplate.create(null); - idClassSource = generateTemplateSource(tempModel, IDCLASS_TEMPLATE_FILE, tempImpl, monitor); - } - } catch (Exception e) { - throw new WFTWrappedException(e); - } - if (fragment != null) { - // Create the java file - String javaFileName = tempModel.getClassName() + DOT_JAVA; - ICompilationUnit cu = fragment.getCompilationUnit(javaFileName); - // Add the compilation unit to the java file - if (cu == null || !cu.exists()) { - cu = fragment.createCompilationUnit(javaFileName, entityClassSource, true, monitor); - } - IFile aFile = (IFile) cu.getResource(); - // Let the annotations controller process the annotated resource - if (tempModel.isArtifactsAnnotated()) { - AnnotationsController controller = AnnotationsControllerManager.INSTANCE.getAnnotationsController(project); - if (controller != null) { - controller.process(aFile); - } - } - //Create IdClass if the primary key is complex - if (idClassSource != null) { - String entityPKName = tempModel.getIdClassName() + DOT_JAVA; - ICompilationUnit cu1 = fragment.getCompilationUnit(entityPKName); - // Add the compilation unit to the java file - if (cu1 == null || !cu1.exists()) { - cu1 = fragment.createCompilationUnit(entityPKName, idClassSource, true, monitor); - } - } - } - - if (!tempModel.isArtifactsAnnotated()) { - if (tempModel.isNonEntitySuperclass()) { - addMappedSuperclassToXML(tempModel, project).schedule(); - } else { - addEntityToXML(tempModel, project).schedule(); - } - } - if (!tempModel.isMappingXMLDefault() || !JptCorePlugin.discoverAnnotatedClasses(project)) { - registerMappingXML(tempModel, project).schedule(); - } - } - - /** - * This method is intended for internal use only. This method will create an - * instance of the CreateEntityTemplateModel model to be used in conjunction - * with the WTPJETEmitter. This method will not return null. - * - * @see CreateEntityTemplateModel - * @see NewEntityClassOperation#generateUsingTemplates(IProgressMonitor, - * IPackageFragment) - * - * @return CreateFilterTemplateModel - */ - private CreateEntityTemplateModel createTemplateModel() { - CreateEntityTemplateModel templateModel = new CreateEntityTemplateModel(model); - return templateModel; - } - - /** - * This method is intended for internal use only. This will use the - * WTPJETEmitter to create an annotated java file based on the passed template model. - * This method does not accept null parameters. It will not return null. - * If annotations are not used, it will use the non annotated template to omit the annotated tags. - * - * @see NewEntityClassOperation#generateUsingTemplates(IProgressMonitor, - * IPackageFragment) - * @see JETEmitter#generate(org.eclipse.core.runtime.IProgressMonitor, - * java.lang.Object[]) - * @see CreateEntityTemplateModel - * - * @param templateModel - * @param monitor - * @param template_file - * @return String the source for the java file - * @throws JETException - * @throws NoSuchMethodException - * @throws SecurityException - * @throws InvocationTargetException - * @throws IllegalAccessException - */ - private String generateTemplateSource(CreateEntityTemplateModel templateModel, String templateFile, Object templateImpl, IProgressMonitor monitor) - throws JETException, SecurityException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - Preferences preferences = J2EEPlugin.getDefault().getPluginPreferences(); - boolean dynamicTranslation = preferences.getBoolean(J2EEPlugin.DYNAMIC_TRANSLATION_OF_JET_TEMPLATES_PREF_KEY); - if (dynamicTranslation) { - URL templateURL = FileLocator.find(JptUiPlugin.getPlugin().getBundle(), new Path(templateFile), null); - cleanUpOldEmitterProject(); - WTPJETEmitter emitter = new WTPJETEmitter(templateURL.toString(), this.getClass().getClassLoader()); - emitter.setIntelligentLinkingEnabled(true); - emitter.addVariable(WTP_CUSTOMIZATION_PLUGIN, JptUiPlugin.PLUGIN_ID); - return emitter.generate(monitor, new Object[] { templateModel }); - } else { - Method method = templateImpl.getClass().getMethod(GENERATE_METHOD, new Class[] { Object.class }); - return (String) method.invoke(templateImpl, templateModel); - } - } - - /** - * This method is intended for internal use only. It will clean up the old emmiter project - * in order to prevent generation issues - */ - private 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) { - e.printStackTrace(); - } - } - - /** - * 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 INewJavaClassDataModelProperties#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(INewJavaClassDataModelProperties.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; - } - - @Override - public IStatus execute(IProgressMonitor monitor, IAdaptable info) - throws ExecutionException { - return doExecute(monitor, info); - } - - public IProject getTargetProject() { - String projectName = model.getStringProperty(IArtifactEditOperationDataModelProperties.PROJECT_NAME); - return ProjectUtilities.getProject(projectName); - } - - /** - * Adds entity to ORM XML in separate job - * @param model entity data model - * @param project JPA project in which the entity will be created - * @return - */ - private Job addEntityToXML(final CreateEntityTemplateModel model, final IProject project) { - Job job = new Job(EntityWizardMsg.ADD_ENTITY_TO_XML) { - @Override - protected IStatus run(IProgressMonitor monitor) { - final OrmXmlResourceProvider modelProvider; - if (model.isMappingXMLDefault()) { - modelProvider = OrmXmlResourceProvider.getDefaultXmlResourceProvider(project); - } - else { - modelProvider = OrmXmlResourceProvider.getXmlResourceProvider(project, model.getMappingXMLName()); - } - modelProvider.modify(new Runnable() { - public void run() { - OrmXmlResource resource = modelProvider.getXmlResource(); - - XmlEntityMappings entityMappings = resource.getEntityMappings(); - if (entityMappings == null) { - entityMappings = OrmFactory.eINSTANCE.createXmlEntityMappings(); - entityMappings.setVersion(VERSION_STRING); - } - - XmlEntity xmlEntity = OrmFactory.eINSTANCE.createXmlEntity(); - xmlEntity.setClassName(model.getQualifiedJavaClassName()); - if (model.isInheritanceSet()) { - Inheritance inheritance = OrmFactory.eINSTANCE.createInheritance(); - String inheritanceStrategy = model.getInheritanceStrategyName(); - if (inheritanceStrategy.equals(EMPTY_STRING)) { - inheritanceStrategy = SINGLE_TABLE; - } - InheritanceType inheritanceType = OrmFactory.eINSTANCE.createInheritanceTypeFromString(null, inheritanceStrategy);// TODO - inheritance.setStrategy(inheritanceType); - xmlEntity.setInheritance(inheritance); - } - - if (model.isEntityNameSet()) { - xmlEntity.setName(model.getEntityName()); - } - if (model.isTableNameSet()) { - XmlTable xmlTable = OrmFactory.eINSTANCE.createXmlTable(); - xmlTable.setName(model.getTableName()); - xmlEntity.setTable(xmlTable); - } - if (model.isCompositePK()) { - XmlIdClass idClass = OrmFactory.eINSTANCE.createXmlIdClass(); - idClass.setClassName(model.getIdClassName()); - xmlEntity.setIdClass(idClass); - } - List<String> pkFields = model.getPKFields(); - if (pkFields.size() > 0) { - Attributes entityAttributes = OrmFactory.eINSTANCE.createAttributes(); - List<XmlIdImpl> ids = new ArrayList<XmlIdImpl>(); - for (String fieldName : pkFields) { - XmlIdImpl idImpl = OrmFactory.eINSTANCE.createXmlIdImpl(); - idImpl.setName(fieldName); - ids.add(idImpl); - } - entityAttributes.eSet(OrmPackage.ATTRIBUTES__IDS, ids); - xmlEntity.setAttributes(entityAttributes); - } - - String accessTypeString = FIELD; - if (!model.isFieldAccess()) { - accessTypeString = PROPERTY; - } - AccessType accessType = OrmFactory.eINSTANCE.createAccessTypeFromString(null, accessTypeString);// TODO - xmlEntity.setAccess(accessType); - EList<XmlEntity> entities = entityMappings.getEntities(); - entities.add(xmlEntity); - resource.getContents().add(entityMappings); - } - }); - return Status.OK_STATUS; - } - }; - return job; - } - - /** - * Adds mapped superclass to ORM XML in separate job - * - * @param model entity data model - * @param project JPA project in which the entity will be created - * @return the created job - */ - private Job addMappedSuperclassToXML(final CreateEntityTemplateModel model, final IProject project) { - Job job = new Job(EntityWizardMsg.ADD_MAPPED_SUPERCLASS_TO_XML) { - @Override - protected IStatus run(IProgressMonitor monitor) { - final OrmXmlResourceProvider modelProvider; - if (model.isMappingXMLDefault()) { - modelProvider = OrmXmlResourceProvider.getDefaultXmlResourceProvider(project); - } - else { - modelProvider = OrmXmlResourceProvider.getXmlResourceProvider(project, model.getMappingXMLName()); - } - modelProvider.modify(new Runnable() { - public void run() { - OrmXmlResource resource = modelProvider.getXmlResource(); - XmlEntityMappings entityMappings = resource.getEntityMappings(); - if (entityMappings == null) { - entityMappings = OrmFactory.eINSTANCE.createXmlEntityMappings(); - entityMappings.setVersion(VERSION_STRING); - } - - XmlMappedSuperclass xmlMappedSuperclass = OrmFactory.eINSTANCE.createXmlMappedSuperclass(); - xmlMappedSuperclass.setClassName(model.getQualifiedJavaClassName()); - - if (model.isCompositePK()) { - XmlIdClass idClass = OrmFactory.eINSTANCE.createXmlIdClass(); - idClass.setClassName(model.getIdClassName()); - xmlMappedSuperclass.setIdClass(idClass); - } - - List<String> pkFields = model.getPKFields(); - if (pkFields.size() > 0) { - Attributes entityAttributes = OrmFactory.eINSTANCE.createAttributes(); - List<XmlIdImpl> ids = new ArrayList<XmlIdImpl>(); - for (String fieldName : pkFields) { - XmlIdImpl idImpl = OrmFactory.eINSTANCE.createXmlIdImpl(); - idImpl.setName(fieldName); - ids.add(idImpl); - } - entityAttributes.eSet(OrmPackage.ATTRIBUTES__IDS, ids); - xmlMappedSuperclass.setAttributes(entityAttributes); - } - - String accessTypeString = FIELD; - if (!model.isFieldAccess()) { - accessTypeString = PROPERTY; - } - AccessType accessType = OrmFactory.eINSTANCE.createAccessTypeFromString(null, accessTypeString); - xmlMappedSuperclass.setAccess(accessType); - entityMappings.getMappedSuperclasses().add(xmlMappedSuperclass); - - resource.getContents().add(entityMappings); - } - }); - return Status.OK_STATUS; - } - }; - return job; - } - - /** - * Register alternative mapping XML and/or classes in the persistence.xml - * - * @param model entity data model - * @param project JPA project in which the entity will be created - * @return the created job - */ - private Job registerMappingXML(final CreateEntityTemplateModel model, final IProject project) { - Job job = new Job(EntityWizardMsg.APPLY_CHANGES_TO_PERSISTENCE_XML) { - @Override - protected IStatus run(IProgressMonitor monitor) { - final PersistenceXmlResourceProvider pmp = - PersistenceXmlResourceProvider.getDefaultXmlResourceProvider(project); - pmp.modify(new Runnable() { - public void run() { - String fileName = getLastSegment(model.getMappingXMLName()); - PersistenceXmlResource persistenceResource = pmp.getXmlResource(); - XmlPersistence xmlPersistence = persistenceResource.getPersistence(); - EList<XmlPersistenceUnit> persistenceUnits = xmlPersistence.getPersistenceUnits(); - XmlPersistenceUnit persistenceUnit = persistenceUnits.get(0);// Multiply persistence unit support - if (!model.isMappingXMLDefault()) { - boolean newXmlMappingFile = true; - EList<XmlMappingFileRef> xmlMappingFiles = persistenceUnit.getMappingFiles(); - for (XmlMappingFileRef fileRef : xmlMappingFiles) { - if (fileName.equals(fileRef.getFileName())) { - newXmlMappingFile = false; - break; - } - } - if (newXmlMappingFile) { - XmlMappingFileRef xmlMappingFileRef = PersistenceFactory.eINSTANCE.createXmlMappingFileRef(); - xmlMappingFileRef.setFileName(fileName); - persistenceUnit.getMappingFiles().add(xmlMappingFileRef); - } - } - if (!model.isNonEntitySuperclass() && !JptCorePlugin.discoverAnnotatedClasses(project)) { - XmlJavaClassRef classRef = PersistenceFactory.eINSTANCE.createXmlJavaClassRef(); - classRef.setJavaClass(model.getQualifiedJavaClassName()); - persistenceUnit.getClasses().add(classRef); - } - persistenceResource.getContents().add(xmlPersistence); - } - }); - - return Status.OK_STATUS; - } - }; - return job; - - } - - /** - * @param input the name of mapping XML from the class wizard page. It is relative path from the source folder - * and includes META-INF folder - * @return the simple name of the mapping XML - */ - private String getLastSegment(String input) { - String output = input; - if (input.indexOf(SEPARATOR) != -1) { - output = input.substring(input.lastIndexOf(SEPARATOR) + 1); - } - return output; - } - -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/orm/MappingFileWizard.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/orm/MappingFileWizard.java deleted file mode 100644 index 344f3a64e1..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/orm/MappingFileWizard.java +++ /dev/null @@ -1,270 +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: - * Oracle - initial API and implementation - *******************************************************************************/ -package org.eclipse.jpt.ui.internal.wizards.orm; - -import java.lang.reflect.InvocationTargetException; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IFolder; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.Path; -import org.eclipse.jdt.core.IJavaElement; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.IPackageFragment; -import org.eclipse.jdt.core.IPackageFragmentRoot; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jem.util.emf.workbench.ProjectUtilities; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jpt.core.JptCorePlugin; -import org.eclipse.jpt.core.context.JpaContextNode; -import org.eclipse.jpt.core.context.persistence.PersistenceUnit; -import org.eclipse.jpt.core.internal.operations.OrmFileCreationDataModelProperties; -import org.eclipse.jpt.core.internal.operations.OrmFileCreationDataModelProvider; -import org.eclipse.jpt.ui.JptUiPlugin; -import org.eclipse.jpt.ui.internal.JptUiIcons; -import org.eclipse.jpt.ui.internal.JptUiMessages; -import org.eclipse.ui.INewWizard; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.ide.IDE; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; -import org.eclipse.wst.common.frameworks.datamodel.IDataModelProvider; -import org.eclipse.wst.common.frameworks.internal.datamodel.ui.DataModelWizard; - -public class MappingFileWizard extends DataModelWizard - implements INewWizard -{ - private MappingFileWizardPage page; - - - public MappingFileWizard() { - this(null); - } - - public MappingFileWizard(IDataModel dataModel) { - super(dataModel); - setWindowTitle(JptUiMessages.MappingFileWizard_title); - setDefaultPageImageDescriptor(JptUiPlugin.getImageDescriptor(JptUiIcons.JPA_FILE_WIZ_BANNER)); - } - - - @Override - protected void doAddPages() { - super.doAddPages(); - page = buildMappingFileWizardPage(); - addPage(page); - } - - protected MappingFileWizardPage buildMappingFileWizardPage() { - return new MappingFileWizardPage(getDataModel(), "Page_1"); - } - - @Override - protected IDataModelProvider getDefaultProvider() { - return new OrmFileCreationDataModelProvider(); - } - - public void init(IWorkbench workbench, IStructuredSelection selection) { - // check for project, source folder, persistence unit? - if (selection == null || selection.isEmpty()) { - return; - } - - Object firstSelection = selection.getFirstElement(); - - PersistenceUnit pUnit = extractPersistenceUnit(firstSelection); - IFolder sourceFolder = extractSourceFolder(pUnit, firstSelection); - IProject project = extractProject(pUnit, sourceFolder, firstSelection); - - if (project != null) { - getDataModel().setStringProperty(OrmFileCreationDataModelProperties.PROJECT_NAME, project.getName()); - } - if (sourceFolder != null) { - getDataModel().setStringProperty(OrmFileCreationDataModelProperties.SOURCE_FOLDER, sourceFolder.getFullPath().toPortableString()); - } - if (pUnit != null) { - getDataModel().setBooleanProperty(OrmFileCreationDataModelProperties.ADD_TO_PERSISTENCE_UNIT, true); - getDataModel().setStringProperty(OrmFileCreationDataModelProperties.PERSISTENCE_UNIT, pUnit.getName()); - } - } - - private PersistenceUnit extractPersistenceUnit(Object selection) { - if (selection instanceof PersistenceUnit) { - return (PersistenceUnit) selection; - } - PersistenceUnit pUnit = null; - if (selection instanceof JpaContextNode) { - try { - pUnit = ((JpaContextNode) selection).getPersistenceUnit(); - } - catch (Exception e) { /* do nothing, just continue */ } - } - if (pUnit == null && selection instanceof IAdaptable) { - pUnit = (PersistenceUnit) ((IAdaptable) selection).getAdapter(PersistenceUnit.class); - - } - return pUnit; - } - - private IFolder extractSourceFolder(PersistenceUnit pUnit, Object selection) { - IJavaProject javaProject = null; - IFolder srcFolder = null; - if (pUnit != null) { - javaProject = pUnit.getJpaProject().getJavaProject(); - srcFolder = findSourceFolder(javaProject, pUnit.getResource()); - if (srcFolder != null) { - return srcFolder; - } - - } - if (selection instanceof IResource) { - javaProject = JavaCore.create(((IResource) selection).getProject()); - if (javaProject.exists()) { - srcFolder = findSourceFolder(javaProject, (IResource) selection); - if (srcFolder != null) { - return srcFolder; - } - } - } - - if (selection instanceof IAdaptable) { - IResource resource = (IResource) ((IAdaptable) selection).getAdapter(IResource.class); - if (resource != null) { - javaProject = JavaCore.create((resource).getProject()); - if (javaProject.exists()) { - srcFolder = findSourceFolder(javaProject, resource); - if (srcFolder != null) { - return srcFolder; - } - } - } - } - return null; - } - - private IFolder findSourceFolder(IJavaProject javaProject, IResource resource) { - if (JptCorePlugin.getJpaProject(javaProject.getProject()) == null) { - // not even a jpa project - return null; - } - while (resource != null && ! (resource instanceof IFolder)) { - resource = resource.getParent(); - } - if (resource == null) { - return null; - } - IFolder folder = (IFolder) resource; - try { - IPackageFragmentRoot packageFragmentRoot = null; - while (packageFragmentRoot == null && folder != null) { - packageFragmentRoot = javaProject.findPackageFragmentRoot(folder.getFullPath()); - if (packageFragmentRoot == null) { - IPackageFragment packageFragment = javaProject.findPackageFragment(folder.getFullPath()); - if (packageFragment != null) { - packageFragmentRoot = (IPackageFragmentRoot) packageFragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); - } - } - if (packageFragmentRoot == null) { - try { - folder = (IFolder) folder.getParent(); - } - catch (ClassCastException cce) { - folder = null; - } - } - } - if (packageFragmentRoot == null) { - return null; - } - if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) { - return (IFolder) packageFragmentRoot.getResource(); - } - } - catch (JavaModelException jme) { /* do nothing, return null */ } - return null; - } - - private IProject extractProject(PersistenceUnit pUnit, IFolder sourceFolder, Object selection) { - if (pUnit != null) { - return pUnit.getJpaProject().getProject(); - } - if (sourceFolder != null) { - return sourceFolder.getProject(); - } - - IProject project = null; - if (selection instanceof IResource) { - project = ((IResource) selection).getProject(); - } - if (project == null && selection instanceof IJavaElement) { - project = ((IJavaElement) selection).getJavaProject().getProject(); - } - if (project == null && selection instanceof JpaContextNode) { - project = ((JpaContextNode) selection).getJpaProject().getProject(); - } - if (project == null && selection instanceof IAdaptable) { - project = (IProject) ((IAdaptable) selection).getAdapter(IProject.class); - if (project == null) { - IResource resource = (IResource) ((IAdaptable) selection).getAdapter(IResource.class); - if (resource != null) { - project = resource.getProject(); - } - } - if (project == null) { - IJavaElement javaElement = (IJavaElement) ((IAdaptable) selection).getAdapter(IJavaElement.class); - if (javaElement != null) { - project = javaElement.getJavaProject().getProject(); - } - } - } - - if (project != null && JptCorePlugin.getJpaProject(project) != null) { - return project; - } - - return null; - } - - protected void postPerformFinish() throws InvocationTargetException { - try { - String projectName = (String) getDataModel().getProperty(OrmFileCreationDataModelProperties.PROJECT_NAME); - IProject project = ProjectUtilities.getProject(projectName); - String sourceFolder = getDataModel().getStringProperty(OrmFileCreationDataModelProperties.SOURCE_FOLDER); - String filePath = getDataModel().getStringProperty(OrmFileCreationDataModelProperties.FILE_PATH); - - IFile file = project.getWorkspace().getRoot().getFile(new Path(sourceFolder).append(filePath)); - openEditor(file); - } - catch (Exception cantOpen) { - throw new InvocationTargetException(cantOpen); - } - } - - private void openEditor(final IFile file) { - if (file != null) { - getShell().getDisplay().asyncExec(new Runnable() { - public void run() { - try { - IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); - IDE.openEditor(page, file, true); - } - catch (PartInitException e) { - JptUiPlugin.log(e); - } - } - }); - } - } -} diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/orm/MappingFileWizardPage.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/orm/MappingFileWizardPage.java deleted file mode 100644 index f75259c241..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/orm/MappingFileWizardPage.java +++ /dev/null @@ -1,272 +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: - * Oracle - initial API and implementation - *******************************************************************************/ -package org.eclipse.jpt.ui.internal.wizards.orm; - -import org.eclipse.core.resources.IContainer; -import org.eclipse.core.resources.IFolder; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.jdt.core.IPackageFragmentRoot; -import org.eclipse.jem.util.emf.workbench.ProjectUtilities; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.viewers.DecoratingLabelProvider; -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerFilter; -import org.eclipse.jface.window.Window; -import org.eclipse.jpt.core.internal.operations.OrmFileCreationDataModelProperties; -import org.eclipse.jpt.ui.JptUiPlugin; -import org.eclipse.jpt.ui.internal.JptUiMessages; -import org.eclipse.jst.j2ee.internal.project.J2EEProjectUtilities; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; -import org.eclipse.ui.dialogs.ISelectionStatusValidator; -import org.eclipse.ui.model.WorkbenchContentProvider; -import org.eclipse.ui.model.WorkbenchLabelProvider; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; -import org.eclipse.wst.common.frameworks.internal.datamodel.ui.DataModelWizardPage; - -public class MappingFileWizardPage extends DataModelWizardPage - implements OrmFileCreationDataModelProperties -{ - private Label projectNameLabel; - - private Combo projectNameCombo; - - private Label sourceFolderLabel; - - private Text sourceFolderText; - - private Label filePathLabel; - - private Text filePathText; - - private Label accessLabel; - - private Combo accessCombo; - - private Button addToPersistenceUnitButton; - - private Label persistenceUnitLabel; - - private Combo persistenceUnitCombo; - - - public MappingFileWizardPage(IDataModel dataModel, String pageName) { - super(dataModel, pageName); - setTitle(JptUiMessages.MappingFileWizardPage_title); - setDescription(JptUiMessages.MappingFileWizardPage_desc); - setPageComplete(false); - } - - - @Override - protected String[] getValidationPropertyNames() { - return new String[] { - PROJECT_NAME, - SOURCE_FOLDER, - FILE_PATH, - DEFAULT_ACCESS, - ADD_TO_PERSISTENCE_UNIT, - PERSISTENCE_UNIT - }; - } - - @Override - protected Composite createTopLevelComposite(Composite parent) { - Composite composite = new Composite(parent, SWT.NULL); - GridLayout layout = new GridLayout(); - layout.numColumns = 3; - composite.setLayout(layout); - GridData data = new GridData(); - data.verticalAlignment = GridData.FILL; - data.horizontalAlignment = GridData.FILL; - data.widthHint = 300; - composite.setLayoutData(data); - - this.projectNameLabel = new Label(composite, SWT.NONE); - this.projectNameLabel.setText(JptUiMessages.MappingFileWizardPage_projectLabel); - data = new GridData(); - this.projectNameLabel.setLayoutData(data); - - this.projectNameCombo = new Combo(composite, SWT.BORDER | SWT.READ_ONLY); - data = new GridData(GridData.FILL_HORIZONTAL); - data.widthHint = 300; - data.horizontalSpan = 1; - this.projectNameCombo.setLayoutData(data); - this.synchHelper.synchCombo(this.projectNameCombo, PROJECT_NAME, null); - new Label(composite, SWT.NONE); - - this.sourceFolderLabel = new Label(composite, SWT.NONE); - this.sourceFolderLabel.setText(JptUiMessages.MappingFileWizardPage_sourceFolderLabel); - data = new GridData(); - this.sourceFolderLabel.setLayoutData(data); - - this.sourceFolderText = new Text(composite, SWT.BORDER); - data = new GridData(GridData.FILL_HORIZONTAL); - data.widthHint = 300; - data.horizontalSpan = 1; - this.sourceFolderText.setLayoutData(data); - this.synchHelper.synchText(this.sourceFolderText, SOURCE_FOLDER, null); - - Button sourceFolderButton = new Button(composite, SWT.PUSH); - sourceFolderButton.setText(JptUiMessages.General_browse); - data = new GridData(GridData.FILL_HORIZONTAL); - data.horizontalSpan = 1; - sourceFolderButton.addSelectionListener( - new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - widgetSelected(e); - } - - public void widgetSelected(SelectionEvent e) { - handleSourceFolderButtonPressed(); - } - }); - - this.filePathLabel = new Label(composite, SWT.NONE); - this.filePathLabel.setText(JptUiMessages.MappingFileWizardPage_filePathLabel); - data = new GridData(); - this.filePathLabel.setLayoutData(data); - - this.filePathText = new Text(composite, SWT.BORDER); - data = new GridData(GridData.FILL_HORIZONTAL); - data.widthHint = 300; - data.horizontalSpan = 1; - this.filePathText.setLayoutData(data); - this.synchHelper.synchText(this.filePathText, FILE_PATH, null); - new Label(composite, SWT.NONE); - - this.accessLabel = new Label(composite, SWT.NONE); - this.accessLabel.setText(JptUiMessages.MappingFileWizardPage_accessLabel); - data = new GridData(); - this.accessLabel.setLayoutData(data); - - this.accessCombo = new Combo(composite, SWT.BORDER | SWT.READ_ONLY); - data = new GridData(GridData.FILL_HORIZONTAL); - data.widthHint = 300; - data.horizontalSpan = 1; - this.accessCombo.setLayoutData(data); - this.synchHelper.synchCombo(this.accessCombo, DEFAULT_ACCESS, null); - new Label(composite, SWT.NONE); - - this.addToPersistenceUnitButton = new Button(composite, SWT.CHECK | SWT.BEGINNING); - this.addToPersistenceUnitButton.setText(JptUiMessages.MappingFileWizardPage_addToPersistenceUnitButton); - data = new GridData(GridData.FILL_HORIZONTAL); - data.horizontalSpan = 3; - this.addToPersistenceUnitButton.setLayoutData(data); - this.synchHelper.synchCheckbox(this.addToPersistenceUnitButton, ADD_TO_PERSISTENCE_UNIT, null); - - this.persistenceUnitLabel = new Label(composite, SWT.NONE); - this.persistenceUnitLabel.setText(JptUiMessages.MappingFileWizardPage_persistenceUnitLabel); - data = new GridData(); - this.persistenceUnitLabel.setLayoutData(data); - - this.persistenceUnitCombo = new Combo(composite, SWT.BORDER | SWT.READ_ONLY); - data = new GridData(GridData.FILL_HORIZONTAL); - data.widthHint = 300; - data.horizontalSpan = 1; - this.persistenceUnitCombo.setLayoutData(data); - this.synchHelper.synchCombo(this.persistenceUnitCombo, PERSISTENCE_UNIT, null); - - new Label(composite, SWT.NONE); - -// classText.setFocus(); - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, getInfopopID()); - Dialog.applyDialogFont(parent); - return composite; - } - - private void handleSourceFolderButtonPressed() { - ISelectionStatusValidator validator = getSourceFolderDialogSelectionValidator(); - ViewerFilter filter = getSourceFolderDialogViewerFilter(); - ITreeContentProvider contentProvider = new WorkbenchContentProvider(); - ILabelProvider labelProvider = new DecoratingLabelProvider( - new WorkbenchLabelProvider(), - PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator()); - ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), labelProvider, contentProvider); - dialog.setValidator(validator); - dialog.setTitle(JptUiMessages.MappingFileWizardPage_accessLabel_sourceFolderDialogTitle); - dialog.setMessage(JptUiMessages.MappingFileWizardPage_accessLabel_sourceFolderDialogDesc); - dialog.addFilter(filter); - String projectName = model.getStringProperty(PROJECT_NAME); - if (projectName==null || projectName.length()==0) { - return; - } - IProject project = ProjectUtilities.getProject(projectName); - dialog.setInput(ResourcesPlugin.getWorkspace().getRoot()); - - if (project != null) { - dialog.setInitialSelection(project); - } - if (dialog.open() == Window.OK) { - Object element = dialog.getFirstResult(); - if (element instanceof IContainer) { - IContainer container = (IContainer) element; - model.setProperty(SOURCE_FOLDER, container.getFullPath().toPortableString()); - } - } - } - - private ISelectionStatusValidator getSourceFolderDialogSelectionValidator() { - return new ISelectionStatusValidator() { - public IStatus validate(Object[] selection) { - if (selection != null && selection[0] != null && ! (selection[0] instanceof IProject)) { - return Status.OK_STATUS; - } - return new Status(IStatus.ERROR, JptUiPlugin.PLUGIN_ID, JptUiMessages.MappingFileWizardPage_incorrectSourceFolderError); - } - }; - } - - private ViewerFilter getSourceFolderDialogViewerFilter() { - return new ViewerFilter() { - @Override - public boolean select(Viewer viewer, Object parent, Object element) { - if (element instanceof IProject) { - IProject project = (IProject) element; - return project.getName().equals(model.getProperty(PROJECT_NAME)); - } - else if (element instanceof IFolder) { - IFolder folder = (IFolder) element; - // only show source folders - IProject project = ProjectUtilities.getProject(model.getStringProperty(PROJECT_NAME)); - IPackageFragmentRoot[] sourceFolders = J2EEProjectUtilities.getSourceContainers(project); - for (int i = 0; i < sourceFolders.length; i++) { - if (sourceFolders[i].getResource()!= null && sourceFolders[i].getResource().equals(folder)) { - return true; - } - } - } - return false; - } - }; - } - - void init(IWorkbench workbench, IStructuredSelection selection) { - - } -} |