diff options
Diffstat (limited to 'jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards')
18 files changed, 0 insertions, 5164 deletions
diff --git a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/DatabaseReconnectWizardPage.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/DatabaseReconnectWizardPage.java deleted file mode 100644 index 1c04312695..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/DatabaseReconnectWizardPage.java +++ /dev/null @@ -1,353 +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.Iterator; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogConstants; -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.JptDbPlugin; -import org.eclipse.jpt.db.Schema; -import org.eclipse.jpt.db.Table; -import org.eclipse.jpt.db.ui.internal.DTPUiTools; -import org.eclipse.jpt.ui.internal.JpaHelpContextIds; -import org.eclipse.jpt.ui.internal.JptUiMessages; -import org.eclipse.jpt.utility.internal.CollectionTools; -import org.eclipse.jpt.utility.internal.StringTools; -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.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Link; -import org.eclipse.ui.PlatformUI; - -public class DatabaseReconnectWizardPage extends WizardPage -{ - private JpaProject jpaProject; - - private ConnectionProfile profile; - - private ConnectionListener connectionListener; - - private DatabaseGroup databaseGroup; - - public DatabaseReconnectWizardPage(JpaProject jpaProject) { - super("Database Settings"); //$NON-NLS-1$ - this.jpaProject = jpaProject; - setTitle(JptUiMessages.DatabaseReconnectWizardPage_databaseConnection); - setMessage(JptUiMessages.DatabaseReconnectWizardPage_reconnectToDatabase); - } - - public void createControl(Composite parent) { - this.setPageComplete(false); - Composite top = this.createTopLevelComposite(parent); - this.setControl(top); - } - - protected Composite createTopLevelComposite(Composite parent) { - Composite composite = new Composite(parent, SWT.NULL); - GridLayout layout = new GridLayout(); - composite.setLayout(layout); - this.databaseGroup = new DatabaseGroup(composite); - Dialog.applyDialogFont(parent); - // TODO Add Help - testing - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, JpaHelpContextIds.PROPERTIES_JAVA_PERSISTENCE_CONNECTION); - return composite; - } - - private Label createLabel(Composite container, int span, String text) { - Label label = new Label(container, SWT.NONE); - label.setText(text); - GridData gd = new GridData(); - gd.horizontalIndent = 30; - gd.horizontalSpan = span; - label.setLayoutData(gd); - return label; - } - - private Combo createCombo(Composite container, boolean fillHorizontal) { - Combo combo = new Combo(container, SWT.BORDER | SWT.SINGLE); - if (fillHorizontal) { - combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - } - else { - combo.setLayoutData(new GridData()); - } - return combo; - } - - /** - * Initialize a grid layout with the default Dialog settings. - */ - protected GridLayout initGridLayout(GridLayout layout, boolean margins) { - layout.horizontalSpacing = this.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - layout.verticalSpacing = this.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - if (margins) { - layout.marginWidth = this.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.marginHeight = this.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - } - else { - layout.marginWidth = 0; - layout.marginHeight = 0; - } - return layout; - } - - public Collection<Table> getTables() { - Schema schema = this.getDefaultSchema(); - if (schema != null && schema.getName() != null) { - return CollectionTools.collection(schema.tables()); - } - return Collections.<Table> emptyList(); - } - - private void updateGenerateEntitiesPage(Schema schema) { - if (this.getWizard() instanceof GenerateEntitiesWizard) { - GenerateEntitiesWizard generateEntitiesWizard = ((GenerateEntitiesWizard) this.getWizard()); - generateEntitiesWizard.updatePossibleTables(CollectionTools.collection(schema.tables())); - } - } - - @Override - public void dispose() { - this.removeConnectionListener(); - super.dispose(); - } - - private void removeConnectionListener() { - if (this.connectionListener != null) { - if (this.profile != null) { - this.profile.removeConnectionListener(this.connectionListener); - } - this.connectionListener = null; - } - } - - ConnectionProfile getProjectConnectionProfile() { - String profileName = this.jpaProject.getDataSource().getConnectionProfileName(); - return this.connectionProfileNamed(profileName); - } - - ConnectionProfile connectionProfileNamed(String profileName) { - return JptDbPlugin.instance().getConnectionProfileRepository().connectionProfileNamed(profileName); - } - - Schema getDefaultSchema() { - return this.jpaProject.getDefaultSchema(); - } - - public String getSelectedConnectionProfileName() { - return this.databaseGroup.getConnectionProfileName(); - } - - public void clearConnectionProfileName() { - this.databaseGroup.clearConnectionProfileName(); - } - // ********** member classes ********** - private final class DatabaseGroup - { - private final Group group; - - private final Combo connectionCombo; - - private final Combo schemaCombo; - - private Link addConnectionLink; - - private Link reconnectLink; - - public DatabaseGroup(Composite composite) { - this.group = new Group(composite, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - this.group.setLayout(layout); - this.group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - this.group.setText(JptUiMessages.DatabaseReconnectWizardPage_database); - // TODO Add Help - // PlatformUI.getWorkbench().getHelpSystem().setHelp( this.group, - // IDaliHelpContextIds.XXX); - createLabel(this.group, 1, JptUiMessages.DatabaseReconnectWizardPage_connection); - this.connectionCombo = createCombo(this.group, true); - this.connectionCombo.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetDefaultSelected(SelectionEvent e) { - widgetSelected(e); - } - - @Override - public void widgetSelected(SelectionEvent e) { - handleConnectionChange(); - } - }); - createLabel(this.group, 1, JptUiMessages.DatabaseReconnectWizardPage_schema); - this.schemaCombo = createCombo(this.group, true); - this.schemaCombo.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetDefaultSelected(SelectionEvent e) { - widgetSelected(e); - } - - @Override - public void widgetSelected(SelectionEvent e) { - handleSchemaChange(); - } - }); - createLabel(this.group, 2, JptUiMessages.DatabaseReconnectWizardPage_schemaInfo); - this.addConnectionLink = new Link(this.group, SWT.NONE); - GridData data = new GridData(GridData.END, GridData.CENTER, false, false); - data.horizontalSpan = 2; - this.addConnectionLink.setLayoutData(data); - this.addConnectionLink.setText(JptUiMessages.DatabaseReconnectWizardPage_addConnectionLink); - this.addConnectionLink.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - openNewConnectionWizard(); - } - }); - this.reconnectLink = new Link(this.group, SWT.NONE); - data = new GridData(GridData.END, GridData.CENTER, false, false); - data.horizontalSpan = 2; - this.reconnectLink.setLayoutData(data); - this.reconnectLink.setText(JptUiMessages.DatabaseReconnectWizardPage_reconnectLink); - this.reconnectLink.setEnabled(false); - this.reconnectLink.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - openConnectionProfileNamed(getConnectionProfileName()); - } - }); - this.populateConnectionCombo(); - this.populateSchemaCombo(); - } - - private ConnectionProfile connectionProfileNamed(String profileName) { - return DatabaseReconnectWizardPage.this.connectionProfileNamed(profileName); - } - - private Iterator<String> dtpConnectionProfileNames() { - return JptDbPlugin.instance().getConnectionProfileRepository().connectionProfileNames(); - } - - private String getProjectConnectionProfileName() { - return jpaProject.getDataSource().getConnectionProfileName(); - } - - private void openConnectionProfileNamed(String connectionProfileName) { - DatabaseReconnectWizardPage.this.removeConnectionListener(); - DatabaseReconnectWizardPage.this.profile = this.connectionProfileNamed(connectionProfileName); - DatabaseReconnectWizardPage.this.profile.connect(); - if (DatabaseReconnectWizardPage.this.profile.isActive()) { - this.populateSchemaCombo(); - DatabaseReconnectWizardPage.this.connectionListener = this.buildConnectionListener(); - DatabaseReconnectWizardPage.this.profile.addConnectionListener(DatabaseReconnectWizardPage.this.connectionListener); - } - return; - } - - private void populateConnectionCombo() { - // clear out connection entries from previous login. - this.connectionCombo.removeAll(); - for (Iterator<String> i = CollectionTools.sort(this.dtpConnectionProfileNames()); i.hasNext();) { - this.connectionCombo.add(i.next()); - } - String connectionName = getProjectConnectionProfileName(); - if (!StringTools.stringIsEmpty(connectionName)) { - this.connectionCombo.select(connectionCombo.indexOf(connectionName)); - this.reconnectLink.setEnabled(true); - } - } - - private void handleConnectionChange() { - this.reconnectLink.setEnabled(true); - this.populateSchemaCombo(); - } - - private void handleSchemaChange() { - ConnectionProfile connectionProfile = this.connectionProfileNamed(getConnectionProfileName()); - Schema schema = connectionProfile.getDatabase().schemaNamed(this.getSchemaName()); - DatabaseReconnectWizardPage.this.updateGenerateEntitiesPage(schema); - DatabaseReconnectWizardPage.this.setPageComplete(true); - } - - private void populateSchemaCombo() { - // clear out schema entries from previous connection selection - this.schemaCombo.removeAll(); - ConnectionProfile connectionProfile = this.connectionProfileNamed(getConnectionProfileName()); - for (Iterator<String> stream = CollectionTools.sort(connectionProfile.getDatabase().schemaNames()); stream.hasNext();) { - this.schemaCombo.add(stream.next()); - } - // get default schema name from the project - Schema schema = getDefaultSchema(); - if (schema != null && schema.getName() != null) { - schema = connectionProfile.getDatabase().schemaNamed(schema.getName()); // verify - // schema - // exist - if (schema != null) { - this.schemaCombo.select(this.schemaCombo.indexOf(schema.getName())); - DatabaseReconnectWizardPage.this.updateGenerateEntitiesPage(schema); - DatabaseReconnectWizardPage.this.setPageComplete(true); - } - } - } - - private String getConnectionProfileName() { - return this.connectionCombo.getText(); - } - - private String getSchemaName() { - return this.schemaCombo.getText(); - } - - void clearConnectionProfileName() { - this.connectionCombo.setText(""); - } - - private void openNewConnectionWizard() { - String addedProfileName = DTPUiTools.createNewProfile(); - ConnectionProfile addedProfile = this.connectionProfileNamed(addedProfileName); - if (!addedProfile.isNull()) { - addedProfile.connect(); - this.populateConnectionCombo(); - this.connectionCombo.select(connectionCombo.indexOf(addedProfile.getName())); - this.handleConnectionChange(); - } - } - - private ConnectionListener buildConnectionListener() { - return new ConnectionAdapter() { - @Override - public void opened(ConnectionProfile profile) { - if (DatabaseReconnectWizardPage.this.profile.equals(profile)) { - DatabaseGroup.this.populateSchemaCombo(); - } - } - - @Override - public void aboutToClose(ConnectionProfile profile) { - if (DatabaseReconnectWizardPage.this.profile.equals(profile)) { - DatabaseReconnectWizardPage.this.removeConnectionListener(); - } - } - }; - } - } -} 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 4b663e604a..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/GenerateEntitiesWizard.java +++ /dev/null @@ -1,165 +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 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.JpaProject; -import org.eclipse.jpt.db.ConnectionProfile; -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; - -public class GenerateEntitiesWizard extends Wizard { - - private JpaProject jpaProject; - - private IStructuredSelection selection; - - /** this page is only built when the project is not connected to the db */ - private DatabaseReconnectWizardPage dbSettingsPage; - - private GenerateEntitiesWizardPage generateEntitiesPage; - - private PackageGenerator.Config packageGeneratorConfig; - - private EntityGenerator.Config entityGeneratorConfig; - - private boolean synchronizePersistenceXml; - - private Collection<Table> selectedTables; - - 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.dbSettingsPage = new DatabaseReconnectWizardPage( this.jpaProject); - this.addPage(this.dbSettingsPage); - this.generateEntitiesPage = new GenerateEntitiesWizardPage(); - this.addPage( this.generateEntitiesPage); - this.generateEntitiesPage.init( this.selection); - } - - @Override - public boolean performFinish() { - this.packageGeneratorConfig.setPackageFragment( this.buildPackageFragment()); - - this.entityGeneratorConfig.setConvertToCamelCase( this.generateEntitiesPage.convertToCamelCase()); - this.entityGeneratorConfig.setFieldAccessType( this.generateEntitiesPage.fieldAccessType()); - this.entityGeneratorConfig.setCollectionTypeName( this.generateEntitiesPage.getCollectionTypeName()); - 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.setOverrideEntityNames( this.generateEntitiesPage.getOverrideEntityNames()); - - this.synchronizePersistenceXml = this.generateEntitiesPage.synchronizePersistenceXml(); - - this.selectedTables = this.generateEntitiesPage.getSelectedTables(); - return true; - } - - 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); - } - } - - Collection<Table> getPossibleTables() { - if ( this.dbSettingsPage != null) { - return this.dbSettingsPage.getTables(); - } - return ( this.projectDefaultSchemaExists()) ? CollectionTools.collection( this.getDefaultSchema().tables()) : Collections.<Table>emptyList(); - } - - ConnectionProfile getProjectConnectionProfile() { - return this.jpaProject.getConnectionProfile(); - } - - JpaProject getJpaProject(){ - return this.jpaProject; - } - - Schema getDefaultSchema() { - return getJpaProject().getDefaultSchema(); - } - - public PackageGenerator.Config getPackageGeneratorConfig() { - return this.packageGeneratorConfig; - } - - public EntityGenerator.Config getEntityGeneratorConfig() { - return this.entityGeneratorConfig; - } - - public Collection<Table> getSelectedTables() { - return this.selectedTables; - } - - public boolean synchronizePersistenceXml(){ - return this.synchronizePersistenceXml; - } - - @Override - public boolean canFinish() { - boolean canFinish = true; - if ( ! this.generateEntitiesPage.isPageComplete()) { - canFinish = false; - } - return canFinish; - } - - private boolean projectDefaultSchemaExists() { - return ( this.getDefaultSchema() != null); - } - - /** - * updatePossibleTables is called when schema’s PossibleTables changed. - * The dbSettingsPage is mainly the source of changes, - * and the generateEntitiesPage needs to be kept in sync. - */ - void updatePossibleTables( Collection<Table> possibleTables) { - this.generateEntitiesPage.updateTablesListViewer( possibleTables); - } - -} 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 af851c959b..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/GenerateEntitiesWizardPage.java +++ /dev/null @@ -1,518 +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.ArrayList; -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.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.StringTools; -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 determine name collisions -class GenerateEntitiesWizardPage extends NewTypeWizardPage { - - CheckboxTableViewer tableTable; - - private boolean convertToCamelCase = true; - private boolean fieldAccessType = true; - private String collectionTypeName = Set.class.getName(); - 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 boolean synchronizePersistenceXml = false; - private Map<Table, String> overrideEntityNames; - - static final String[] TABLE_TABLE_COLUMN_PROPERTIES = { "table", "entityName" }; - 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); - - final Button synchronizeClassesCheckBox = new Button(composite, SWT.CHECK); - synchronizeClassesCheckBox.setText(JptUiMessages.GenerateEntitiesWizardPage_synchronizeClasses); - synchronizeClassesCheckBox.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - setSynchronizePersistenceXml(synchronizeClassesCheckBox.getSelection()); - } - }); - - 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); - - GenerateEntitiesWizard generateEntitiesWizard = ((GenerateEntitiesWizard)this.getWizard()); - Collection<Table> possibleTables = generateEntitiesWizard.getPossibleTables(); - initTablesSelectionControl(possibleTables); - - //set initial selection state of the synchronize classes checkbox - synchronizeClassesCheckBox.setSelection(!generateEntitiesWizard.getJpaProject().discoversAnnotatedClasses()); - setSynchronizePersistenceXml(synchronizeClassesCheckBox.getSelection()); - - PlatformUI.getWorkbench().getHelpSystem().setHelp(this.tableTable.getControl(), JpaHelpContextIds.DIALOG_GENERATE_ENTITIES_TABLES); - - setControl(composite); - this.setPageComplete( false); - } - - private void selectAllTables(){ - this.tableTable.setAllChecked(true); - doStatusUpdate(); - } - - private void deselectAllTables(){ - this.tableTable.setAllChecked(false); - doStatusUpdate(); - } - - private void initTablesSelectionControl(Collection<Table> possibleTables) { - this.overrideEntityNames = new HashMap<Table, String>(possibleTables.size()); - 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(event); - } - }); - - 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(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - selectAllTables(); - - } - }); - - Button deselectAllButton = new Button(buttonComposite, SWT.PUSH); - deselectAllButton.setText(JptUiMessages.General_deselectAll); - gridData = new GridData(); - gridData.horizontalAlignment = GridData.FILL; - deselectAllButton.setLayoutData(gridData); - deselectAllButton.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - deselectAllTables(); - } - }); - } - - - 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) { - return; - } - 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(SelectionChangedEvent event) { - this.setPageComplete(true); - if ( ! this.hasTablesSelected()) { - this.setPageComplete(false); - } - } - - private IBaseLabelProvider buildTableTableLabelProvider() { - return new TableTableLabelProvider(); - } - - private IContentProvider buildTableTableContentProvider() { - return new TableTableContentProvider(); - } - - private ICellModifier buildTableTableCellModifier() { - return new TableTableCellModifier(); - } - - Collection<Table> getSelectedTables() { - ArrayList<Table> selectedTables = new ArrayList<Table>(); - for (Object selectedTable : this.tableTable.getCheckedElements()) - selectedTables.add((Table) selectedTable); - return selectedTables; - } - - private boolean hasTablesSelected() { - return (this.tableTable != null) ? (this.getSelectedTables().size() > 0) : false; - } - - void updateTablesListViewer(Collection<Table> possibleTables) { - if (this.tableTable != null) { - this.initTablesSelectionControl(possibleTables); - } - } - - @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.hasTablesSelected()) { - this.setPageComplete(false); - } - } - - String entityName(Table table) { - String overrideEntityName = this.overrideEntityNames.get(table); - return (overrideEntityName != null) ? overrideEntityName : this.defaultEntityName(table); - } - - private String defaultEntityName(Table table) { - String entityName = table.getShortJavaClassName(); - if (this.convertToCamelCase) { - entityName = StringTools.convertUnderscoresToCamelCase(entityName); - } - return entityName; - } - - void setOverrideEntityName(Table table, String name) { - if (table.getShortJavaClassName().equals(name)) { - this.overrideEntityNames.remove(table); - } else { - this.overrideEntityNames.put(table, name); - } - } - - boolean convertToCamelCase() { - return this.convertToCamelCase; - } - - boolean fieldAccessType() { - return this.fieldAccessType; - } - - String getCollectionTypeName() { - return this.collectionTypeName; - } - - 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; - } - - private void setSynchronizePersistenceXml(boolean synchronizePersistenceXml){ - this.synchronizePersistenceXml = synchronizePersistenceXml; - } - - /** - * key = table - * value = override entity name - */ - Map<Table, String> getOverrideEntityNames() { - return this.overrideEntityNames; - } - - - // ********** inner classes ********** - - private 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.entityName((Table) element); - } - throw new IllegalArgumentException("invalid column index: " + columnIndex); - } - - } - - - private 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(); - } - - } - - - private 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.entityName((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; - } - - boolean unchanged = false; - Table table = (Table) element; - if (property.equals(TABLE_TABLE_COLUMN_PROPERTIES[ENTITY_NAME_COLUMN_INDEX])) { - unchanged = GenerateEntitiesWizardPage.this.entityName(table).equals(value); - GenerateEntitiesWizardPage.this.setOverrideEntityName(table, (String) value); - } - if (! unchanged) { - 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 22851d2db7..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/JpaFacetWizardPage.java +++ /dev/null @@ -1,389 +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.jdt.ui.JavaUI; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.preference.PreferenceDialog; -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.jpt.ui.internal.prefs.JpaPreferencePage; -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.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; -import org.eclipse.wst.common.frameworks.datamodel.IDataModel; -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 ConnectionGroup(composite); - new ClasspathConfigGroup(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_OVERRIDE_DEFAULT_SCHEMA, - USER_OVERRIDE_DEFAULT_SCHEMA, - USE_SERVER_JPA_IMPLEMENTATION, - JPA_LIBRARY, - DISCOVER_ANNOTATED_CLASSES - }; - } - - @Override - public boolean isPageComplete() { - if (! super.isPageComplete()) { - return false; - } - else { - return (model.validate().getSeverity() != IStatus.ERROR); - } - } - - @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 ConnectionGroup - { - private final Combo connectionCombo; - - private Link connectionLink; - - private Link connectLink; - - 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(); - } - }); - - 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); - GridData 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.createNewProfile(); - if (connectionName != null) { - model.setProperty(CONNECTION, connectionName); - } - } - - private void openConnectionProfile() { - ConnectionProfile connection = getConnectionProfile(); - connection.connect(); - model.setBooleanProperty(CONNECTION_ACTIVE, connection.isActive()); - updateConnectLink(); - return; - } - - private void updateConnectLink() { - ConnectionProfile connectionProfile = getConnectionProfile(); - connectLink.setEnabled(! connectionProfile.isNull() && ! connectionProfile.isConnected()); - } - - private ConnectionProfile getConnectionProfile() { - return JptDbPlugin.instance().getConnectionProfileRepository().connectionProfileNamed(model.getStringProperty(CONNECTION)); - } - } - - - private final class ClasspathConfigGroup - { - private final Button useServerLibButton; - - private final Button specifyLibButton; - - private final Combo jpaLibCombo; - - private final Link jpaPrefsLink; - - private final Link userLibsLink; - - - public ClasspathConfigGroup(Composite composite) { - Group group = new Group(composite, SWT.NONE); - group.setText(JptUiMessages.JpaFacetWizardPage_jpaImplementationLabel); - group.setLayout(new GridLayout(2, false)); - group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - PlatformUI.getWorkbench().getHelpSystem().setHelp(group, JpaHelpContextIds.NEW_JPA_PROJECT_CONTENT_PAGE_CLASSPATH); - - useServerLibButton = createButton(group, 2, JptUiMessages.JpaFacetWizardPage_userServerLibLabel, SWT.RADIO); - synchHelper.synchRadio(useServerLibButton, USE_SERVER_JPA_IMPLEMENTATION, null); - - specifyLibButton = createButton(group, 1, JptUiMessages.JpaFacetWizardPage_specifyLibLabel, SWT.RADIO); - synchHelper.synchRadio(specifyLibButton, USE_USER_JPA_LIBRARY, null); - - jpaLibCombo = createCombo(group, 1, true); - synchHelper.synchCombo(jpaLibCombo, JPA_LIBRARY, null); - - jpaPrefsLink = new Link(group, SWT.NONE); - GridData data = new GridData(GridData.END, GridData.CENTER, false, false); - data.horizontalSpan = 2; - jpaPrefsLink.setLayoutData(data); - jpaPrefsLink.setText(JptUiMessages.JpaFacetWizardPage_jpaPrefsLink); - jpaPrefsLink.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - promptToConfigJpaPrefs(); - } - } - ); - - userLibsLink = new Link(group, SWT.NONE); - data = new GridData(GridData.END, GridData.CENTER, false, false); - data.horizontalSpan = 2; - userLibsLink.setLayoutData(data); - userLibsLink.setText(JptUiMessages.JpaFacetWizardPage_userLibsLink); - userLibsLink.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - promptToConfigUserLibraries(); - } - } - ); - } - - private void promptToConfigJpaPrefs() { - PreferenceDialog dlg = - PreferencesUtil.createPreferenceDialogOn( - getShell(), - JpaPreferencePage.ID, - new String[] {JpaPreferencePage.ID}, - null); - dlg.open(); - model.notifyPropertyChange(JPA_LIBRARY, IDataModel.VALID_VALUES_CHG); - model.notifyPropertyChange(JPA_LIBRARY, IDataModel.DEFAULT_CHG); - } - - private void promptToConfigUserLibraries() { - PreferenceDialog dlg = - PreferencesUtil.createPreferenceDialogOn( - getShell(), - JavaUI.ID_USER_LIBRARY_PREFERENCE_PAGE, - new String[] {JavaUI.ID_USER_LIBRARY_PREFERENCE_PAGE}, - null); - dlg.open(); - model.notifyPropertyChange(JPA_LIBRARY, IDataModel.VALID_VALUES_CHG); - } - } - - - 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/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/EntityClassWizardPage.java b/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityClassWizardPage.java deleted file mode 100644 index 06a7ea6f6f..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityClassWizardPage.java +++ /dev/null @@ -1,471 +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.TreePath; -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.ui.internal.wizards.entity.data.model.IEntityDataModelProperties; -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.KeyAdapter; -import org.eclipse.swt.events.KeyEvent; -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.Control; -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.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.plugin.WTPCommonPlugin; -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 XML_EXTENSION = ".xml";//$NON-NLS-1$ - private static final String PERSISTENCE_XML = "persistence.xml";//$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); - } - - /* 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(); - ormXmlName.setEnabled(isChecked); - browseButton.setEnabled(isChecked); - if (isFirstCheck) { - ormXmlName.setText(JptCorePlugin.DEFAULT_ORM_XML_FILE_PATH); - isFirstCheck = false; - } - //Disable the choose alternative XML : see enhancement request 152461 - //The creation of alternative mapping is problematic - disableMappingXMLChooseGroup(); - } - }); - 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); - ormXmlName.setEnabled(false); - //Disable the choose alternative XML : see enhancement request 152461 - //The creation of alternative mapping is problematic - disableMappingXMLChooseGroup(); - } - - /** - * 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; - } - ISelectionStatusValidator validator = getDialogSelectionValidator(); - 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.setValidator(validator); - 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 can be extended by subclasses, as it does some basic validation. - * @return new instance of the Selection validator for the SelectMappingXMLDialog - */ - protected ISelectionStatusValidator getDialogSelectionValidator() { - return new ISelectionStatusValidator() { - public IStatus validate(Object[] selection) { - if (selection != null && selection.length > 0 && selection[0] != null && !(selection[0] instanceof IProject)) - return WTPCommonPlugin.OK_STATUS; - return WTPCommonPlugin.createErrorStatus(EntityWizardMsg.INCORRECT_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 (file.getName().endsWith(XML_EXTENSION) && !file.getName().equals(PERSISTENCE_XML)) { - return true; - } - } - return false; - } - }; - } - - private void disableMappingXMLChooseGroup() { - //Disable the choose alternative XML : see enhancement request 152461 - //The creation of alternative mapping is problematic - displayNameLabel.setEnabled(false); - ormXmlName.setEnabled(false); - browseButton.setEnabled(false); - - } - - /** - * 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 Text newXmlName; - private String xmlName = EMPTY; - private IStatus currentStatus = new Status(IStatus.OK, PlatformUI.PLUGIN_ID, IStatus.OK, EMPTY, null); - - public SelectMappingXMLDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider) { - super(parent, labelProvider, contentProvider); - } - - /* - * @see Dialog#createDialogArea(Composite) - */ - @Override - protected Control createDialogArea(Composite parent) { - Composite composite = (Composite)super.createDialogArea(parent); - Label fileNameLabel = new Label(composite, SWT.LEFT); - fileNameLabel.setText(EntityWizardMsg.XML_NAME_TITLE); - fileNameLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); - newXmlName = new Text(composite, SWT.SINGLE | SWT.BORDER); - newXmlName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - newXmlName.addKeyListener(new KeyAdapter() { - @Override - public void keyReleased(KeyEvent e) { - super.keyReleased(e); - xmlName = newXmlName.getText(); - TreeSelection selection = (TreeSelection)getTreeViewer().getSelection(); - IResource selectedResource = (IResource)selection.getFirstElement(); - if (selectedResource instanceof IFile) { - getTreeViewer().setSelection(new TreeSelection(new TreePath(getSegments(selectedResource.getParent())))); - } - updateOKStatus(); - } - - }); - return composite; - } - - /** - * @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) { - IFile file = (IFile)selectedResource; - xmlName = file.getName(); - newXmlName.setText(xmlName); - currentStatus = new Status(IStatus.OK, PlatformUI.PLUGIN_ID, IStatus.OK, EMPTY, null); - } - if (!xmlName.endsWith(XML_EXTENSION)) { - currentStatus = new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, IStatus.ERROR, EntityWizardMsg.INCORRECT_XML_NAME, null); - } else { - currentStatus = new Status(IStatus.OK, PlatformUI.PLUGIN_ID, IStatus.OK, EMPTY, null); - } - updateStatus(currentStatus); - } - - /** - * 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; - } - - /** - * This method is for internal purposes only. It is intended to create correct - * selection of the resource resource - * @param resource - * @return the segments of the resource - */ - private Object[] getSegments(IResource resource) { - Object[] segments = new Object[resource.getFullPath().segments().length]; - for (int i = segments.length - 1; i > -1; i--) { - segments[i] = resource; - resource = resource.getParent(); - } - return segments; - } - } -} 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 3cf301e9d0..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityFieldsWizardPage.java +++ /dev/null @@ -1,214 +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(); - EntityRowTableWizardSection initSection = new EntityRowTableWizardSection(composite, model, IEntityDataModelProperties.ENTITY_FIELDS); - - 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; - } - - /** - * 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 bd725f8d7d..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/EntityRowTableWizardSection.java +++ /dev/null @@ -1,745 +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; - 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)); - - Label titleLabel = new Label(this, SWT.LEFT); - titleLabel.setText(title); - GridData data = new GridData(); - data.horizontalSpan = 2; - titleLabel.setLayoutData(data); - - mTableWidget = new Table(this, SWT.CHECK | SWT.FULL_SELECTION | SWT.BORDER); - mTableWidget.setHeaderVisible(true); - mTableWidget.setLinesVisible(true); - - mTableViewer = new CheckboxTableViewer(mTableWidget); - 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.getType(); - } - 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/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 7fe698b5b5..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 INCORRECT_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; - 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/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 095eb7e7d3..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/model/CreateEntityTemplateModel.java +++ /dev/null @@ -1,385 +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 311e15861c..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/model/EntityDataModelProvider.java +++ /dev/null @@ -1,212 +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.runtime.IStatus; -import org.eclipse.jdt.core.JavaConventions; -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.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); - } - - /* 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; - } - //Should be check existing of the class with the relevant name - if (propertyName.equals(CLASS_NAME)) { - String classNameValue = getStringProperty(propertyName); - result = super.validateJavaClassName(getStringProperty(propertyName)); - if (result.isOK()){ - return super.canCreateTypeInClasspath(classNameValue); - } - } - if (propertyName.equals(XML_NAME)) { -// String xmlName = getStringProperty(propertyName); -// xmlName = xmlName.substring(xmlName.lastIndexOf(File.separator) + 1); -// return ResourcesPlugin.getWorkspace().validateName(xmlName, IResource.FILE); - } - 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 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 e93ab339d8..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/entity/data/operation/NewEntityClassOperation.java +++ /dev/null @@ -1,584 +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.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.Status; -import org.eclipse.core.runtime.jobs.Job; -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.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.OrmArtifactEdit; -import org.eclipse.jpt.core.resource.orm.OrmFactory; -import org.eclipse.jpt.core.resource.orm.OrmPackage; -import org.eclipse.jpt.core.resource.orm.OrmResource; -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.PersistenceArtifactEdit; -import org.eclipse.jpt.core.resource.persistence.PersistenceFactory; -import org.eclipse.jpt.core.resource.persistence.PersistenceResource; -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.EntityWizardMsg; -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.project.WTPJETEmitter; -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$ - - - /** - * 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 filter template model - CreateEntityTemplateModel tempModel = createTemplateModel(); - IProject project = getTargetProject(); - String entityClassSource = null; - String idClassSource = null; - // Using the WTPJetEmitter, generate the java source based on the filter template model - try { - if (tempModel.isArtifactsAnnotated()) { - entityClassSource = generateTemplateSource(tempModel, monitor, ANNOTATED_ENTITY_TEMPLATE_FILE); - } else { - entityClassSource = generateTemplateSource(tempModel, monitor, ENTITY_TEMPLATE_FILE); - } - if (tempModel.isCompositePK()) { - idClassSource = generateTemplateSource(tempModel, monitor, IDCLASS_TEMPLATE_FILE); - - } - } 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()) { - addMappedSuperclassToXLM(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 tempModel - * @param monitor - * @param template_file - * @return String the source for the java file - * @throws JETException - */ - private String generateTemplateSource(CreateEntityTemplateModel tempModel, IProgressMonitor monitor, String template_file) throws JETException { - URL templateURL = FileLocator.find(JptUiPlugin.getPlugin().getBundle(), new Path(template_file), 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[] { tempModel }); - } - - /** - * 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) { - OrmArtifactEdit oae = OrmArtifactEdit.getArtifactEditForWrite(project); - try { - String xmlUri = JptCorePlugin.getDefaultOrmXmlDeploymentURI(project); - OrmResource resource = oae.getResource(xmlUri); - if (!model.isMappingXMLDefault()) { - resource = oae.getResource(model.getMappingXmlFile()); - } - - 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); - oae.save(null); - } catch (Exception e) { - JptUiPlugin.log(e); - oae.dispose(); - } finally { - oae.dispose(); - } - 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 addMappedSuperclassToXLM(final CreateEntityTemplateModel model, final IProject project) { - Job job = new Job(EntityWizardMsg.ADD_MAPPED_SUPERCLASS_TO_XML) { - @Override - protected IStatus run(IProgressMonitor monitor) { - OrmArtifactEdit oae = OrmArtifactEdit.getArtifactEditForWrite(project); - try { - //OrmResource resource = oae.getResource(JptCorePlugin.ormXmlDeploymentURI(project)); - String xmlUri = JptCorePlugin.getDefaultOrmXmlDeploymentURI(project); - if (!model.isMappingXMLDefault()) { - xmlUri = model.getMappingXMLName(); - } - OrmResource resource = oae.getResource(xmlUri); - 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); - oae.save(null); - } catch (Exception e) { - JptUiPlugin.log(e); - } finally { - oae.dispose(); - } - 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) { - String fileName = getLastSegment(model.getMappingXMLName()); - PersistenceArtifactEdit pae = PersistenceArtifactEdit.getArtifactEditForWrite(project); - try { - PersistenceResource persistenceResource = pae.getResource(JptCorePlugin.getPersistenceXmlDeploymentURI(project)); - 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); - pae.save(null); - } catch (Exception e) { - JptUiPlugin.log(e); - } finally { - pae.dispose(); - } - 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 04e198336d..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/orm/MappingFileWizard.java +++ /dev/null @@ -1,266 +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 = new MappingFileWizardPage(getDataModel(), "Page_1"); - addPage(page); - } - - @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 cc1b313fbe..0000000000 --- a/jpa/plugins/org.eclipse.jpt.ui/src/org/eclipse/jpt/ui/internal/wizards/orm/MappingFileWizardPage.java +++ /dev/null @@ -1,271 +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); - - projectNameLabel = new Label(composite, SWT.NONE); - projectNameLabel.setText(JptUiMessages.MappingFileWizardPage_projectLabel); //$NON-NLS-1$ - data = new GridData(); - projectNameLabel.setLayoutData(data); - - projectNameCombo = new Combo(composite, SWT.BORDER | SWT.READ_ONLY); - data = new GridData(GridData.FILL_HORIZONTAL); - data.widthHint = 300; - data.horizontalSpan = 1; - projectNameCombo.setLayoutData(data); - synchHelper.synchCombo(projectNameCombo, PROJECT_NAME, null); - new Label(composite, SWT.NONE); - - sourceFolderLabel = new Label(composite, SWT.NONE); - sourceFolderLabel.setText(JptUiMessages.MappingFileWizardPage_sourceFolderLabel); //$NON-NLS-1$ - data = new GridData(); - sourceFolderLabel.setLayoutData(data); - - sourceFolderText = new Text(composite, SWT.BORDER); - data = new GridData(GridData.FILL_HORIZONTAL); - data.widthHint = 300; - data.horizontalSpan = 1; - sourceFolderText.setLayoutData(data); - synchHelper.synchText(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(); - } - }); - - filePathLabel = new Label(composite, SWT.NONE); - filePathLabel.setText(JptUiMessages.MappingFileWizardPage_filePathLabel); //$NON-NLS-1$ - data = new GridData(); - filePathLabel.setLayoutData(data); - - filePathText = new Text(composite, SWT.BORDER | SWT.READ_ONLY); - data = new GridData(GridData.FILL_HORIZONTAL); - data.widthHint = 300; - data.horizontalSpan = 1; - filePathText.setLayoutData(data); - synchHelper.synchText(filePathText, FILE_PATH, null); - new Label(composite, SWT.NONE); - - accessLabel = new Label(composite, SWT.NONE); - accessLabel.setText(JptUiMessages.MappingFileWizardPage_accessLabel); //$NON-NLS-1$ - data = new GridData(); - accessLabel.setLayoutData(data); - - accessCombo = new Combo(composite, SWT.BORDER | SWT.READ_ONLY); - data = new GridData(GridData.FILL_HORIZONTAL); - data.widthHint = 300; - data.horizontalSpan = 1; - accessCombo.setLayoutData(data); - synchHelper.synchCombo(accessCombo, DEFAULT_ACCESS, null); - new Label(composite, SWT.NONE); - - addToPersistenceUnitButton = new Button(composite, SWT.CHECK | SWT.BEGINNING); - addToPersistenceUnitButton.setText(JptUiMessages.MappingFileWizardPage_addToPersistenceUnitButton); - data = new GridData(GridData.FILL_HORIZONTAL); - data.horizontalSpan = 3; - addToPersistenceUnitButton.setLayoutData(data); - synchHelper.synchCheckbox(addToPersistenceUnitButton, ADD_TO_PERSISTENCE_UNIT, null); - - persistenceUnitLabel = new Label(composite, SWT.NONE); - persistenceUnitLabel.setText(JptUiMessages.MappingFileWizardPage_persistenceUnitLabel); //$NON-NLS-1$ - data = new GridData(); - persistenceUnitLabel.setLayoutData(data); - - persistenceUnitCombo = new Combo(composite, SWT.BORDER | SWT.READ_ONLY); - data = new GridData(GridData.FILL_HORIZONTAL); - data.widthHint = 300; - data.horizontalSpan = 1; - persistenceUnitCombo.setLayoutData(data); - synchHelper.synchCombo(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(Status.ERROR, JptUiPlugin.PLUGIN_ID, JptUiMessages.MappingFileWizardPage_incorrectSourceFolderError); - } - }; - } - - private ViewerFilter getSourceFolderDialogViewerFilter() { - return new ViewerFilter() { - 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) { - - } -} |