Author: dgeraskov
Date: 2009-05-04 08:08:45 -0400 (Mon, 04 May 2009)
New Revision: 15000
Added:
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/icons/hibernate_small_icon.gif
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/ConfigurationActor.java
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/NewHibernateMappingFilePage.java
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/NewHibernateMappingFileWizard.java
trunk/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/HbmExportExceptionTest.java
trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/res/hbm/
trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/res/hbm/pack/
trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/res/hbm/pack/A.java
trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/res/hbm/pack/B.java
trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/src/org/hibernate/eclipse/jdt/ui/test/hbmexporter/
trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/src/org/hibernate/eclipse/jdt/ui/test/hbmexporter/HbmExporterTest.java
Removed:
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/wizards/NewHibernateMappingFilePage.java
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/wizards/NewHibernateMappingFileWizard.java
Modified:
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/META-INF/MANIFEST.MF
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/plugin.properties
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/plugin.xml
trunk/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/Customization.java
trunk/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/TestSet.java
Log:
https://jira.jboss.org/jira/browse/JBIDE-3457
Deleted:
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/wizards/NewHibernateMappingFilePage.java
===================================================================
---
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/wizards/NewHibernateMappingFilePage.java 2009-05-04
10:06:51 UTC (rev 14999)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/wizards/NewHibernateMappingFilePage.java 2009-05-04
12:08:45 UTC (rev 15000)
@@ -1,285 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site:
http://www.fsf.org.
- */
-package org.hibernate.eclipse.console.wizards;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.core.search.IJavaSearchScope;
-import org.eclipse.jdt.core.search.SearchEngine;
-import org.eclipse.jdt.ui.IJavaElementSearchConstants;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jface.dialogs.IDialogPage;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.ScrolledComposite;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-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.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.dialogs.ContainerSelectionDialog;
-import org.eclipse.ui.dialogs.SelectionDialog;
-import org.eclipse.ui.dialogs.WizardNewFileCreationPage;
-import org.hibernate.eclipse.console.HibernateConsoleMessages;
-import org.hibernate.eclipse.console.HibernateConsolePlugin;
-import org.hibernate.eclipse.console.utils.xpl.SelectionHelper;
-
-/**
- * The "New" wizard page allows setting the container for the new file as well
- * as the file name. The page will only accept file name without the extension
- * OR with the extension that matches the expected one (hbm.xml).
- */
-
-public class NewHibernateMappingFilePage extends WizardPage {
- private Label containerText;
-
- private Label fileText;
-
- private ISelection selection;
-
- private Text classToMap;
-
- private WizardNewFileCreationPage fileCreation;
-
- private boolean beenShown;
-
- /**
- * Constructor for SampleNewWizardPage.
- * @param page
- *
- * @param pageName
- */
- public NewHibernateMappingFilePage(ISelection selection, WizardNewFileCreationPage page)
{
- super("wizardPage"); //$NON-NLS-1$
- this.fileCreation = page;
- setTitle(HibernateConsoleMessages.NewHibernateMappingFilePage_hibernate_xml_mapping_file);
- setDescription(HibernateConsoleMessages.NewHibernateMappingFilePage_this_wizard_creates);
- this.selection = selection;
- }
-
- public void setVisible(boolean visible) {
- containerText.setText(fileCreation.getContainerFullPath().toPortableString() );
- fileText.setText(fileCreation.getFileName() );
- super.setVisible(visible);
- if(visible) {
- classToMap.setFocus();
- }
- beenShown = true;
- dialogChanged();
- }
-
- /**
- * @see IDialogPage#createControl(Composite)
- */
- public void createControl(Composite parent) {
- final ScrolledComposite sc = new ScrolledComposite(parent, SWT.H_SCROLL |
SWT.V_SCROLL);
- sc.setExpandHorizontal(true);
- sc.setExpandVertical(true);
-
- Composite container = new Composite(sc, SWT.NULL);
- sc.setContent(container);
- GridLayout layout = new GridLayout();
- container.setLayout(layout);
- layout.numColumns = 3;
- layout.verticalSpacing = 9;
-
- Label label = new Label(container, SWT.NULL);
- label.setText(HibernateConsoleMessages.NewHibernateMappingFilePage_container);
-
- containerText = new Label(container, SWT.BORDER | SWT.SINGLE);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- containerText.setLayoutData(gd);
-
- label = new Label(container, SWT.NULL);
- label.setText(""); //$NON-NLS-1$
-
- label = new Label(container, SWT.NULL);
- label.setText(HibernateConsoleMessages.NewHibernateMappingFilePage_file_name);
-
- fileText = new Label(container, SWT.BORDER | SWT.SINGLE);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- fileText.setLayoutData(gd);
-
- label = new Label(container, SWT.NULL);
- label.setText(""); //$NON-NLS-1$
-
- label = new Label(container, SWT.NULL);
- label.setText(HibernateConsoleMessages.NewHibernateMappingFilePage_class_to_map);
-
- classToMap = new Text(container, SWT.BORDER | SWT.SINGLE);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- classToMap.setLayoutData(gd);
- classToMap.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- dialogChanged();
- }
- });
- //TODO (internal api!):
ControlContentAssistHelper.createTextContentAssistant(classToMap, aCompletionProcessor);
-
- Button button = new Button(container, SWT.PUSH);
- button.setText(HibernateConsoleMessages.NewHibernateMappingFilePage_browse);
- button.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- handleClassToMapBrowse();
- }
- });
-
- sc.setMinSize(container.computeSize(SWT.DEFAULT, SWT.DEFAULT));
-
- initialize();
- dialogChanged();
- setControl(sc);
- }
-
- /**
- * Tests if the current workbench selection is a suitable container to use.
- */
-
- private void initialize() {
- IType initialJavaElement =
SelectionHelper.getClassFromElement(SelectionHelper.getInitialJavaElement(selection));
- if(initialJavaElement!=null) {
- classToMap.setText(initialJavaElement.getFullyQualifiedName('.'));
- }
- }
-
- /**
- * Uses the standard container selection dialog to choose the new value for
- * the container field.
- */
-
- private void handleBrowse() {
- ContainerSelectionDialog dialog = new ContainerSelectionDialog(
- getShell(), ResourcesPlugin.getWorkspace().getRoot(), false,
- HibernateConsoleMessages.NewHibernateMappingFilePage_select_new_file_container);
- if (dialog.open() == ContainerSelectionDialog.OK) {
- Object[] result = dialog.getResult();
- if (result.length == 1) {
- containerText.setText(((Path) result[0]).toString());
- }
- }
- }
-
- private void handleClassToMapBrowse() {
- IType type = findClassToMap();
- if(type!=null) {
- classToMap.setText(type.getFullyQualifiedName('.'));
- }
- }
-
- IType findClassToMap() {
- IJavaProject root= getRootJavaProject();
- if (root == null)
- return null;
-
- IJavaElement[] elements= new IJavaElement[] { root };
- IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);
-
- try {
- SelectionDialog dialog= JavaUI.createTypeDialog(getShell(),
getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES, false,
getClassToMapText());
- dialog.setTitle(HibernateConsoleMessages.NewHibernateMappingFilePage_select_class_to_map);
- dialog.setMessage(HibernateConsoleMessages.NewHibernateMappingFilePage_the_class_will_be_used_when);
- if (dialog.open() == Window.OK) {
- Object[] resultArray= dialog.getResult();
- if (resultArray != null && resultArray.length > 0)
- return (IType) resultArray[0];
- }
- } catch (JavaModelException e) {
- HibernateConsolePlugin.getDefault().log(e);
- }
- return null;
- }
-
- private IJavaProject getRootJavaProject() {
- IResource resource =
ResourcesPlugin.getWorkspace().getRoot().findMember(containerText.getText());
- if(resource!=null) {
- if(resource.getProject()!=null) {
- IJavaProject project = JavaCore.create(resource.getProject());
- return project;
- }
- }
- return null;
- }
-
- String getClassToMapText() {
- return classToMap.getText();
- }
-
- /**
- * Ensures that both text fields are set.
- */
-
- private void dialogChanged() {
- IResource container = ResourcesPlugin.getWorkspace().getRoot()
- .findMember(new Path(getContainerName()));
- String fileName = getFileName();
-
- if (getContainerName().length() == 0) {
- updateStatus(HibernateConsoleMessages.NewHibernateMappingFilePage_file_container_must_be_specified);
- return;
- }
- if (container == null
- || (container.getType() & (IResource.PROJECT | IResource.FOLDER)) == 0) {
- updateStatus(HibernateConsoleMessages.NewHibernateMappingFilePage_file_container_must_exist);
- return;
- }
- if (!container.isAccessible()) {
- updateStatus(HibernateConsoleMessages.NewHibernateMappingFilePage_project_must_be_writable);
- return;
- }
- if (fileName.length() == 0) {
- updateStatus(HibernateConsoleMessages.NewHibernateMappingFilePage_file_name_must_be_specified);
- return;
- }
- if (fileName.replace('\\', '/').indexOf('/', 1) > 0) {
- updateStatus(HibernateConsoleMessages.NewHibernateMappingFilePage_file_name_must_be_valid);
- return;
- }
-
- updateStatus(null);
- }
-
- private void updateStatus(String message) {
- setErrorMessage(message);
- setPageComplete(message == null);
- }
-
- public String getContainerName() {
- return containerText.getText();
- }
-
- public String getFileName() {
- return fileText.getText();
- }
-}
\ No newline at end of file
Deleted:
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/wizards/NewHibernateMappingFileWizard.java
===================================================================
---
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/wizards/NewHibernateMappingFileWizard.java 2009-05-04
10:06:51 UTC (rev 14999)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/wizards/NewHibernateMappingFileWizard.java 2009-05-04
12:08:45 UTC (rev 15000)
@@ -1,225 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site:
http://www.fsf.org.
- */
-package org.hibernate.eclipse.console.wizards;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.ui.INewWizard;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWizard;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.WizardNewFileCreationPage;
-import org.eclipse.ui.ide.IDE;
-import org.hibernate.console.ImageConstants;
-import org.hibernate.eclipse.console.HibernateConsoleMessages;
-import org.hibernate.eclipse.console.HibernateConsolePlugin;
-import org.hibernate.eclipse.console.utils.EclipseImages;
-import org.hibernate.eclipse.console.utils.xpl.SelectionHelper;
-import org.hibernate.util.StringHelper;
-
-public class NewHibernateMappingFileWizard extends Wizard implements INewWizard {
- private NewHibernateMappingFilePage mappingFileInfoPage;
- private ISelection selection;
- private WizardNewFileCreationPage cPage;
-
-
- /**
- * Constructor for NewConfigurationWizard.
- */
- public NewHibernateMappingFileWizard() {
- super();
-
setDefaultPageImageDescriptor(EclipseImages.getImageDescriptor(ImageConstants.NEW_WIZARD)
);
- setNeedsProgressMonitor(true);
- }
-
- /** extended to update status messages on first show **/
- static class ExtendedWizardNewFileCreationPage extends WizardNewFileCreationPage {
-
- public ExtendedWizardNewFileCreationPage(String pageName, IStructuredSelection
selection) {
- super(pageName, selection);
- }
-
- boolean firstTime = true;
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if(firstTime) {
- validatePage();
- firstTime = false;
- }
- }
- }
- /**
- * Adding the page to the wizard.
- */
-
- public void addPages() {
- cPage =
- new ExtendedWizardNewFileCreationPage( "Chbmxml",
(IStructuredSelection) selection ); //$NON-NLS-1$
- cPage.setTitle(
HibernateConsoleMessages.NewHibernateMappingFileWizard_create_hibernate_xml_mapping_file
);
- cPage.setDescription(
HibernateConsoleMessages.NewHibernateMappingFileWizard_create_new_xml_mapping_file );
- IType initialJavaElement =
SelectionHelper.getClassFromElement(SelectionHelper.getInitialJavaElement(selection));
- if(initialJavaElement!=null) {
- cPage.setFileName(initialJavaElement.getElementName() + ".hbm.xml");
//$NON-NLS-1$
- } else {
- cPage.setFileName("NewMapping.hbm.xml"); //$NON-NLS-1$
- }
- addPage( cPage );
-
-
- mappingFileInfoPage = new NewHibernateMappingFilePage(selection, cPage);
- addPage(mappingFileInfoPage);
-
- }
-
-
-
- /**
- * This method is called when 'Finish' button is pressed in
- * the wizard. We will create an operation and run it
- * using wizard as execution context.
- */
- public boolean performFinish() {
- final IFile file = cPage.createNewFile();
- final String classToMapText = mappingFileInfoPage.getClassToMapText();
-
- IRunnableWithProgress op = new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException {
- try {
- createFile(file, classToMapText, monitor);
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- } finally {
- monitor.done();
- }
- }
- };
- try {
- getContainer().run(true, false, op);
- } catch (InterruptedException e) {
- return false;
- } catch (InvocationTargetException e) {
- Throwable realException = e.getTargetException();
- HibernateConsolePlugin.getDefault().log(realException);
- return false;
- }
- return true;
- }
-
-
- /**
- * The worker method. It will find the container, create the
- * file if missing or just replace its contents, and open
- * the editor on the newly created file.
- * @param file
- * @param props
- */
-
- private void createFile(
- final IFile file, String classToMapText, IProgressMonitor monitor)
- throws CoreException {
- // create a sample file
- monitor.beginTask(HibernateConsoleMessages.NewHibernateMappingFileWizard_creating +
file.getName(), 2);
- try {
- InputStream stream = openContentStream(classToMapText);
- if (file.exists() ) {
- file.setContents(stream, true, true, monitor);
- } else {
- file.create(stream, true, monitor);
- }
- stream.close();
- } catch (IOException e) {
- }
- monitor.worked(1);
- monitor.setTaskName(HibernateConsoleMessages.NewHibernateMappingFileWizard_opening_file_for_editing);
- getShell().getDisplay().asyncExec(new Runnable() {
- public void run() {
- IWorkbenchPage page =
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- try {
- IDE.openEditor(page, file, true);
- } catch (PartInitException e) {
- }
- }
- });
- monitor.worked(1);
- }
-
- /**
- * We will initialize file contents with a sample text.
- */
-
- private InputStream openContentStream(String classToMapText) {
-
- String classname = null;
- String packagename = null;
-
- if(StringHelper.isNotEmpty(classToMapText)) {
- classname = StringHelper.unqualify(classToMapText);
- packagename = StringHelper.qualifier(classToMapText);
- }
- String contents =
- "<?xml version=\"1.0\"?>\n" + //$NON-NLS-1$
- "<!DOCTYPE hibernate-mapping PUBLIC\n" + //$NON-NLS-1$
- " \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\n" +
//$NON-NLS-1$
- " \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\n"
+ //$NON-NLS-1$
- "<hibernate-mapping"; //$NON-NLS-1$
-
- if(StringHelper.isNotEmpty(packagename)) {
- contents +=" package=\"" + packagename + "\">";
//$NON-NLS-1$//$NON-NLS-2$
- } else {
- contents +=">\n"; //$NON-NLS-1$
- }
-
- if(StringHelper.isNotEmpty(classname)) {
- contents +="\n <class name=\"" + classname +
"\">\n" + //$NON-NLS-1$ //$NON-NLS-2$
- " </class>"; //$NON-NLS-1$
- }
-
- contents += "\n</hibernate-mapping>"; //$NON-NLS-1$
-
- return new ByteArrayInputStream(contents.getBytes());
- }
-
- /**
- * We will accept the selection in the workbench to see if
- * we can initialize from it.
- * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
- */
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- this.selection = selection;
- }
-
-
-}
\ No newline at end of file
Modified: trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/META-INF/MANIFEST.MF
===================================================================
---
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/META-INF/MANIFEST.MF 2009-05-04
10:06:51 UTC (rev 14999)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/META-INF/MANIFEST.MF 2009-05-04
12:08:45 UTC (rev 15000)
@@ -26,4 +26,5 @@
org.hibernate.eclipse.jdt.ui.internal.jpa.actions,
org.hibernate.eclipse.jdt.ui.internal.jpa.collect,
org.hibernate.eclipse.jdt.ui.internal.jpa.common,
- org.hibernate.eclipse.jdt.ui.internal.jpa.process
+ org.hibernate.eclipse.jdt.ui.internal.jpa.process,
+ org.hibernate.eclipse.jdt.ui.wizards
Added:
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/icons/hibernate_small_icon.gif
===================================================================
(Binary files differ)
Property changes on:
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/icons/hibernate_small_icon.gif
___________________________________________________________________
Name: svn:mime-type
+ image/gif
Modified: trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/plugin.properties
===================================================================
--- trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/plugin.properties 2009-05-04
10:06:51 UTC (rev 14999)
+++ trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/plugin.properties 2009-05-04
12:08:45 UTC (rev 15000)
@@ -6,3 +6,4 @@
JavaEditorMenu_GenerateHibernateAnnotations=Generate &Hibernate/JPA annotations...
JavaElementMenu_GenerateHibernateAnnotations=Generate &Hibernate/JPA annotations
Menu_Source=&Source
+New_wizard_menu_New_mapping_file=Hibernate XML Mapping file (hbm.xml)
\ No newline at end of file
Modified: trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/plugin.xml
===================================================================
--- trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/plugin.xml 2009-05-04
10:06:51 UTC (rev 14999)
+++ trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/plugin.xml 2009-05-04
12:08:45 UTC (rev 15000)
@@ -142,5 +142,13 @@
</action>
</objectContribution>
</extension>
-
+ <extension
+ point="org.eclipse.ui.newWizards">
+ <wizard
+ category="hibernatewizards"
+
class="org.hibernate.eclipse.jdt.ui.wizards.NewHibernateMappingFileWizard"
+ icon="icons/hibernate_small_icon.gif"
+
id="org.hibernate.eclipse.console.wizards.NewHibernateMappingFileWizard"
+ name="%New_wizard_menu_New_mapping_file"/>
+ </extension>
</plugin>
Added:
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/ConfigurationActor.java
===================================================================
---
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/ConfigurationActor.java
(rev 0)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/ConfigurationActor.java 2009-05-04
12:08:45 UTC (rev 15000)
@@ -0,0 +1,574 @@
+/*******************************************************************************
+ * Copyright (c) 2007-2008 Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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
+ *
+ * Contributor:
+ * Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.hibernate.eclipse.jdt.ui.wizards;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.Map.Entry;
+
+import org.eclipse.core.runtime.Assert;
+import org.eclipse.jdt.core.ICompilationUnit;
+import org.eclipse.jdt.core.IJavaProject;
+import org.eclipse.jdt.core.IType;
+import org.eclipse.jdt.core.JavaModelException;
+import org.eclipse.jdt.core.dom.ASTVisitor;
+import org.eclipse.jdt.core.dom.ArrayType;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.jdt.core.dom.FieldDeclaration;
+import org.eclipse.jdt.core.dom.ITypeBinding;
+import org.eclipse.jdt.core.dom.MethodDeclaration;
+import org.eclipse.jdt.core.dom.ParameterizedType;
+import org.eclipse.jdt.core.dom.PrimitiveType;
+import org.eclipse.jdt.core.dom.QualifiedType;
+import org.eclipse.jdt.core.dom.SimpleType;
+import org.eclipse.jdt.core.dom.Type;
+import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
+import org.eclipse.jdt.core.dom.WildcardType;
+import org.hibernate.FetchMode;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Mappings;
+import org.hibernate.eclipse.jdt.ui.internal.jpa.collect.AllEntitiesInfoCollector;
+import org.hibernate.eclipse.jdt.ui.internal.jpa.common.EntityInfo;
+import org.hibernate.eclipse.jdt.ui.internal.jpa.common.RefEntityInfo;
+import org.hibernate.eclipse.jdt.ui.internal.jpa.common.RefType;
+import org.hibernate.eclipse.jdt.ui.internal.jpa.common.Utils;
+import org.hibernate.mapping.Array;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.IndexedCollection;
+import org.hibernate.mapping.JoinedSubclass;
+import org.hibernate.mapping.List;
+import org.hibernate.mapping.ManyToOne;
+import org.hibernate.mapping.OneToMany;
+import org.hibernate.mapping.OneToOne;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.PrimitiveArray;
+import org.hibernate.mapping.Property;
+import org.hibernate.mapping.RootClass;
+import org.hibernate.mapping.SimpleValue;
+import org.hibernate.mapping.SingleTableSubclass;
+import org.hibernate.mapping.Subclass;
+import org.hibernate.mapping.Table;
+import org.hibernate.mapping.ToOne;
+import org.hibernate.mapping.Value;
+import org.hibernate.util.StringHelper;
+
+/**
+ * @author Dmitry Geraskov
+ *
+ */
+public class ConfigurationActor {
+
+ /**
+ * selected compilation units for startup processing,
+ * result of processing selection
+ */
+ protected Set<ICompilationUnit> selectionCU;
+
+ public ConfigurationActor(Set<ICompilationUnit> selectionCU){
+ this.selectionCU = selectionCU;
+ }
+
+ /**
+ *
+ * @return different configuration for different projects
+ */
+ public Map<IJavaProject, Configuration> createConfigurations(){
+ Map<IJavaProject, Configuration> configs = new HashMap<IJavaProject,
Configuration>();
+ if (selectionCU.size() == 0) {
+ return configs;
+ }
+
+ AllEntitiesInfoCollector collector = new AllEntitiesInfoCollector();
+ Iterator<ICompilationUnit> it = selectionCU.iterator();
+
+ Map<IJavaProject, Set<ICompilationUnit>> mapJP_CUSet =
+ new HashMap<IJavaProject, Set<ICompilationUnit>>();
+ //separate by parent project
+ while (it.hasNext()) {
+ ICompilationUnit cu = it.next();
+ Set<ICompilationUnit> set = mapJP_CUSet.get(cu.getJavaProject());
+ if (set == null) {
+ set = new HashSet<ICompilationUnit>();
+ mapJP_CUSet.put(cu.getJavaProject(), set);
+ }
+ set.add(cu);
+ }
+ Iterator<Map.Entry<IJavaProject, Set<ICompilationUnit>>>
+ mapIt = mapJP_CUSet.entrySet().iterator();
+ while (mapIt.hasNext()) {
+ Map.Entry<IJavaProject, Set<ICompilationUnit>>
+ entry = mapIt.next();
+ IJavaProject javaProject = entry.getKey();
+ Iterator<ICompilationUnit> setIt = entry.getValue().iterator();
+ collector.initCollector(javaProject);
+ while (setIt.hasNext()) {
+ ICompilationUnit icu = setIt.next();
+ collector.collect(icu);
+ }
+ collector.resolveRelations();
+ //I don't check here if any non abstract class selected
+ configs.put(javaProject, createConfiguration(javaProject,
collector.getMapCUs_Info()));
+
+ }
+ return configs;
+ }
+
+ protected Configuration createConfiguration(IJavaProject project, Map<String,
EntityInfo> entities) {
+ Configuration config = new Configuration();
+
+ ProcessEntityInfo processor = new ProcessEntityInfo();
+ processor.setEntities(entities);
+
+ for (Entry<String, EntityInfo> entry : entities.entrySet()) {
+ String fullyQualifiedName = entry.getKey();
+ ICompilationUnit icu = Utils.findCompilationUnit(project, fullyQualifiedName);
+ CompilationUnit cu = Utils.getCompilationUnit(icu, true);
+
+ processor.setEntityInfo(entry.getValue());
+ cu.accept(processor);
+ }
+
+ Mappings mappings = config.createMappings();
+ Collection<PersistentClass> classesCollection = createHierarhyStructure(project,
processor.getRootClasses());
+ for (PersistentClass persistentClass : classesCollection) {
+ mappings.addClass(persistentClass);
+ }
+ return config;
+ }
+
+ /**
+ * Replace <class> element on <joined-subclass> or <subclass>.
+ * @param project
+ * @param rootClasses
+ * @return
+ */
+ private Collection<PersistentClass> createHierarhyStructure(IJavaProject project,
Map<String, RootClass> rootClasses){
+ Map<String, PersistentClass> pcCopy = new HashMap<String,
PersistentClass>();
+ for (Map.Entry<String, RootClass> entry : rootClasses.entrySet()) {
+ pcCopy.put(entry.getKey(), entry.getValue());
+ }
+ for (Map.Entry<String, PersistentClass> entry : pcCopy.entrySet()) {
+ PersistentClass pc = null;
+ try {
+ pc = getMappedSuperclass(project, pcCopy, (RootClass) entry.getValue());
+ Subclass subclass = null;
+ if (pc != null){
+ subclass = new JoinedSubclass(pc);
+ } else {
+ pc = getMappedImplementedInterface(project, pcCopy, (RootClass) entry.getValue());
+ if (pc != null){
+ subclass = new SingleTableSubclass(pc);
+ }
+ }
+ if (subclass != null){
+ PersistentClass pastClass = pcCopy.get(entry.getKey());
+ subclass.setClassName(pastClass.getClassName());
+ subclass.setEntityName(pastClass.getEntityName());
+ subclass.setDiscriminatorValue(StringHelper.unqualify(pastClass.getClassName()));
+ subclass.setAbstract(pastClass.isAbstract());
+ entry.setValue(subclass);
+ }
+ } catch (JavaModelException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ return pcCopy.values();
+ }
+
+ private PersistentClass getMappedSuperclass(IJavaProject project, Map<String,
PersistentClass> persistentClasses, RootClass rootClass) throws JavaModelException{
+ IType type = Utils.findType(project, rootClass.getClassName());
+ //TODO not direct superclass?
+ if (type.getSuperclassName() != null
+ && persistentClasses.get(type.getSuperclassName()) != null){
+ return persistentClasses.get(type.getSuperclassName());
+ }
+ return null;
+ }
+
+ private PersistentClass getMappedImplementedInterface(IJavaProject project,
Map<String, PersistentClass> persistentClasses, RootClass rootClass) throws
JavaModelException{
+ IType type = Utils.findType(project, rootClass.getClassName());
+ //TODO not direct interfaces?
+ String[] interfaces = type.getSuperInterfaceNames();
+ for (String interfaze : interfaces) {
+ String[][] fullInterfaces = type.resolveType(interfaze);
+ for (String[] fullInterface : fullInterfaces) {
+ String inrefaceName = fullInterface[0] + '.' + fullInterface[1];
+ if (persistentClasses.get(inrefaceName) != null){
+ return persistentClasses.get(inrefaceName);
+ }
+ }
+ }
+ return null;
+ }
+
+}
+
+class ProcessEntityInfo extends ASTVisitor {
+
+ private Map<String, RootClass> rootClasses = new HashMap<String,
RootClass>();
+
+ /**
+ * current rootClass
+ */
+ private RootClass rootClass;
+
+ /**
+ * information about entity
+ */
+ protected EntityInfo entityInfo;
+
+ TypeVisitor typeVisitor;
+
+ /**
+ * information about all entities
+ */
+ protected Map<String, EntityInfo> entities;
+
+ public void setEntities(Map<String, EntityInfo> entities) {
+ this.entities = entities;
+ rootClasses.clear();
+ Iterator<Map.Entry<String, EntityInfo>> it =
entities.entrySet().iterator();
+ while (it.hasNext()) {
+ Map.Entry<String, EntityInfo> entry = it.next();
+ EntityInfo entryInfo = entry.getValue();
+ String className = entryInfo.getName();
+ Table table = new Table(className.toUpperCase());
+ RootClass rootClass = new RootClass();
+ rootClass.setEntityName( className );
+ rootClass.setClassName( entryInfo.getFullyQualifiedName() );
+ rootClass.setProxyInterfaceName( className );
+ rootClass.setLazy(true);
+ rootClass.setTable(table);
+ rootClass.setAbstract(entryInfo.isAbstractFlag());//abstract or interface
+ rootClasses.put(entry.getKey(), rootClass);
+ }
+ typeVisitor = new TypeVisitor(rootClasses);
+ }
+
+
+ public void setEntityInfo(EntityInfo entityInfo) {
+ this.entityInfo = entityInfo;
+ rootClass = rootClasses.get(entityInfo.getFullyQualifiedName());
+ }
+
+ @Override
+ public boolean visit(CompilationUnit node) {
+ Assert.isNotNull(rootClass);
+ return true;
+ }
+
+ public boolean visit(FieldDeclaration node) {
+ Type type = node.getType();
+ if (type == null) {
+ return true;
+ }
+
+ String primaryIdName = entityInfo.getPrimaryIdName();
+ Iterator itVarNames = node.fragments().iterator();
+ while (itVarNames.hasNext()) {
+ VariableDeclarationFragment var = (VariableDeclarationFragment)itVarNames.next();
+ Property prop = createProperty(var);
+ if (prop == null) {
+ continue;
+ }
+
+ String name = var.getName().getIdentifier();
+ if (name.equals(primaryIdName)) {
+ rootClass.setIdentifierProperty(prop);
+ } else {
+ rootClass.addProperty(prop);
+ }
+ }
+
+ return true;
+ }
+
+ @Override
+ public boolean visit(MethodDeclaration node) {
+ if (!entityInfo.isInterfaceFlag()) return super.visit(node);
+ org.eclipse.jdt.core.dom.TypeDeclaration type =
(org.eclipse.jdt.core.dom.TypeDeclaration) node.getParent();
+ //TODO check Abstract methods
+ if (type.isInterface()){
+ String varName = Utils.getFieldNameByGetter(node);
+ if (varName != null){
+ String primaryIdName = entityInfo.getPrimaryIdName();
+ Type methodType = node.getReturnType2();
+ if (varName.toLowerCase().equals(primaryIdName.toLowerCase()))
+ varName = primaryIdName;
+ Property prop = createProperty(varName, methodType);
+ if (varName.equals(primaryIdName)) {
+ rootClass.setIdentifierProperty(prop);
+ } else {
+ rootClass.addProperty(prop);
+ }
+ //System.out.println("From method->" + varName);
+ }
+ }
+ return super.visit(node);
+ }
+
+
+ /**
+ * @return the rootClass
+ */
+ public PersistentClass getPersistentClass() {
+ return rootClass;
+ }
+
+ protected Property createProperty(VariableDeclarationFragment var) {
+ return createProperty(var.getName().getIdentifier(),
((FieldDeclaration)var.getParent()).getType());
+ }
+
+ protected Property createProperty(String varName, Type varType) {
+ typeVisitor.init(varName, entityInfo);
+ varType.accept(typeVisitor);
+ Property p = typeVisitor.getProperty();
+ return p;
+ }
+
+ /**
+ * @return the rootClasses
+ */
+ public Map<String, RootClass> getRootClasses() {
+ return rootClasses;
+ }
+
+}
+
+class TypeVisitor extends ASTVisitor{
+
+ private String varName;
+
+ private Map<String, RootClass> rootClasses;
+
+ private RootClass rootClass;
+
+ private EntityInfo entityInfo;
+
+ private RefEntityInfo ref;
+
+ private Property prop;
+
+ TypeVisitor(Map<String, RootClass> rootClasses){
+ this.rootClasses = rootClasses;
+ }
+
+ public void init(String varName, EntityInfo entityInfo){
+ this.varName = varName;
+ this.entityInfo = entityInfo;
+ Map<String, RefEntityInfo> refs = entityInfo.getReferences();
+ ref = refs.get(varName);
+ prop = null;
+ rootClass = rootClasses.get(entityInfo.getFullyQualifiedName());
+ }
+
+ @Override
+ public boolean visit(ArrayType type) {
+ Array array = null;
+ Type componentType = type.getComponentType();
+ ITypeBinding tb = componentType.resolveBinding();
+ if (tb.isPrimitive()){
+ array = new PrimitiveArray(rootClass);
+
+ SimpleValue value = buildSimpleValue(tb.getName());
+ value.setTable(rootClass.getTable());
+ array.setElement(value);
+ array.setCollectionTable(rootClass.getTable());//TODO what to set?
+ } else {
+ RootClass associatedClass = rootClasses.get(tb.getBinaryName());
+ array = new Array(rootClass);
+ array.setElementClassName(tb.getBinaryName());
+ array.setCollectionTable(associatedClass.getTable());
+
+ OneToMany oValue = new OneToMany(rootClass);
+ oValue.setAssociatedClass(associatedClass);
+ oValue.setReferencedEntityName(tb.getBinaryName());
+
+ array.setElement(oValue);
+ }
+ if (array == null) return true;
+
+ SimpleValue key = new SimpleValue();
+ if (StringHelper.isNotEmpty(entityInfo.getPrimaryIdName())) {
+ key.addColumn(new Column(entityInfo.getPrimaryIdName().toUpperCase()));
+ }
+ array.setKey(key);
+ array.setFetchMode(FetchMode.SELECT);
+ SimpleValue index = new SimpleValue();
+
+ //add default index
+ //index.addColumn(new Column(varName.toUpperCase()+"_POSITION"));
+
+ array.setIndex(index);
+ buildProperty(array);
+ prop.setCascade("none");//$NON-NLS-1$
+ return false;//do not visit children
+ }
+
+ @Override
+ public boolean visit(ParameterizedType type) {
+ Assert.isNotNull(type, "Type object cannot be null");
+ Assert.isNotNull(entityInfo, "EntityInfo object cannot be null");
+ ITypeBinding tb = type.resolveBinding();
+ Assert.isNotNull(tb, "Type binding not resolved.");
+ rootClass = rootClasses.get(entityInfo.getFullyQualifiedName());
+ Assert.isNotNull(rootClass, "RootClass not found.");
+
+ Value value = null;
+ if (ref != null && rootClasses.get(ref.fullyQualifiedName) != null){
+ RootClass associatedClass = rootClasses.get(ref.fullyQualifiedName);
+ ITypeBinding[] interfaces = Utils.getAllInterfaces(tb);
+ value = buildCollectionValue(interfaces);
+ if (value != null) {
+ org.hibernate.mapping.Collection cValue = (org.hibernate.mapping.Collection)value;
+ OneToMany oValue = new OneToMany(rootClass);
+ oValue.setAssociatedClass(associatedClass);
+ oValue.setReferencedEntityName(ref.fullyQualifiedName);
+ //Set another table
+ cValue.setCollectionTable(associatedClass.getTable());
+
+ cValue.setElement(oValue);
+
+ if (value instanceof List){
+ ((IndexedCollection)cValue).setIndex(new SimpleValue());
+ } else if (value instanceof org.hibernate.mapping.Map){
+ SimpleValue map_key = new SimpleValue();
+ //FIXME: is it possible to map Map<SourceType, String>?
+ //Or only Map<String, SourceType>
+ map_key.setTypeName(tb.getTypeArguments()[0].getBinaryName());
+ ((IndexedCollection)cValue).setIndex(map_key);
+ }
+ }
+ }
+
+ if (value == null) {
+ value = buildSimpleValue(tb.getBinaryName());
+ }
+
+ buildProperty(value);
+ if (!(value instanceof SimpleValue)){
+ prop.setCascade("none");//$NON-NLS-1$
+ }
+ return false;//do not visit children
+ }
+
+ @Override
+ public boolean visit(PrimitiveType type) {
+ buildProperty(buildSimpleValue(type.getPrimitiveTypeCode().toString()));
+ return false;
+ }
+
+ @Override
+ public boolean visit(QualifiedType type) {
+ return super.visit(type);
+ }
+
+ @Override
+ public boolean visit(SimpleType type) {
+ ITypeBinding tb = type.resolveBinding();
+ Assert.isNotNull(tb);
+ ITypeBinding[] interfaces = Utils.getAllInterfaces(tb);
+ Value value = buildCollectionValue(interfaces);
+ if (value != null){
+ SimpleValue element = buildSimpleValue("string");//$NON-NLS-1$
+ ((org.hibernate.mapping.Collection) value).setElement(element);
+ buildProperty(value);
+ if (value instanceof List){
+ ((IndexedCollection)value).setIndex(new SimpleValue());
+ } else if (value instanceof org.hibernate.mapping.Map){
+ SimpleValue map_key = new SimpleValue();
+ //FIXME: how to detect key-type here
+ map_key.setTypeName("String");
+ ((IndexedCollection)value).setIndex(map_key);
+ }
+ prop.setCascade("none");//$NON-NLS-1$
+ } else if (ref != null){
+ ToOne sValue = null;
+ if (ref.refType == RefType.MANY2ONE){
+ sValue = new ManyToOne(rootClass.getTable());
+ } else if (ref.refType == RefType.ONE2ONE){
+ sValue = new OneToOne(rootClass.getTable(), rootClass);
+ } else if (ref.refType == RefType.UNDEF){
+ sValue = new OneToOne(rootClass.getTable(), rootClass);
+ } else {
+ //OneToMany and ManyToMany must be a collection
+ throw new IllegalStateException(ref.refType.toString());
+ }
+
+ Column column = new Column(varName.toUpperCase());
+ sValue.addColumn(column);
+ sValue.setTypeName(tb.getBinaryName());
+ sValue.setFetchMode(FetchMode.SELECT);
+ sValue.setReferencedEntityName(ref.fullyQualifiedName);
+ buildProperty(sValue);
+ prop.setCascade("none");//$NON-NLS-1$
+ } else {
+ value = buildSimpleValue(tb.getBinaryName());
+ buildProperty(value);
+ }
+ return super.visit(type);
+ }
+
+ @Override
+ public boolean visit(WildcardType type) {
+ return super.visit(type);
+ }
+
+ public Property getProperty(){
+ return prop;
+ }
+
+ protected void buildProperty(Value value){
+ prop = new Property();
+ prop.setName(varName);
+ prop.setValue(value);
+ }
+
+ private SimpleValue buildSimpleValue(String typeName){
+ SimpleValue sValue = new SimpleValue();
+ sValue.addColumn(new Column(varName.toUpperCase()));
+ sValue.setTypeName(typeName);
+ return sValue;
+ }
+
+ private org.hibernate.mapping.Collection buildCollectionValue(ITypeBinding[]
interfaces){
+ org.hibernate.mapping.Collection cValue = null;
+ if (Utils.isImplementInterface(interfaces, "java.util.Set")){//$NON-NLS-1$
+ cValue = new org.hibernate.mapping.Set(rootClass);
+ } else if (Utils.isImplementInterface(interfaces,
"java.util.List")){//$NON-NLS-1$
+ cValue = new org.hibernate.mapping.List(rootClass);
+ } else if (Utils.isImplementInterface(interfaces,
"java.util.Map")){//$NON-NLS-1$
+ cValue = new org.hibernate.mapping.Map(rootClass);
+ } else if (Utils.isImplementInterface(interfaces,
"java.util.Collection")){//$NON-NLS-1$
+ cValue = new org.hibernate.mapping.Bag(rootClass);
+ }
+
+ if (cValue == null) return null;
+
+ //By default set the same table, but for one-to many should change it to associated
class's table
+ cValue.setCollectionTable(rootClass.getTable());
+
+ SimpleValue key = new SimpleValue();
+ key.setTypeName("string");//$NON-NLS-1$
+ if (StringHelper.isNotEmpty(entityInfo.getPrimaryIdName())){
+ key.addColumn(new Column(entityInfo.getPrimaryIdName().toUpperCase()));
+ }
+ cValue.setKey(key);
+ cValue.setLazy(true);
+ cValue.setRole(StringHelper.qualify(rootClass.getEntityName(), varName));
+ return cValue;
+ }
+}
Property changes on:
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/ConfigurationActor.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Author Id Revision Date
Name: svn:eol-style
+ native
Added:
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/NewHibernateMappingFilePage.java
===================================================================
---
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/NewHibernateMappingFilePage.java
(rev 0)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/NewHibernateMappingFilePage.java 2009-05-04
12:08:45 UTC (rev 15000)
@@ -0,0 +1,260 @@
+/*******************************************************************************
+ * Copyright (c) 2007-2009 Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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
+ *
+ * Contributor:
+ * Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.hibernate.eclipse.jdt.ui.wizards;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.eclipse.jdt.core.IJavaProject;
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.CheckboxCellEditor;
+import org.eclipse.jface.viewers.ICellModifier;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TextCellEditor;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.ScrolledComposite;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.FillLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableColumn;
+import org.eclipse.swt.widgets.TableItem;
+import org.hibernate.console.ImageConstants;
+import org.hibernate.eclipse.console.HibernateConsoleMessages;
+import org.hibernate.eclipse.console.utils.EclipseImages;
+import org.hibernate.eclipse.jdt.ui.internal.jpa.common.EntityInfo;
+
+/**
+ * @author Dmitry Geraskov
+ *
+ */
+public class NewHibernateMappingFilePage extends WizardPage {
+
+ private TableViewer viewer;
+
+ private Map<IJavaProject, Collection<EntityInfo>> project_infos;
+
+ /**
+ * @param pageName
+ */
+ protected NewHibernateMappingFilePage(Map<IJavaProject,
Collection<EntityInfo>> project_infos) {
+ super("");
+ setTitle(HibernateConsoleMessages.NewHibernateMappingFilePage_hibernate_xml_mapping_file);
+ setDescription(HibernateConsoleMessages.NewHibernateMappingFilePage_this_wizard_creates);
+ this.project_infos = project_infos;
+ }
+
+ public void createControl(Composite parent) {
+
+ final ScrolledComposite sc = new ScrolledComposite(parent, SWT.H_SCROLL |
SWT.V_SCROLL);
+ sc.setExpandHorizontal(true);
+ sc.setExpandVertical(true);
+ sc.pack(false);
+
+ Composite container = new Composite(sc, SWT.NULL);
+ sc.setContent(container);
+
+ FillLayout layout = new FillLayout();
+ container.setLayout(layout);
+
+ Table table = new Table(container, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL |
SWT.V_SCROLL | SWT.FULL_SELECTION );
+ table.setHeaderVisible(true);
+ table.setLinesVisible(true);
+ table.pack(false);
+ createTableColumns(table);
+ viewer = createTableFilterViewer(table);
+ viewer.setInput(project_infos);
+
+ sc.setMinSize(container.computeSize(SWT.DEFAULT, SWT.DEFAULT));
+ setControl(sc);
+ }
+
+ private void createTableColumns(Table table){
+ int coulmnIndex = 0;
+ TableColumn column = new TableColumn(table, SWT.CENTER, coulmnIndex++);
+ column.setText("!");
+ column.setWidth(20);
+ column.setResizable(false);
+
+ if (project_infos.keySet().size() > 1){
+ column = new TableColumn(table, SWT.LEFT, coulmnIndex++);
+ column.setText("Project name");
+ column.setWidth(120);
+ }
+
+ column = new TableColumn(table, SWT.LEFT, coulmnIndex++);
+ column.setText("Class name");
+ column.setWidth(150);
+
+ column = new TableColumn(table, SWT.LEFT, coulmnIndex++);
+ column.setText("File name");
+ column.setWidth(150);
+ }
+
+ private TableViewer createTableFilterViewer(Table table) {
+ TableViewer result = new TableViewer( table );
+ result.setUseHashlookup( true );
+ if (project_infos.keySet().size() > 1){
+ result.setColumnProperties( new String[] {"create", "project",
//$NON-NLS-1$//$NON-NLS-2$
+ "class", "file",} ); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ result.setColumnProperties( new String[] {"create", //$NON-NLS-1$
+ "class", "file",} ); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+
+ CellEditor[] editors = new CellEditor[result.getColumnProperties().length];
+ editors[0] = new CheckboxCellEditor( result.getTable() );
+ editors[1] = new TextCellEditor( result.getTable() );
+ editors[2] = new TextCellEditor( result.getTable() );
+ if (project_infos.keySet().size() > 1){
+ editors[3] = new TextCellEditor( result.getTable() );
+ }
+
+ result.setCellEditors( editors );
+ result.setCellModifier( new TableCellModifier(result) );
+ result.setLabelProvider(new TableLableProvider(result));
+ result.setContentProvider( new TableContentProvider() );
+ return result;
+ }
+
+ private class TableLine {
+
+ public String projectName;
+
+ public String className;
+
+ public String fileName;
+
+ public Boolean isCreate = true;
+
+ public TableLine(String projectName, String className){
+ this(projectName, className, className + ".hbm.xml",true);
+ }
+
+ public TableLine(String projectName, String className, String fileName, boolean
isCreate){
+ this.projectName = projectName;
+ this.className = className;
+ this.fileName = fileName;
+ this.isCreate = isCreate;
+ }
+
+ }
+
+ private class TableContentProvider implements IStructuredContentProvider {
+
+ public Object[] getElements(Object inputElement) {
+ if (inputElement instanceof Map) {
+ List<TableLine> result = new ArrayList<TableLine>();
+ Map<IJavaProject, Collection<EntityInfo>> configs = (Map<IJavaProject,
Collection<EntityInfo>>)inputElement;
+ for (Entry<IJavaProject, Collection<EntityInfo>> entry :
configs.entrySet()) {
+ Iterator<EntityInfo> iter = entry.getValue().iterator();
+ while (iter.hasNext()) {
+ EntityInfo ei = iter.next();
+ result.add(new TableLine(entry.getKey().getProject().getName(), ei.getName()));
+ }
+ }
+ return result.toArray();
+ }
+ return new Object[0];
+ }
+
+ public void dispose() { }
+
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+
+ private class TableLableProvider extends LabelProvider implements ITableLabelProvider
{
+
+ private final TableViewer tv;
+
+ public TableLableProvider(TableViewer tv) {
+ this.tv = tv;
+ }
+
+ public Image getColumnImage(Object element, int columnIndex) {
+ String property = (String) tv.getColumnProperties()[columnIndex];
+ if("create".equals(property)) {
+ TableLine tl = (TableLine) element;
+ String key = tl.isCreate ? null : ImageConstants.CLOSE ; // TODO: find a better
image
+ return EclipseImages.getImage(key);
+ }
+ return null;
+ }
+
+ public String getColumnText(Object element, int columnIndex) {
+ String property = (String) tv.getColumnProperties()[columnIndex];
+ TableLine tl = (TableLine) element;
+
+ if ("class".equals(property)){
+ return tl.className;
+ } else if ("project".equals(property)){
+ return tl.projectName;
+ } else if ("file".equals(property)){
+ return tl.fileName;
+ } else return "";
+ }
+ }
+
+ private class TableCellModifier implements ICellModifier {
+
+ private final TableViewer tv;
+
+ public TableCellModifier(TableViewer tv) {
+ this.tv = tv;
+ }
+
+ public boolean canModify(Object element, String property) {
+ return false/*TODO "file".equals(property) ||
"create".equals(property)*/;
+ }
+
+ public Object getValue(Object element, String property) {
+ if ("class".equals(property)){
+ return ((TableLine)element).className;
+ } else if ("project".equals(property)){
+ return ((TableLine)element).projectName;
+ } else if ("file".equals(property)){
+ return ((TableLine)element).fileName;
+ } else if ("create".equals(property)){
+ return ((TableLine)element).isCreate;
+ }
+ return null;
+ }
+
+ public void modify(Object element, String property, Object value) {
+ TableLine tl = (TableLine)((TableItem)element).getData();
+ if ("class".equals(property)){
+ tl.className = (String)value;
+ } else if ("project".equals(property)){
+ tl.projectName = (String)value;
+ } else if ("file".equals(property)){
+ tl.fileName = (String)value;
+ } else if ("create".equals(property)){
+ tl.isCreate = (Boolean)value;
+ }
+
+ tv.update(new Object[] { tl }, new String[] { property });
+ }
+ }
+}
Property changes on:
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/NewHibernateMappingFilePage.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Author Id Revision Date
Name: svn:eol-style
+ native
Added:
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/NewHibernateMappingFileWizard.java
===================================================================
---
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/NewHibernateMappingFileWizard.java
(rev 0)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/NewHibernateMappingFileWizard.java 2009-05-04
12:08:45 UTC (rev 15000)
@@ -0,0 +1,302 @@
+/*******************************************************************************
+ * Copyright (c) 2007-2009 Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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
+ *
+ * Contributor:
+ * Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.hibernate.eclipse.jdt.ui.wizards;
+
+import java.lang.reflect.Field;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.Map.Entry;
+
+import org.eclipse.core.internal.filebuffers.SynchronizableDocument;
+import org.eclipse.core.internal.resources.File;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jdt.core.ICompilationUnit;
+import org.eclipse.jdt.core.IJavaElement;
+import org.eclipse.jdt.core.IJavaProject;
+import org.eclipse.jdt.core.IPackageFragmentRoot;
+import org.eclipse.jdt.core.JavaCore;
+import org.eclipse.jdt.core.JavaModelException;
+import org.eclipse.jdt.core.dom.AST;
+import org.eclipse.jdt.core.dom.ASTParser;
+import org.eclipse.jdt.core.dom.AbstractTypeDeclaration;
+import org.eclipse.jdt.core.dom.TypeDeclaration;
+import org.eclipse.jdt.internal.core.JavaElement;
+import org.eclipse.jdt.internal.core.JavaElementInfo;
+import org.eclipse.jdt.internal.core.JavaProject;
+import org.eclipse.jdt.internal.core.PackageFragment;
+import org.eclipse.jdt.internal.core.PackageFragmentRoot;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.TextSelection;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.TreeSelection;
+import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.ui.INewWizard;
+import org.eclipse.ui.IWorkbench;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.console.ImageConstants;
+import org.hibernate.eclipse.console.HibernateConsolePlugin;
+import org.hibernate.eclipse.console.utils.EclipseImages;
+import org.hibernate.eclipse.jdt.ui.internal.jpa.collect.AllEntitiesInfoCollector;
+import org.hibernate.eclipse.jdt.ui.internal.jpa.common.EntityInfo;
+import org.hibernate.eclipse.jdt.ui.internal.jpa.common.Utils;
+import org.hibernate.tool.hbm2x.HibernateMappingExporter;
+import org.hibernate.tool.hbm2x.HibernateMappingGlobalSettings;
+
+/**
+ * @author Dmitry Geraskov
+ *
+ */
+public class NewHibernateMappingFileWizard extends Wizard implements INewWizard {
+
+ /**
+ * Selected compilation units for startup processing,
+ * result of processing selection
+ */
+ private Set<ICompilationUnit> selectionCU = new
HashSet<ICompilationUnit>();
+
+ private Map<IJavaProject, Collection<EntityInfo>> project_infos = new
HashMap<IJavaProject, Collection<EntityInfo>>();
+
+
+ public NewHibernateMappingFileWizard(){
+ setDefaultPageImageDescriptor(EclipseImages.getImageDescriptor(ImageConstants.NEW_WIZARD)
);
+ }
+
+ @Override
+ public void addPages() {
+ super.addPages();
+ addPage(new NewHibernateMappingFilePage(project_infos));
+ }
+
+ public void init(IWorkbench workbench, IStructuredSelection selection) {
+ updateSelectedItems(selection);
+ initEntitiesInfo();
+ }
+
+ @Override
+ public boolean performFinish() {
+ Map<IJavaProject, Configuration> configs = createConfigurations();
+ for (Entry<IJavaProject, Configuration> entry : configs.entrySet()) {
+ Configuration config = entry.getValue();
+ HibernateMappingGlobalSettings hmgs = new HibernateMappingGlobalSettings();
+
+ IResource container;
+ try {
+ container = entry.getKey().getPackageFragmentRoots().length > 0
+ ? entry.getKey().getPackageFragmentRoots()[0].getResource()
+ : entry.getKey().getResource();
+
+ HibernateMappingExporter hce = new HibernateMappingExporter(config,
+ container.getLocation().toFile());
+
+ hce.setGlobalSettings(hmgs);
+ //hce.setForEach("entity");
+ //hce.setFilePattern(file.getName());
+ try {
+ hce.start();
+ } catch (Exception e){
+ e.getCause().printStackTrace();
+ }
+ container.refreshLocal(IResource.DEPTH_INFINITE, null);
+ } catch (JavaModelException e1) {
+ HibernateConsolePlugin.getDefault().log(e1);
+ } catch (CoreException e) {
+ HibernateConsolePlugin.getDefault().log(e);
+ }
+ }
+ return true;
+ }
+
+ protected void initEntitiesInfo(){
+ if (selectionCU.size() == 0) return;
+ AllEntitiesInfoCollector collector = new AllEntitiesInfoCollector();
+ Iterator<ICompilationUnit> it = selectionCU.iterator();
+
+ Map<IJavaProject, Set<ICompilationUnit>> mapJP_CUSet =
+ new HashMap<IJavaProject, Set<ICompilationUnit>>();
+ //separate by parent project
+ while (it.hasNext()) {
+ ICompilationUnit cu = it.next();
+ Set<ICompilationUnit> set = mapJP_CUSet.get(cu.getJavaProject());
+ if (set == null) {
+ set = new HashSet<ICompilationUnit>();
+ mapJP_CUSet.put(cu.getJavaProject(), set);
+ }
+ set.add(cu);
+ }
+ Iterator<Map.Entry<IJavaProject, Set<ICompilationUnit>>>
+ mapIt = mapJP_CUSet.entrySet().iterator();
+ while (mapIt.hasNext()) {
+ Map.Entry<IJavaProject, Set<ICompilationUnit>>
+ entry = mapIt.next();
+ IJavaProject javaProject = entry.getKey();
+ Iterator<ICompilationUnit> setIt = entry.getValue().iterator();
+ collector.initCollector(javaProject);
+ while (setIt.hasNext()) {
+ ICompilationUnit icu = setIt.next();
+ collector.collect(icu);
+ }
+ collector.resolveRelations();
+ //I don't check here if any non abstract class selected
+ project_infos.put(javaProject, collector.getMapCUs_Info().values());
+
+ }
+ }
+
+ private Map<IJavaProject, Configuration> createConfigurations() {
+ ConfigurationActor actor = new ConfigurationActor(selectionCU);
+ Map<IJavaProject, Configuration> configs = actor.createConfigurations();
+ return configs;
+ }
+
+ protected void updateSelectedItems(ISelection sel) {
+ if (sel instanceof TextSelection) {
+ String fullyQualifiedName = ""; //$NON-NLS-1$
+ IDocument fDocument = null;
+ SynchronizableDocument sDocument = null;
+ org.eclipse.jdt.core.dom.CompilationUnit resultCU = null;
+ Class clazz = sel.getClass();
+ Field fd = null;
+ try {
+ fd = clazz.getDeclaredField("fDocument"); //$NON-NLS-1$
+ } catch (NoSuchFieldException e) {
+ // just ignore it!
+ }
+ if (fd != null) {
+ try {
+ fd.setAccessible(true);
+ fDocument = (IDocument)fd.get(sel);
+ if (fDocument instanceof SynchronizableDocument) {
+ sDocument = (SynchronizableDocument)fDocument;
+ }
+ if (sDocument != null) {
+ ASTParser parser = ASTParser.newParser(AST.JLS3);
+ parser.setSource(sDocument.get().toCharArray());
+ parser.setResolveBindings(false);
+ resultCU = (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(null);
+ }
+ if (resultCU != null && resultCU.types().size() > 0 ) {
+ if (resultCU.getPackage() != null) {
+ fullyQualifiedName = resultCU.getPackage().getName().getFullyQualifiedName() +
"."; //$NON-NLS-1$
+ }
+ else {
+ fullyQualifiedName = ""; //$NON-NLS-1$
+ }
+ Object tmp = resultCU.types().get(0);
+ if (tmp instanceof AbstractTypeDeclaration) {
+ fullyQualifiedName += ((AbstractTypeDeclaration)tmp).getName();
+ }
+ if (!(tmp instanceof TypeDeclaration)) {
+ // ignore EnumDeclaration & AnnotationTypeDeclaration
+ fullyQualifiedName = ""; //$NON-NLS-1$
+ }
+ }
+ } catch (IllegalArgumentException e) {
+ HibernateConsolePlugin.getDefault().logErrorMessage("IllegalArgumentException:
", e); //$NON-NLS-1$
+ } catch (IllegalAccessException e) {
+ HibernateConsolePlugin.getDefault().logErrorMessage("IllegalAccessException:
", e); //$NON-NLS-1$
+ } catch (SecurityException e) {
+ HibernateConsolePlugin.getDefault().logErrorMessage("SecurityException: ",
e); //$NON-NLS-1$
+ }
+ }
+ if (fullyQualifiedName.length() > 0) {
+ ICompilationUnit cu = Utils.findCompilationUnit(fullyQualifiedName);
+ selectionCU.add(cu);
+ }
+ }
+ else if (sel instanceof TreeSelection) {
+ TreeSelection treeSelection = (TreeSelection)sel;
+ Iterator it = treeSelection.iterator();
+ while (it.hasNext()) {
+ Object obj = it.next();
+ processJavaElements(obj);
+ }
+ }
+ }
+
+ protected void processJavaElements(Object obj) {
+ if (obj instanceof ICompilationUnit) {
+ ICompilationUnit cu = (ICompilationUnit)obj;
+ selectionCU.add(cu);
+ }
+ else if (obj instanceof File) {
+ File file = (File)obj;
+ if (file != null && file.getProject() != null) {
+ IJavaProject javaProject = JavaCore.create(file.getProject());
+ ICompilationUnit[] cus = Utils.findCompilationUnits(javaProject,
+ file.getFullPath());
+ if (cus != null) {
+ for (int i = 0; i < cus.length; i++) {
+ selectionCU.add(cus[i]);
+ }
+ }
+ }
+ }
+ else if (obj instanceof JavaProject) {
+ JavaProject javaProject = (JavaProject)obj;
+ IPackageFragmentRoot[] pfr = null;
+ try {
+ pfr = javaProject.getAllPackageFragmentRoots();
+ } catch (JavaModelException e) {
+ // just ignore it!
+ //HibernateConsolePlugin.getDefault().logErrorMessage("JavaModelException:
", e); //$NON-NLS-1$
+ }
+ if (pfr != null) {
+ for (int i = 0; i < pfr.length; i++) {
+ processJavaElements(pfr[i]);
+ }
+ }
+ }
+ else if (obj instanceof PackageFragment) {
+ PackageFragment packageFragment = (PackageFragment)obj;
+ ICompilationUnit[] cus = null;
+ try {
+ cus = packageFragment.getCompilationUnits();
+ } catch (JavaModelException e) {
+ // just ignore it!
+ //HibernateConsolePlugin.getDefault().logErrorMessage("JavaModelException:
", e); //$NON-NLS-1$
+ }
+ if (cus != null) {
+ for (int i = 0; i < cus.length; i++) {
+ selectionCU.add(cus[i]);
+ }
+ }
+ }
+ else if (obj instanceof PackageFragmentRoot) {
+ PackageFragmentRoot packageFragmentRoot = (PackageFragmentRoot)obj;
+ JavaElement javaElement = (JavaElement)obj;
+ JavaElementInfo javaElementInfo = null;
+ try {
+ javaElementInfo = (JavaElementInfo)javaElement.getElementInfo();
+ } catch (JavaModelException e) {
+ // just ignore it!
+ //HibernateConsolePlugin.getDefault().logErrorMessage("JavaModelException:
", e); //$NON-NLS-1$
+ }
+ if (javaElementInfo != null) {
+ IJavaElement[] je = javaElementInfo.getChildren();
+ for (int i = 0; i < je.length; i++) {
+ processJavaElements(je[i]);
+ }
+ }
+ }
+ else if (obj instanceof JavaElement) {
+ JavaElement javaElement = (JavaElement)obj;
+ ICompilationUnit cu = javaElement.getCompilationUnit();
+ selectionCU.add(cu);
+ }
+ }
+
+}
Property changes on:
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/NewHibernateMappingFileWizard.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Author Id Revision Date
Name: svn:eol-style
+ native
Modified:
trunk/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/Customization.java
===================================================================
---
trunk/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/Customization.java 2009-05-04
10:06:51 UTC (rev 14999)
+++
trunk/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/Customization.java 2009-05-04
12:08:45 UTC (rev 15000)
@@ -25,7 +25,8 @@
/**
* packages name pattern
*/
- public static final String TEST_PACKS_PATTERN = ".*\\.bidi"; //$NON-NLS-1$
+ public static final String TEST_PACKS_PATTERN =
+ "mapping\\.((idclass))"; //$NON-NLS-1$
/**
* is stop after missing package or run further
Added:
trunk/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/HbmExportExceptionTest.java
===================================================================
---
trunk/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/HbmExportExceptionTest.java
(rev 0)
+++
trunk/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/HbmExportExceptionTest.java 2009-05-04
12:08:45 UTC (rev 15000)
@@ -0,0 +1,197 @@
+/*******************************************************************************
+ * Copyright (c) 2007-2008 Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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
+ *
+ * Contributor:
+ * Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.hibernate.eclipse.console.test.mappingproject;
+
+import java.io.File;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+
+import junit.framework.TestCase;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.jobs.Job;
+import org.eclipse.jdt.core.IPackageFragment;
+import org.eclipse.jdt.core.IPackageFragmentRoot;
+import org.eclipse.jdt.core.JavaModelException;
+import org.eclipse.jdt.internal.core.PackageFragmentRoot;
+import org.eclipse.osgi.util.NLS;
+import org.eclipse.swt.widgets.Display;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.console.ConsoleConfiguration;
+import org.hibernate.console.KnownConfigurations;
+import org.hibernate.console.execution.ExecutionContext;
+import org.hibernate.eclipse.console.test.ConsoleTestMessages;
+import org.hibernate.tool.hbm2x.ArtifactCollector;
+import org.hibernate.tool.hbm2x.ExporterException;
+import org.hibernate.tool.hbm2x.HibernateMappingExporter;
+import org.hibernate.tool.hbm2x.HibernateMappingGlobalSettings;
+
+/**
+ * @author Dmitry Geraskov
+ *
+ */
+public class HbmExportExceptionTest extends TestCase {
+
+ public void testHbmExportExceptionTest() throws Exception {
+ IPackageFragment pack = HibernateAllMappingTests.getActivePackage();
+ try{
+ KnownConfigurations knownConfigurations = KnownConfigurations.getInstance();
+ final ConsoleConfiguration consCFG =
knownConfigurations.find(ProjectUtil.ConsoleCFGName);
+ assertNotNull(consCFG);
+ consCFG.reset();
+ consCFG.build();
+ assertTrue(consCFG.hasConfiguration());
+ consCFG.execute( new ExecutionContext.Command() {
+
+ public Object execute() {
+ if(consCFG.hasConfiguration()) {
+ consCFG.getConfiguration().buildMappings();
+ }
+ return consCFG;
+ }
+ } );
+ Configuration config = consCFG.getConfiguration();
+
+ //delete old hbm files
+ assertNotNull( pack );
+ if (pack.getNonJavaResources().length > 0){
+ Object[] ress = pack.getNonJavaResources();
+ for (int i = 0; i < ress.length; i++) {
+ if (ress[i] instanceof IFile){
+ IFile res = (IFile)ress[i];
+ if (res.getName().endsWith(".hbm.xml")){ //$NON-NLS-1$
+ res.delete(true, false, null);
+ }
+ }
+ }
+ }
+
+ HibernateMappingGlobalSettings hmgs = new HibernateMappingGlobalSettings();
+
+
+ HibernateMappingExporter hce = new HibernateMappingExporter(config,
+ getSrcFolder());
+
+ hce.setGlobalSettings(hmgs);
+ try {
+ hce.start();
+ ArtifactCollector collector = hce.getArtifactCollector();
+ collector.formatFiles();
+
+ try {//build generated configuration
+ pack.getResource().refreshLocal(IResource.DEPTH_ONE, null);
+ waitForJobs();
+ ProjectUtil.customizeCFGFileForPack(pack);
+ assertNotNull(consCFG);
+ consCFG.reset();
+
+ consCFG.build();
+ assertTrue(consCFG.hasConfiguration());
+ consCFG.execute( new ExecutionContext.Command() {
+
+ public Object execute() {
+ if(consCFG.hasConfiguration()) {
+ consCFG.getConfiguration().buildMappings();
+ }
+ return consCFG;
+ }
+ } );
+ config = consCFG.getConfiguration();
+ } catch (CoreException e) {
+ String out =
NLS.bind(ConsoleTestMessages.UpdateConfigurationTest_error_customising_file_for_package,
+ new Object[] { ProjectUtil.CFG_FILE_NAME, pack.getPath(), e.getMessage() } );
+ fail(out);
+ }
+ } catch (ExporterException e){
+ throw (Exception)e.getCause();
+ }
+ } catch (Exception e){
+ String newMessage = "\nPackage " + pack.getElementName() + ":";
+ throw new WripperException(newMessage, e);
+ }
+ }
+
+ private File getSrcFolder() throws JavaModelException{
+ MappingTestProject mapProject = MappingTestProject.getTestProject();
+ PackageFragmentRoot packageFragmentRoot = null;
+ IPackageFragmentRoot[] roots =
mapProject.getIJavaProject().getAllPackageFragmentRoots();
+ for (int i = 0; i < roots.length; i++) {
+ if (roots[i].getClass() != PackageFragmentRoot.class) continue;
+ packageFragmentRoot = (PackageFragmentRoot) roots[i];
+ break;
+ }
+ assertNotNull(packageFragmentRoot);
+ return packageFragmentRoot.getResource().getLocation().toFile();
+ }
+
+ public void waitForJobs() {
+ long start = System.currentTimeMillis();
+ // Job.getJobManager().isIdle() is more efficient than EditorTestHelper.allJobsQuiet()
+ // EditorTestHelper.allJobsQuiet() isn't thread-safe
+ //
https://bugs.eclipse.org/bugs/show_bug.cgi?id=198241 is fixed
+ //while (!EditorTestHelper.allJobsQuiet()) {
+ while (!Job.getJobManager().isIdle()) {
+ delay(1000);
+ if ( (System.currentTimeMillis()-start) > MAX_IDLE )
+ throw new RuntimeException("A long running task detected"); //$NON-NLS-1$
+ }
+ }
+ private static final long MAX_IDLE = 30*60*1000L;
+
+ protected void delay(long waitTimeMillis) {
+ if (waitTimeMillis <= 0) return;
+ Display display = Display.getCurrent();
+
+ // If this is the UI thread,
+ // then process input.
+ if (display != null) {
+ long endTimeMillis = System.currentTimeMillis() + waitTimeMillis;
+ while (System.currentTimeMillis() < endTimeMillis) {
+ if (!display.readAndDispatch())
+ display.sleep();
+ }
+ display.update();
+ }
+
+ // Otherwise, perform a simple sleep.
+ else {
+ try {
+ Thread.sleep(waitTimeMillis);
+ } catch (InterruptedException e) {
+ // Ignored.
+ }
+ }
+ }
+}
+
+class WripperException extends Exception {
+
+ private String message;
+
+ public WripperException(String message, Exception cause){
+ super(cause);
+ this.message = message;
+ setStackTrace(cause.getStackTrace());
+ }
+
+ @Override
+ public Throwable getCause() {
+ return null;
+ }
+
+ @Override
+ public void printStackTrace(PrintWriter s) {
+ s.println(message);
+ super.getCause().printStackTrace(s);
+ }
+}
Property changes on:
trunk/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/HbmExportExceptionTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Author Id Revision Date
Name: svn:eol-style
+ native
Modified:
trunk/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/TestSet.java
===================================================================
---
trunk/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/TestSet.java 2009-05-04
10:06:51 UTC (rev 14999)
+++
trunk/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/TestSet.java 2009-05-04
12:08:45 UTC (rev 15000)
@@ -40,9 +40,10 @@
}
private static void addPackTests(TestSuite suite){
- suite.addTestSuite( OpenSourceFileTest.class );
+ /*suite.addTestSuite( OpenSourceFileTest.class );
suite.addTestSuite( OpenMappingFileTest.class );
- suite.addTestSuite( OpenMappingDiagramTest.class );
+ suite.addTestSuite( OpenMappingDiagramTest.class );*/
+ suite.addTestSuite( HbmExportExceptionTest.class );
}
private static void addTestsPackTearDown(TestSuite suite){
Added: trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/res/hbm/pack/A.java
===================================================================
--- trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/res/hbm/pack/A.java
(rev 0)
+++
trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/res/hbm/pack/A.java 2009-05-04
12:08:45 UTC (rev 15000)
@@ -0,0 +1,66 @@
+package pack;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class A {
+ private Integer id;
+ private B prop;
+ private B[] bs;
+ private List<B> list;
+ private Set<B> set;
+
+ private Map<String, B> mapValue;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public B getProp() {
+ return prop;
+ }
+
+ public void setProp(B b) {
+ this.prop = b;
+ }
+
+ public List<B> getList() {
+ return list;
+ }
+
+ public void setList(List<B> list) {
+ this.list = list;
+ }
+
+ public Set<B> getSet() {
+ return set;
+ }
+
+ public void setSet(Set<B> set) {
+ this.set = set;
+ }
+
+ public Map<String, B> getMapValue() {
+ return mapValue;
+ }
+
+ public void setMapValue(Map<String, B> mapValue) {
+ this.mapValue = mapValue;
+ }
+
+ public B[] getBs() {
+ return bs;
+ }
+
+ public void setBs(B[] bs) {
+ this.bs = bs;
+ }
+}
Property changes on:
trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/res/hbm/pack/A.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Author Id Revision Date
Name: svn:eol-style
+ native
Added: trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/res/hbm/pack/B.java
===================================================================
--- trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/res/hbm/pack/B.java
(rev 0)
+++
trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/res/hbm/pack/B.java 2009-05-04
12:08:45 UTC (rev 15000)
@@ -0,0 +1,25 @@
+package pack;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class B {
+ private Integer id;
+ private int[] testIntArray;
+
+ public int[] getTestIntArray() {
+ return testIntArray;
+ }
+
+ public void setTestIntArray(int[] testIntArray) {
+ this.testIntArray = testIntArray;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Property changes on:
trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/res/hbm/pack/B.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Author Id Revision Date
Name: svn:eol-style
+ native
Added:
trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/src/org/hibernate/eclipse/jdt/ui/test/hbmexporter/HbmExporterTest.java
===================================================================
---
trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/src/org/hibernate/eclipse/jdt/ui/test/hbmexporter/HbmExporterTest.java
(rev 0)
+++
trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/src/org/hibernate/eclipse/jdt/ui/test/hbmexporter/HbmExporterTest.java 2009-05-04
12:08:45 UTC (rev 15000)
@@ -0,0 +1,260 @@
+package org.hibernate.eclipse.jdt.ui.test.hbmexporter;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URL;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import junit.framework.TestCase;
+
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.FileLocator;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.jdt.core.ICompilationUnit;
+import org.eclipse.jdt.core.IJavaProject;
+import org.eclipse.jdt.core.IPackageFragmentRoot;
+import org.eclipse.jdt.core.JavaModelException;
+import org.eclipse.osgi.util.NLS;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.eclipse.console.test.ConsoleTestMessages;
+import org.hibernate.eclipse.console.test.mappingproject.TestUtilsCommon;
+import org.hibernate.eclipse.console.utils.ProjectUtils;
+import org.hibernate.eclipse.jdt.ui.internal.jpa.collect.AllEntitiesInfoCollector;
+import org.hibernate.eclipse.jdt.ui.internal.jpa.common.Utils;
+import org.hibernate.eclipse.jdt.ui.internal.jpa.process.AllEntitiesProcessor;
+import org.hibernate.eclipse.jdt.ui.test.HibernateJDTuiTestPlugin;
+import org.hibernate.eclipse.jdt.ui.wizards.ConfigurationActor;
+import org.hibernate.mapping.Array;
+import org.hibernate.mapping.ManyToOne;
+import org.hibernate.mapping.OneToMany;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.PrimitiveArray;
+import org.hibernate.mapping.Property;
+import org.hibernate.mapping.SimpleValue;
+import org.hibernate.mapping.Value;
+import org.hibernate.type.IntegerType;
+
+public class HbmExporterTest extends TestCase {
+
+ public static final String PROJECT_NAME = "TestProject"; //$NON-NLS-1$
+ public static final String RESOURCE_PATH =
"res/hbm/".replaceAll("//", File.separator); //$NON-NLS-1$
//$NON-NLS-2$
+ public static final String TESTRESOURCE_PATH = "testresources"; //$NON-NLS-1$
+
+ protected AllEntitiesInfoCollector collector = new AllEntitiesInfoCollector();
+ protected AllEntitiesProcessor processor = new AllEntitiesProcessor();
+
+ protected IProject project;
+ protected IJavaProject javaProject;
+
+ protected void setUp() throws Exception {
+ try {
+ createTestProject();
+ } catch (JavaModelException e1) {
+ fail(e1.getMessage());
+ } catch (CoreException e1) {
+ fail(e1.getMessage());
+ } catch (IOException e1) {
+ fail(e1.getMessage());
+ }
+ assertNotNull(project);
+ assertNotNull(javaProject);
+ assertNotNull(ProjectUtils.findJavaProject(PROJECT_NAME));
+ try {
+ javaProject.getProject().open(null);
+ } catch (CoreException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ /**
+ * Method returns Configuration object for selected ICompilationUnits.
+ * Fails if configuration is null.
+ * @return
+ */
+ protected Configuration getConfigurationFor(String... cuNames){
+ Set<ICompilationUnit> selectionCU = new HashSet();
+ for (int i = 0; i < cuNames.length; i++) {
+ ICompilationUnit icu = Utils.findCompilationUnit(javaProject,
+ cuNames[i]);
+ assertNotNull(icu);
+ selectionCU.add(icu);
+ }
+ ConfigurationActor actor = new ConfigurationActor(selectionCU);
+ Map<IJavaProject, Configuration> configurations = actor.createConfigurations();
+ assertEquals(1, configurations.size());
+ Configuration config = configurations.get(javaProject);
+ assertNotNull(config);
+ return config;
+ }
+
+ protected void checkClassesMaped(Configuration config, String... classesNames){
+ for (int i = 0; i < classesNames.length; i++) {
+ assertNotNull(config.getClassMapping(classesNames[i]));
+ }
+ }
+
+ public void testId(){
+ Configuration config = getConfigurationFor("pack.A");
+ checkClassesMaped(config, "A", "B");
+ PersistentClass a = config.getClassMapping("A");
+ PersistentClass b = config.getClassMapping("B");
+
+ Property aId= a.getIdentifierProperty();
+ Property bId= b.getIdentifierProperty();
+ assertNotNull(aId);
+ assertNotNull(bId);
+ assertEquals("id", aId.getName());
+ assertEquals("id", bId.getName());
+ }
+
+ public void testProperty(){
+ Configuration config = getConfigurationFor("pack.A");
+ checkClassesMaped(config, "A", "B");
+ PersistentClass a = config.getClassMapping("A");
+
+ Property prop = a.getProperty("prop");
+ Value value = prop.getValue();
+ assertNotNull(value);
+ assertTrue("Expected to get ManyToOne-type mapping", value.getClass()==
ManyToOne.class);
+ ManyToOne mto = (ManyToOne)value;
+ assertEquals("pack.B", mto.getTypeName());
+ }
+
+ public void testArray(){
+ Configuration config = getConfigurationFor("pack.A");
+ checkClassesMaped(config, "A", "B");
+ PersistentClass a = config.getClassMapping("A");
+ PersistentClass b = config.getClassMapping("B");
+
+ Property bs = a.getProperty("bs");
+ Value value = bs.getValue();
+ assertNotNull(value);
+ assertTrue("Expected to get Array-type mapping",
value.getClass()==Array.class);
+ Array ar = (Array)value;
+ assertEquals("pack.B", ar.getElementClassName());
+ assertTrue("Expected to get one-to-many array's element type",
+ ar.getElement().getClass() == OneToMany.class);
+
+ Property testIntArray = b.getProperty("testIntArray");
+ assertNotNull(testIntArray);
+ value = testIntArray.getValue();
+ assertNotNull(value);
+ assertTrue("Expected to get PrimitiveArray-type mapping",
+ value.getClass()==PrimitiveArray.class);
+ PrimitiveArray pAr = (PrimitiveArray) value;
+ assertNotNull(pAr.getElement());
+ assertTrue("Expected to get int-type primitive array",
pAr.getElement().getType().getClass()==IntegerType.class);
+ }
+
+ public void testList(){
+ Configuration config = getConfigurationFor("pack.A");
+ checkClassesMaped(config, "A", "B");
+ PersistentClass a = config.getClassMapping("A");
+ PersistentClass b = config.getClassMapping("B");
+
+ Property listProp = a.getProperty("list");
+ Value value = listProp.getValue();
+ assertNotNull(value);
+ assertTrue("Expected to get List-type mapping",
+ value.getClass()==org.hibernate.mapping.List.class);
+ org.hibernate.mapping.List list = (org.hibernate.mapping.List)value;
+ assertTrue(list.getElement() instanceof OneToMany);
+ assertTrue(list.getCollectionTable().equals(b.getTable()));
+ assertNotNull(list.getIndex());
+ assertNotNull(list.getKey());
+ }
+
+ public void testSet(){
+ Configuration config = getConfigurationFor("pack.A");
+ checkClassesMaped(config, "A", "B");
+ PersistentClass a = config.getClassMapping("A");
+ PersistentClass b = config.getClassMapping("B");
+
+ Property setProp = a.getProperty("set");
+ Value value = setProp.getValue();
+ assertNotNull(value);
+ assertTrue("Expected to get Set-type mapping",
+ value.getClass()==org.hibernate.mapping.Set.class);
+ org.hibernate.mapping.Set set = (org.hibernate.mapping.Set)value;
+ assertTrue(set.getElement() instanceof OneToMany);
+ assertTrue(set.getCollectionTable().equals(b.getTable()));
+ assertNotNull(set.getKey());
+ }
+
+ public void testMap(){
+ Configuration config = getConfigurationFor("pack.A");
+ checkClassesMaped(config, "A", "B");
+ PersistentClass a = config.getClassMapping("A");
+ PersistentClass b = config.getClassMapping("B");
+
+ Property mapValue = a.getProperty("mapValue");
+ Value value = mapValue.getValue();
+ assertNotNull(value);
+ assertTrue("Expected to get Map-type mapping",
+ value.getClass()==org.hibernate.mapping.Map.class);
+ org.hibernate.mapping.Map map = (org.hibernate.mapping.Map)value;
+ assertTrue(map.getElement() instanceof OneToMany);
+ assertTrue(map.getCollectionTable().equals(b.getTable()));
+ assertNotNull(map.getKey());
+ assertEquals("string", map.getKey().getType().getName());
+ }
+
+
+ protected void createTestProject() throws JavaModelException,
+ CoreException, IOException {
+ TestUtilsCommon commonUtil = new TestUtilsCommon();
+ project = commonUtil.buildNewProject(PROJECT_NAME);
+ javaProject = commonUtil.buildJavaProject(project);
+ File resourceFolder = getResourceItem(RESOURCE_PATH);
+ if (!resourceFolder.exists()) {
+ String out = NLS.bind(
+ ConsoleTestMessages.MappingTestProject_folder_not_found,
+ RESOURCE_PATH);
+ throw new RuntimeException(out);
+ }
+ IPackageFragmentRoot sourceFolder = commonUtil.createSourceFolder(
+ project, javaProject);
+ commonUtil.recursiveCopyFiles(resourceFolder, (IFolder) sourceFolder
+ .getResource());
+ File resourceFolderLib = getResourceItem(TESTRESOURCE_PATH);
+ if (!resourceFolderLib.exists()) {
+ String out = NLS.bind(
+ ConsoleTestMessages.MappingTestProject_folder_not_found,
+ RESOURCE_PATH);
+ throw new RuntimeException(out);
+ }
+ List<IPath> libs = commonUtil.copyLibs2(project, javaProject,
+ resourceFolderLib.getAbsolutePath());
+ commonUtil.generateClassPath(javaProject, libs, sourceFolder);
+ }
+
+ protected File getResourceItem(String strResPath) throws IOException {
+ IPath resourcePath = new Path(strResPath);
+ File resourceFolder = resourcePath.toFile();
+ URL entry = HibernateJDTuiTestPlugin.getDefault().getBundle().getEntry(
+ strResPath);
+ URL resProject = FileLocator.resolve(entry);
+ String tplPrjLcStr = FileLocator.resolve(resProject).getFile();
+ resourceFolder = new File(tplPrjLcStr);
+ return resourceFolder;
+ }
+
+ protected void tearDown() throws Exception {
+ try {
+ project.delete(true, true, null);
+ project = null;
+ javaProject = null;
+ } catch (CoreException e) {
+ fail(e.getMessage());
+ }
+ assertNull(project);
+ assertNull(javaProject);
+ }
+
+}
Property changes on:
trunk/hibernatetools/tests/org.hibernate.eclipse.jdt.ui.test/src/org/hibernate/eclipse/jdt/ui/test/hbmexporter/HbmExporterTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Author Id Revision Date
Name: svn:eol-style
+ native