Author: vyemialyanchyk
Date: 2009-05-22 11:59:07 -0400 (Fri, 22 May 2009)
New Revision: 15446
Added:
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/utils/OpenMappingUtils.java
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/utils/OpenMappingUtilsEjb3.java
Removed:
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/actions/OpenFileActionUtils.java
Modified:
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/actions/OpenMappingAction.java
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/utils/ProjectUtils.java
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/internal/CriteriaQuickAssistProcessor.java
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/internal/HQLQuickAssistProcessor.java
Log:
https://jira.jboss.org/jira/browse/JBIDE-4227 - "Open Mapping File" for
Hibernate JPA configuration
Deleted:
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/actions/OpenFileActionUtils.java
===================================================================
---
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/actions/OpenFileActionUtils.java 2009-05-22
15:09:10 UTC (rev 15445)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/actions/OpenFileActionUtils.java 2009-05-22
15:59:07 UTC (rev 15446)
@@ -1,713 +0,0 @@
-/*******************************************************************************
- * 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.console.actions;
-
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.dom4j.Attribute;
-import org.dom4j.Document;
-import org.dom4j.DocumentException;
-import org.dom4j.Element;
-import org.dom4j.VisitorSupport;
-import org.dom4j.io.SAXReader;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.internal.core.PackageFragmentRoot;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.FindReplaceDocumentAdapter;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.part.MultiPageEditorPart;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.hibernate.console.ConsoleConfiguration;
-import org.hibernate.eclipse.console.HibernateConsoleMessages;
-import org.hibernate.eclipse.console.HibernateConsolePlugin;
-import org.hibernate.mapping.PersistentClass;
-import org.hibernate.mapping.Property;
-import org.hibernate.mapping.RootClass;
-import org.hibernate.mapping.Subclass;
-import org.hibernate.mapping.Table;
-import org.hibernate.tool.hbm2x.Cfg2HbmTool;
-import org.hibernate.util.StringHelper;
-import org.hibernate.util.XMLHelper;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.InputSource;
-
-/**
- * Utility class for useful open mapping file action functions.
- *
- * @author Dmitry Geraskov
- * @author Vitali Yemialyanchyk
- */
-public class OpenFileActionUtils {
-
- public static final String HIBERNATE_TAG_CLASS = "class";
//$NON-NLS-1$
- public static final String HIBERNATE_TAG_TABLE = "table";
//$NON-NLS-1$
- public static final String HIBERNATE_TAG_SUBCLASS = "subclass";
//$NON-NLS-1$
- public static final String HIBERNATE_TAG_JOINED_SUBCLASS = "joined-subclass";
//$NON-NLS-1$
- public static final String HIBERNATE_TAG_UNION_SUBCLASS = "union-subclass";
//$NON-NLS-1$
- public static final String HIBERNATE_TAG_NAME = "name";
//$NON-NLS-1$
- public static final String HIBERNATE_TAG_ENTITY_NAME = "entity-name";
//$NON-NLS-1$
- public static final String HIBERNATE_TAG_SESSION_FACTORY = "session-factory";
//$NON-NLS-1$
- public static final String HIBERNATE_TAG_MAPPING = "mapping";
//$NON-NLS-1$
- public static final String HIBERNATE_TAG_RESOURCE = "resource";
//$NON-NLS-1$
- public static final String HIBERNATE_TAG_CATALOG = "catalog";
//$NON-NLS-1$
- public static final String HIBERNATE_TAG_SCHEMA = "schema";
//$NON-NLS-1$
- public static final String EJB_TAG_ENTITY = "entity";
//$NON-NLS-1$
- public static final String EJB_TAG_CLASS = "class";
//$NON-NLS-1$
-
- //prohibit constructor call
- private OpenFileActionUtils() {}
-
- /**
- * Get name of a persistent class.
- * @param rootClass
- * @return
- */
- public static String getPersistentClassName(PersistentClass rootClass) {
- if (rootClass == null) {
- return ""; //$NON-NLS-1$
- }
- return rootClass.getEntityName() != null ? rootClass.getEntityName() :
rootClass.getClassName();
- }
-
- /**
- * Formulate a full table name.
- * @param catalog
- * @param schema
- * @param name
- * @return
- */
- public static String getTableName(String catalog, String schema, String name) {
- return (catalog != null ? catalog + '.' : "") + (schema != null ?
schema + '.' : "") + name; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Get a full table name.
- * @param table
- * @return
- */
- public static String getTableName(Table table) {
- return getTableName(table.getCatalog(), table.getSchema(), table.getName());
- }
-
- /**
- * Check has consoleConfiguration config.xml file a mapping class for provided
rootClass.
- * @param consoleConfiguration
- * @param rootClass
- * @return
- */
- public static boolean hasConfigXMLMappingClassAnnotation(ConsoleConfiguration
consoleConfiguration, PersistentClass rootClass) {
- java.io.File configXMLFile = consoleConfiguration.getPreferences().getConfigXMLFile();
- if (configXMLFile == null) {
- return true;
- }
- EntityResolver entityResolver =
consoleConfiguration.getConfiguration().getEntityResolver();
- Document doc = getDocument(configXMLFile, entityResolver);
- return getElements(doc, HIBERNATE_TAG_MAPPING, HIBERNATE_TAG_CLASS,
getPersistentClassName(rootClass)).hasNext();
- }
-
- /**
- * Check has this particular element correspondence in the file.
- * @param consoleConfiguration
- * @param file
- * @param element
- * @return
- */
- public static boolean elementInFile(ConsoleConfiguration consoleConfiguration, IFile
file, Object element) {
- boolean res = false;
- if (element instanceof RootClass) {
- res = rootClassInFile(consoleConfiguration, file, (RootClass)element);
- } else if (element instanceof Subclass) {
- res = subclassInFile(consoleConfiguration, file, (Subclass)element);
- } else if (element instanceof Table) {
- res = tableInFile(consoleConfiguration, file, (Table)element);
- }
- return res;
- }
-
- private static String[][] classPairs = {
- { HIBERNATE_TAG_CLASS, HIBERNATE_TAG_NAME, },
- { HIBERNATE_TAG_CLASS, HIBERNATE_TAG_ENTITY_NAME, },
- { EJB_TAG_ENTITY, HIBERNATE_TAG_CLASS, },
- { EJB_TAG_ENTITY, HIBERNATE_TAG_NAME, },
- };
-
- /**
- * Check has this particular rootClass correspondence in the file.
- * @param consoleConfiguration
- * @param file
- * @param rootClass
- * @return
- */
- public static boolean rootClassInFile(ConsoleConfiguration consoleConfiguration, IFile
file, RootClass rootClass) {
- EntityResolver entityResolver =
consoleConfiguration.getConfiguration().getEntityResolver();
- Document doc = getDocument(file.getLocation().toFile(), entityResolver);
- final String clName = getPersistentClassName(rootClass);
- final String clNameUnq = StringHelper.unqualify(clName);
- boolean res = false;
- // TODO: getElements - this is *extremely* inefficient - no need to scan the whole tree
again and again.
- for (int i = 0; i < classPairs.length; i++) {
- res = getElements(doc, classPairs[i][0], classPairs[i][1], clNameUnq).hasNext();
- if (res) break;
- res = getElements(doc, classPairs[i][0], classPairs[i][1], clName).hasNext();
- if (res) break;
- }
- return res;
- }
-
- private static String[][] subClassPairs = {
- { HIBERNATE_TAG_SUBCLASS, HIBERNATE_TAG_NAME, },
- { HIBERNATE_TAG_SUBCLASS, HIBERNATE_TAG_ENTITY_NAME, },
- { HIBERNATE_TAG_JOINED_SUBCLASS, HIBERNATE_TAG_NAME, },
- { HIBERNATE_TAG_JOINED_SUBCLASS, HIBERNATE_TAG_ENTITY_NAME, },
- { HIBERNATE_TAG_UNION_SUBCLASS, HIBERNATE_TAG_NAME, },
- { HIBERNATE_TAG_UNION_SUBCLASS, HIBERNATE_TAG_ENTITY_NAME, },
- { EJB_TAG_ENTITY, HIBERNATE_TAG_CLASS, },
- { EJB_TAG_ENTITY, HIBERNATE_TAG_NAME, },
- };
-
- /**
- * Check has this particular subclass correspondence in the file.
- * @param consoleConfiguration
- * @param file
- * @param subclass
- * @return
- */
- public static boolean subclassInFile(ConsoleConfiguration consoleConfiguration, IFile
file, Subclass subclass) {
- EntityResolver entityResolver =
consoleConfiguration.getConfiguration().getEntityResolver();
- Document doc = getDocument(file.getLocation().toFile(), entityResolver);
- final String clName = getPersistentClassName(subclass);
- final String clNameUnq = StringHelper.unqualify(clName);
- boolean res = false;
- // TODO: getElements - this is *extremely* inefficient - no need to scan the whole tree
again and again.
- for (int i = 0; i < subClassPairs.length; i++) {
- res = getElements(doc, subClassPairs[i][0], subClassPairs[i][1],
clNameUnq).hasNext();
- if (res) break;
- res = getElements(doc, subClassPairs[i][0], subClassPairs[i][1], clName).hasNext();
- if (res) break;
- }
- return res;
- }
-
- /**
- * Check has this particular table correspondence in the file.
- * @param consoleConfiguration
- * @param file
- * @param table
- * @return
- */
- public static boolean tableInFile(ConsoleConfiguration consoleConfiguration, IFile file,
Table table) {
- EntityResolver entityResolver =
consoleConfiguration.getConfiguration().getEntityResolver();
- Document doc = getDocument(file.getLocation().toFile(), entityResolver);
- Iterator<Element> classes = getElements(doc, HIBERNATE_TAG_CLASS);
- boolean res = false;
- while (classes.hasNext()) {
- Element element = classes.next();
- Attribute tableAttr = element.attribute(HIBERNATE_TAG_TABLE);
- if (tableAttr != null) {
- Attribute catalogAttr = element.attribute(HIBERNATE_TAG_CATALOG);
- if (catalogAttr == null) {
- catalogAttr = doc.getRootElement().attribute(HIBERNATE_TAG_CATALOG);
- }
- Attribute schemaAttr = element.attribute(HIBERNATE_TAG_SCHEMA);
- if (schemaAttr == null) {
- schemaAttr = doc.getRootElement().attribute(HIBERNATE_TAG_SCHEMA);
- }
- String catalog = catalogAttr != null ? catalogAttr.getValue() : null;
- String schema = schemaAttr != null ? schemaAttr.getValue() : null;
- String name = tableAttr.getValue();
- if (getTableName(catalog, schema, name).equals(getTableName(table))) {
- res = true;
- break;
- }
- }
- Attribute classNameAttr = element.attribute(HIBERNATE_TAG_NAME);
- if (classNameAttr == null) {
- classNameAttr = element.attribute(HIBERNATE_TAG_ENTITY_NAME);
- }
- if (classNameAttr != null) {
- String physicalTableName =
consoleConfiguration.getConfiguration().getNamingStrategy().classToTableName(classNameAttr.getValue());
- if (table.getName().equals(physicalTableName)) {
- res = true;
- break;
- }
- }
- }
- if (!res && getElements(doc, HIBERNATE_TAG_TABLE, table.getName()).hasNext())
{
- res = true;
- }
- return res;
- }
-
- private static Iterator<Element> getElements(Document doc, String elementName) {
- return getElements(doc, elementName, null, null);
- }
-
- private static Iterator<Element> getElements(Document doc, String attrName, String
attrValue) {
- return getElements(doc, null, attrName, attrValue);
- }
-
- private static Iterator<Element> getElements(Document doc, String elementName,
String attrName, String attrValue) {
- LVS visitor = new LVS(elementName, attrName, attrValue);
- doc.accept(visitor);
- return visitor.iterator();
- }
-
- private static class LVS extends VisitorSupport {
- private String nodeName;
- private String attrName;
- private String attrValue;
- private List<Element> ret = new ArrayList<Element>();
-
- public LVS(String nodeName, String attrName, String attrValue) {
- super();
- this.nodeName = nodeName;
- this.attrName = attrName;
- this.attrValue = attrValue;
- }
-
- public void visit(Element element) {
- if (nodeName == null) {
- if (attrName != null && attrValue != null) {
- if (inspectAttributeForValue(element, attrName, attrValue)) {
- ret.add(element);
- }
- }
- } else {
- if (nodeName.equals(element.getName())) {
- if (attrName != null) {
- if (inspectAttributeForValue(element, attrName, attrValue)) {
- ret.add(element);
- }
- } else {
- ret.add(element);
- }
- }
- }
- }
-
- public Iterator<Element> iterator() {
- return ret.iterator();
- }
-
- protected boolean inspectAttributeForValue(Element element, String attrName, String
checkValue) {
- Attribute attr = element.attribute(attrName);
- if (attr != null && checkValue.equals(attr.getValue())) {
- return checkValue.equals(attr.getValue());
- }
- return false;
- }
- }
-
- /**
- * Trying to find hibernate console config mapping file,
- * which is corresponding to provided element.
- *
- * @param configXMLFile
- * @param entityResolver
- * @return
- */
- public static Document getDocument(java.io.File configXMLFile, EntityResolver
entityResolver) {
- Document doc = null;
- if (configXMLFile == null) {
- return doc;
- }
- InputStream stream = null;
- try {
- stream = new FileInputStream(configXMLFile);
- } catch (FileNotFoundException e) {
- HibernateConsolePlugin.getDefault().logErrorMessage("Configuration file not
found", e); //$NON-NLS-1$
- }
- try {
- List<Throwable> errors = new ArrayList<Throwable>();
- XMLHelper helper = new XMLHelper();
- SAXReader saxReader = helper.createSAXReader(configXMLFile.getPath(), errors,
entityResolver);
- doc = saxReader.read(new InputSource( stream));
- if (errors.size() != 0) {
- HibernateConsolePlugin.getDefault().logErrorMessage("invalid
configuration", (Throwable)null); //$NON-NLS-1$
- }
- }
- catch (DocumentException e) {
- HibernateConsolePlugin.getDefault().logErrorMessage("Could not parse
configuration", e); //$NON-NLS-1$
- }
- finally {
- try {
- if (stream != null) stream.close();
- }
- catch (IOException ioe) {
- HibernateConsolePlugin.getDefault().logErrorMessage("could not close input
stream for", ioe); //$NON-NLS-1$
- }
- }
- return doc;
- }
-
- /**
- * Trying to find hibernate console config mapping file,
- * which is corresponding to provided element.
- *
- * @param consoleConfiguration
- * @param proj
- * @param element
- * @return
- */
- @SuppressWarnings("unchecked")
- public static IFile searchInMappingFiles(ConsoleConfiguration consoleConfiguration,
IJavaProject proj, Object element) {
- IFile file = null;
- if (consoleConfiguration == null || proj == null) {
- return file;
- }
- java.io.File configXMLFile = consoleConfiguration.getPreferences().getConfigXMLFile();
- EntityResolver entityResolver =
consoleConfiguration.getConfiguration().getEntityResolver();
- Document doc = getDocument(configXMLFile, entityResolver);
- if (doc == null) {
- return file;
- }
- Element sfNode = doc.getRootElement().element(HIBERNATE_TAG_SESSION_FACTORY);
- Iterator<Element> elements = sfNode.elements(HIBERNATE_TAG_MAPPING).iterator();
- while (elements.hasNext() && file == null) {
- Element subelement = elements.next();
- Attribute resourceAttr = subelement.attribute(HIBERNATE_TAG_RESOURCE);
- if (resourceAttr == null) {
- continue;
- }
- IPackageFragmentRoot[] packageFragmentRoots = new IPackageFragmentRoot[0];
- try {
- packageFragmentRoots = proj.getAllPackageFragmentRoots();
- } catch (JavaModelException e) {
- HibernateConsolePlugin.getDefault().logErrorMessage(HibernateConsoleMessages.OpenFileActionUtils_problems_while_get_project_package_fragment_roots,
e);
- }
- for (int i = 0; i < packageFragmentRoots.length; i++) {
- //search in source folders.
- if (packageFragmentRoots[i].getClass() != PackageFragmentRoot.class) {
- continue;
- }
- IPackageFragmentRoot packageFragmentRoot = packageFragmentRoots[i];
- IPath path = packageFragmentRoot.getPath().append(resourceAttr.getValue());
- file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
- if (file == null) {
- continue;
- }
- if (file.exists() && elementInFile(consoleConfiguration, file, element)) {
- break;
- }
- file = null;
- }
- }
- return file;
- }
-
- /**
- * Trying to find console configuration additional mapping file,
- * which is corresponding to provided element.
- *
- * @param consoleConfiguration
- * @param element
- * @return
- */
- public static IFile searchInAdditionalMappingFiles(ConsoleConfiguration
consoleConfiguration, Object element) {
- IFile file = null;
- if (consoleConfiguration == null) {
- return file;
- }
- java.io.File[] files = consoleConfiguration.getPreferences().getMappingFiles();
- for (int i = 0; i < files.length; i++) {
- java.io.File fileTmp = files[i];
- if (fileTmp == null) {
- continue;
- }
- file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(new
Path(fileTmp.getPath()));
- if (file == null) {
- continue;
- }
- if (file.exists() && elementInFile(consoleConfiguration, file, element)) {
- break;
- }
- file = null;
- }
- return file;
- }
-
- /**
- * This function is trying to find hibernate console config file,
- * which is corresponding to provided element.
- *
- * @param consoleConfiguration
- * @param proj
- * @param element
- * @return
- */
- public static IFile searchFileToOpen(ConsoleConfiguration consoleConfiguration,
IJavaProject proj, Object element) {
- IFile file = searchInMappingFiles(consoleConfiguration, proj, element);
- if (file == null) {
- file = searchInAdditionalMappingFiles(consoleConfiguration, element);
- }
- //if (file == null) {
- // file = searchInEjb3MappingFiles(consoleConfiguration, proj, element);
- //}
- return file;
- }
-
- /**
- * Creates FindReplaceDocumentAdapter for provided text editor.
- *
- * @param textEditor
- * @return
- */
- public static FindReplaceDocumentAdapter createFindDocAdapter(ITextEditor textEditor) {
- IDocument document = null;
- if (textEditor.getDocumentProvider() != null){
- document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
- }
- if (document == null) {
- return null;
- }
- return new FindReplaceDocumentAdapter(document);
- }
-
- /**
- * Opens an editor on the given file resource.
- * @param file the editor input
- * @return an open editor or <code>null</code> if an external editor was
opened
- * @exception PartInitException if the editor could not be initialized
- */
- public static IEditorPart openFileInEditor(IFile file) throws PartInitException {
- IWorkbenchPage page =
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- return IDE.openEditor(page, file);
- }
-
- /**
- * Finds a document region, which corresponds of given selection object.
- * @param findAdapter
- * @param selection
- * @return a proper document region
- */
- public static IRegion findSelectRegion(FindReplaceDocumentAdapter findAdapter, Object
selection) {
- IRegion selectRegion = null;
- if (selection instanceof RootClass || selection instanceof Subclass) {
- selectRegion = findSelectRegion(findAdapter, (PersistentClass)selection);
- } else if (selection instanceof Property){
- selectRegion = findSelectRegion(findAdapter, (Property)selection);
- }
- return selectRegion;
- }
-
- /**
- * Finds a document region, which corresponds of given property.
- * @param findAdapter
- * @param property
- * @return a proper document region
- */
- public static IRegion findSelectRegion(FindReplaceDocumentAdapter findAdapter, Property
property) {
- Assert.isNotNull(property.getPersistentClass());
- IRegion classRegion = findSelectRegion(findAdapter, property.getPersistentClass());
- if (classRegion == null) {
- return null;
- }
- final Cfg2HbmTool tool = new Cfg2HbmTool();
- final String tagName = tool.getTag(property.getPersistentClass());
- IRegion finalRegion = null;
- IRegion propRegion = null;
- int startOffset = classRegion.getOffset() + classRegion.getLength();
- try {
- String tagClose = "</" + tagName; //$NON-NLS-1$
- finalRegion = findAdapter.find(startOffset, tagClose, true, true, false, false);
- if (finalRegion == null) {
- tagClose = "</" + EJB_TAG_ENTITY; //$NON-NLS-1$
- finalRegion = findAdapter.find(startOffset, tagClose, true, true, false, false);
- }
- propRegion = findAdapter.find(startOffset, generateHbmPropertyPattern(property), true,
true, false, true);
- if (propRegion == null) {
- propRegion = findAdapter.find(startOffset, generateEjbPropertyPattern(property),
true, true, false, true);
- }
- } catch (BadLocationException e) {
- //ignore
- }
- IRegion res = null;
- if (propRegion != null) {
- int length = property.getName().length();
- int offset = propRegion.getOffset() + propRegion.getLength() - length - 1;
- res = new Region(offset, length);
- if (finalRegion != null && propRegion.getOffset() >
finalRegion.getOffset()) {
- res = null;
- }
- }
- return res;
- }
-
- /**
- * Finds a document region, which corresponds of given persistent class.
- * @param findAdapter
- * @param persistentClass
- * @return a proper document region
- */
- public static IRegion findSelectRegion(FindReplaceDocumentAdapter findAdapter,
PersistentClass persistentClass) {
- IRegion res = null;
- String[] classPatterns = generatePersistentClassPatterns(persistentClass);
- IRegion classRegion = null;
- try {
- for (int i = 0; (classRegion == null) && (i < classPatterns.length); i++){
- classRegion = findAdapter.find(0, classPatterns[i], true, true, false, true);
- }
- } catch (BadLocationException e) {
- //ignore
- }
- if (classRegion != null) {
- int length = persistentClass.getNodeName().length();
- int offset = classRegion.getOffset() + classRegion.getLength() - length - 1;
- res = new Region(offset, length);
- }
- return res;
- }
-
- /**
- * Creates a xml tag search pattern with given tag name which should contains
- * proper name-value pair.
- *
- * @param tagName
- * @param name
- * @param value
- * @return a result search pattern
- */
- public static String createPattern(String tagName, String name, String value) {
- StringBuffer pattern = new StringBuffer("<"); //$NON-NLS-1$
- pattern.append(tagName);
- pattern.append("[\\s]+[.[^>]]*"); //$NON-NLS-1$
- pattern.append(name);
- pattern.append("[\\s]*=[\\s]*\""); //$NON-NLS-1$
- pattern.append(value);
- pattern.append('\"');
- return pattern.toString();
- }
-
- private static String[][] persistentClassPairs = {
- { HIBERNATE_TAG_CLASS, HIBERNATE_TAG_NAME, },
- { HIBERNATE_TAG_CLASS, HIBERNATE_TAG_ENTITY_NAME, },
- { EJB_TAG_ENTITY, HIBERNATE_TAG_NAME, },
- { EJB_TAG_ENTITY, EJB_TAG_CLASS, },
- };
-
- /**
- * Generates a persistent class xml tag search patterns.
- *
- * @param persClass
- * @return an arrays of search patterns
- */
- public static String[] generatePersistentClassPatterns(PersistentClass persClass){
- String fullClassName = null;
- String shortClassName = null;
- if (persClass.getEntityName() != null){
- fullClassName = persClass.getEntityName();
- } else {
- fullClassName = persClass.getClassName();
- }
- shortClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);
- final Cfg2HbmTool tool = new Cfg2HbmTool();
- final String tagName = tool.getTag(persClass);
- persistentClassPairs[0][0] = tagName;
- persistentClassPairs[1][0] = tagName;
- List<String> patterns = new ArrayList<String>();
- for (int i = 0; i < persistentClassPairs.length; i++) {
- patterns.add(createPattern(persistentClassPairs[i][0], persistentClassPairs[i][1],
shortClassName));
- patterns.add(createPattern(persistentClassPairs[i][0], persistentClassPairs[i][1],
fullClassName));
- }
- return patterns.toArray(new String[0]);
- }
-
- /**
- * Generates a property xml tag search pattern, which corresponds hibernate hbm syntax.
- *
- * @param property
- * @return a search patterns
- */
- public static String generateHbmPropertyPattern(Property property) {
- final Cfg2HbmTool tool = new Cfg2HbmTool();
- String toolTag = ""; //$NON-NLS-1$
- PersistentClass pc = property.getPersistentClass();
- if (pc != null && pc.getIdentifierProperty() == property) {
- if (property.isComposite()) {
- toolTag = "composite-id"; //$NON-NLS-1$
- } else {
- toolTag = "id"; //$NON-NLS-1$
- }
- } else {
- toolTag = tool.getTag(property);
- if ("component".equals(toolTag) &&
"embedded".equals(property.getPropertyAccessorName())) {
//$NON-NLS-1$//$NON-NLS-2$
- toolTag = "properties"; //$NON-NLS-1$
- }
- }
- return createPattern(toolTag, HIBERNATE_TAG_NAME, property.getName());
- }
-
- /**
- * Generates a property xml tag search pattern, which corresponds ejb3 syntax.
- *
- * @param property
- * @return a search patterns
- */
- public static String generateEjbPropertyPattern(Property property) {
- String toolTag = ""; //$NON-NLS-1$
- PersistentClass pc = property.getPersistentClass();
- if (pc != null && pc.getIdentifierProperty() == property) {
- if (property.isComposite()) {
- toolTag = "composite-id"; //$NON-NLS-1$
- } else {
- toolTag = "id"; //$NON-NLS-1$
- }
- } else {
- toolTag = "basic"; //$NON-NLS-1$
- }
- return createPattern(toolTag, HIBERNATE_TAG_NAME, property.getName());
- }
-
- /**
- * Method gets all ITextEditors from IEditorPart. Shouldn't returns null value.
- *
- * @param editorPart
- * @return
- */
- public static ITextEditor[] getTextEditors(IEditorPart editorPart) {
- // if EditorPart is MultiPageEditorPart then get ITextEditor from it.
- ITextEditor[] res = new ITextEditor[0];
- if (editorPart instanceof MultiPageEditorPart) {
- List<ITextEditor> testEditors = new ArrayList<ITextEditor>();
- IEditorPart[] editors =
((MultiPageEditorPart)editorPart).findEditors(editorPart.getEditorInput());
- for (int i = 0; i < editors.length; i++) {
- if (editors[i] instanceof ITextEditor){
- testEditors.add((ITextEditor)editors[i]);
- }
- }
- res = testEditors.toArray(res);
- } else if (editorPart instanceof ITextEditor){
- res = new ITextEditor[]{(ITextEditor) editorPart};
- }
- return res;
- }
-}
Modified:
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/actions/OpenMappingAction.java
===================================================================
---
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/actions/OpenMappingAction.java 2009-05-22
15:09:10 UTC (rev 15445)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/actions/OpenMappingAction.java 2009-05-22
15:59:07 UTC (rev 15446)
@@ -30,6 +30,7 @@
import org.hibernate.console.ConsoleConfiguration;
import org.hibernate.eclipse.console.HibernateConsoleMessages;
import org.hibernate.eclipse.console.HibernateConsolePlugin;
+import org.hibernate.eclipse.console.utils.OpenMappingUtils;
import org.hibernate.eclipse.console.utils.ProjectUtils;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.PersistentClass;
@@ -74,6 +75,14 @@
}
}
+ /**
+ * @param path
+ * @param consoleConfiguration
+ * @return
+ * @throws PartInitException
+ * @throws JavaModelException
+ * @throws FileNotFoundException
+ */
public static IEditorPart run(TreePath path, ConsoleConfiguration consoleConfiguration)
throws PartInitException, JavaModelException, FileNotFoundException {
boolean isPropertySel = (path.getLastSegment().getClass() == Property.class);
if (isPropertySel) {
@@ -105,17 +114,17 @@
Property p = (Property)selection;
if (p.getPersistentClass() != null) {
//use PersistentClass to open editor
- file = OpenFileActionUtils.searchFileToOpen(consoleConfiguration, proj,
p.getPersistentClass());
+ file = OpenMappingUtils.searchFileToOpen(consoleConfiguration, proj,
p.getPersistentClass());
//editorPart = openMapping(p.getPersistentClass(), consoleConfiguration);
}
}
else {
- file = OpenFileActionUtils.searchFileToOpen(consoleConfiguration, proj, selection);
+ file = OpenMappingUtils.searchFileToOpen(consoleConfiguration, proj, selection);
//editorPart = openMapping(selection, consoleConfiguration);
}
if (file != null) {
- editorPart = OpenFileActionUtils.openFileInEditor(file);
- updateEditorSelection(editorPart, selection);
+ editorPart = OpenMappingUtils.openFileInEditor(file);
+ updateEditorSelection(proj, editorPart, selection);
}
if (editorPart == null) {
//try to find hibernate-annotations
@@ -130,7 +139,7 @@
}
}
if (rootClass != null){
- if (OpenFileActionUtils.hasConfigXMLMappingClassAnnotation(consoleConfiguration,
rootClass)) {
+ if (OpenMappingUtils.hasConfigXMLMappingClassAnnotation(consoleConfiguration,
rootClass)) {
String fullyQualifiedName = rootClass.getClassName();
editorPart = OpenSourceAction.run(selection, proj, fullyQualifiedName);
}
@@ -155,14 +164,14 @@
public static IEditorPart run(Property compositeProperty, Property parentProperty,
ConsoleConfiguration consoleConfiguration) throws PartInitException, JavaModelException,
FileNotFoundException{
PersistentClass rootClass = parentProperty.getPersistentClass();
IJavaProject proj = ProjectUtils.findJavaProject(consoleConfiguration);
- IFile file = OpenFileActionUtils.searchFileToOpen(consoleConfiguration, proj,
rootClass);
+ IFile file = OpenMappingUtils.searchFileToOpen(consoleConfiguration, proj, rootClass);
IEditorPart editorPart = null;
if (file != null){
- editorPart = OpenFileActionUtils.openFileInEditor(file);
- updateEditorSelection(editorPart, compositeProperty, parentProperty);
+ editorPart = OpenMappingUtils.openFileInEditor(file);
+ updateEditorSelection(proj, editorPart, compositeProperty, parentProperty);
}
if (editorPart == null && parentProperty.isComposite()) {
- if (OpenFileActionUtils.hasConfigXMLMappingClassAnnotation(consoleConfiguration,
rootClass)) {
+ if (OpenMappingUtils.hasConfigXMLMappingClassAnnotation(consoleConfiguration,
rootClass)) {
String fullyQualifiedName
=((Component)parentProperty.getValue()).getComponentClassName();
editorPart = OpenSourceAction.run(compositeProperty, proj, fullyQualifiedName);
}
@@ -178,8 +187,8 @@
* @param editorPart
* @param selection
*/
- public static boolean updateEditorSelection(IEditorPart editorPart, Object selection) {
- ITextEditor[] textEditors = OpenFileActionUtils.getTextEditors(editorPart);
+ public static boolean updateEditorSelection(IJavaProject proj, IEditorPart editorPart,
Object selection) {
+ ITextEditor[] textEditors = OpenMappingUtils.getTextEditors(editorPart);
if (textEditors.length == 0) {
return false;
}
@@ -188,12 +197,12 @@
ITextEditor textEditor = null;
for (int i = 0; i < textEditors.length && findAdapter == null; i++) {
textEditor = textEditors[i];
- findAdapter = OpenFileActionUtils.createFindDocAdapter(textEditor);
+ findAdapter = OpenMappingUtils.createFindDocAdapter(textEditor);
}
if (findAdapter == null) {
return false;
}
- IRegion selectRegion = OpenFileActionUtils.findSelectRegion(findAdapter, selection);
+ IRegion selectRegion = OpenMappingUtils.findSelectRegion(proj, findAdapter,
selection);
if (selectRegion != null) {
textEditor.selectAndReveal(selectRegion.getOffset(), selectRegion.getLength());
return true;
@@ -206,8 +215,8 @@
* @param compositeProperty
* @param parentProperty
*/
- public static boolean updateEditorSelection(IEditorPart editorPart, Property
compositeProperty, Property parentProperty) {
- ITextEditor[] textEditors = OpenFileActionUtils.getTextEditors(editorPart);
+ public static boolean updateEditorSelection(IJavaProject proj, IEditorPart editorPart,
Property compositeProperty, Property parentProperty) {
+ ITextEditor[] textEditors = OpenMappingUtils.getTextEditors(editorPart);
if (textEditors.length == 0) {
return false;
}
@@ -216,19 +225,19 @@
ITextEditor textEditor = null;
for (int i = 0; i < textEditors.length && findAdapter == null; i++) {
textEditor = textEditors[i];
- findAdapter = OpenFileActionUtils.createFindDocAdapter(textEditor);
+ findAdapter = OpenMappingUtils.createFindDocAdapter(textEditor);
}
if (findAdapter == null) {
return false;
}
- IRegion parentRegion = OpenFileActionUtils.findSelectRegion(findAdapter,
parentProperty);
+ IRegion parentRegion = OpenMappingUtils.findSelectRegion(proj, findAdapter,
parentProperty);
if (parentRegion == null) {
return false;
}
int startOffset = parentRegion.getOffset() + parentRegion.getLength();
IRegion propRegion = null;
try {
- final String hbmPropertyPattern =
OpenFileActionUtils.generateHbmPropertyPattern(compositeProperty);
+ final String hbmPropertyPattern =
OpenMappingUtils.generateHbmPropertyPattern(compositeProperty);
propRegion = findAdapter.find(startOffset, hbmPropertyPattern, true, true, false,
true);
PersistentClass rootClass = parentProperty.getPersistentClass();
if (propRegion == null && parentProperty.isComposite()
Copied:
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/utils/OpenMappingUtils.java
(from rev 15390,
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/actions/OpenFileActionUtils.java)
===================================================================
---
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/utils/OpenMappingUtils.java
(rev 0)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/utils/OpenMappingUtils.java 2009-05-22
15:59:07 UTC (rev 15446)
@@ -0,0 +1,901 @@
+/*******************************************************************************
+ * 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.console.utils;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.dom4j.Attribute;
+import org.dom4j.Document;
+import org.dom4j.DocumentException;
+import org.dom4j.Element;
+import org.dom4j.VisitorSupport;
+import org.dom4j.io.SAXReader;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.Assert;
+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.IType;
+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.ITypeBinding;
+import org.eclipse.jdt.core.dom.Type;
+import org.eclipse.jdt.core.dom.TypeDeclaration;
+import org.eclipse.jdt.internal.core.JarPackageFragmentRoot;
+import org.eclipse.jdt.internal.core.PackageFragmentRoot;
+import org.eclipse.jdt.internal.core.SourceType;
+import org.eclipse.jface.text.BadLocationException;
+import org.eclipse.jface.text.FindReplaceDocumentAdapter;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.Region;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.ide.IDE;
+import org.eclipse.ui.part.MultiPageEditorPart;
+import org.eclipse.ui.texteditor.ITextEditor;
+import org.hibernate.console.ConsoleConfiguration;
+import org.hibernate.console.execution.ExecutionContext;
+import org.hibernate.eclipse.console.HibernateConsoleMessages;
+import org.hibernate.eclipse.console.HibernateConsolePlugin;
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.Component;
+import org.hibernate.mapping.ManyToOne;
+import org.hibernate.mapping.Map;
+import org.hibernate.mapping.OneToMany;
+import org.hibernate.mapping.OneToOne;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Property;
+import org.hibernate.mapping.RootClass;
+import org.hibernate.mapping.Subclass;
+import org.hibernate.mapping.Table;
+import org.hibernate.mapping.ToOne;
+import org.hibernate.mapping.Value;
+import org.hibernate.tool.hbm2x.Cfg2HbmTool;
+import org.hibernate.util.StringHelper;
+import org.hibernate.util.XMLHelper;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.InputSource;
+
+/**
+ * Utility class for useful open mapping file action functions.
+ *
+ * @author Dmitry Geraskov
+ * @author Vitali Yemialyanchyk
+ */
+public class OpenMappingUtils {
+
+ public static final String HIBERNATE_TAG_CLASS = "class";
//$NON-NLS-1$
+ public static final String HIBERNATE_TAG_TABLE = "table";
//$NON-NLS-1$
+ public static final String HIBERNATE_TAG_SUBCLASS = "subclass";
//$NON-NLS-1$
+ public static final String HIBERNATE_TAG_JOINED_SUBCLASS = "joined-subclass";
//$NON-NLS-1$
+ public static final String HIBERNATE_TAG_UNION_SUBCLASS = "union-subclass";
//$NON-NLS-1$
+ public static final String HIBERNATE_TAG_NAME = "name";
//$NON-NLS-1$
+ public static final String HIBERNATE_TAG_ENTITY_NAME = "entity-name";
//$NON-NLS-1$
+ public static final String HIBERNATE_TAG_SESSION_FACTORY = "session-factory";
//$NON-NLS-1$
+ public static final String HIBERNATE_TAG_MAPPING = "mapping";
//$NON-NLS-1$
+ public static final String HIBERNATE_TAG_RESOURCE = "resource";
//$NON-NLS-1$
+ public static final String HIBERNATE_TAG_CATALOG = "catalog";
//$NON-NLS-1$
+ public static final String HIBERNATE_TAG_SCHEMA = "schema";
//$NON-NLS-1$
+ public static final String EJB_TAG_ENTITY = "entity";
//$NON-NLS-1$
+ public static final String EJB_TAG_CLASS = "class";
//$NON-NLS-1$
+ public static final String EJB_TAG_MAPPED_SUPERCLASS = "mapped-superclass";
//$NON-NLS-1$
+
+ //prohibit constructor call
+ private OpenMappingUtils() {}
+
+ /**
+ * Get name of a persistent class.
+ * @param rootClass
+ * @return
+ */
+ public static String getPersistentClassName(PersistentClass rootClass) {
+ if (rootClass == null) {
+ return ""; //$NON-NLS-1$
+ }
+ return rootClass.getEntityName() != null ? rootClass.getEntityName() :
rootClass.getClassName();
+ }
+
+ /**
+ * Formulate a full table name.
+ * @param catalog
+ * @param schema
+ * @param name
+ * @return
+ */
+ public static String getTableName(String catalog, String schema, String name) {
+ return (catalog != null ? catalog + '.' : "") + (schema != null ?
schema + '.' : "") + name; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * Get a full table name.
+ * @param table
+ * @return
+ */
+ public static String getTableName(Table table) {
+ return getTableName(table.getCatalog(), table.getSchema(), table.getName());
+ }
+
+ /**
+ * Check has consoleConfiguration config.xml file a mapping class for provided
rootClass.
+ * @param consoleConfiguration
+ * @param rootClass
+ * @return
+ */
+ public static boolean hasConfigXMLMappingClassAnnotation(ConsoleConfiguration
consoleConfiguration, PersistentClass rootClass) {
+ java.io.File configXMLFile = consoleConfiguration.getPreferences().getConfigXMLFile();
+ if (configXMLFile == null) {
+ return true;
+ }
+ EntityResolver entityResolver =
consoleConfiguration.getConfiguration().getEntityResolver();
+ Document doc = getDocument(configXMLFile, entityResolver);
+ return getElements(doc, HIBERNATE_TAG_MAPPING, HIBERNATE_TAG_CLASS,
getPersistentClassName(rootClass)).hasNext();
+ }
+
+ /**
+ * Check has this particular element correspondence in the file.
+ * @param consoleConfiguration
+ * @param file
+ * @param element
+ * @return
+ */
+ public static boolean elementInFile(ConsoleConfiguration consoleConfiguration, IFile
file, Object element) {
+ boolean res = false;
+ if (element instanceof RootClass) {
+ res = rootClassInFile(consoleConfiguration, file, (RootClass)element);
+ } else if (element instanceof Subclass) {
+ res = subclassInFile(consoleConfiguration, file, (Subclass)element);
+ } else if (element instanceof Table) {
+ res = tableInFile(consoleConfiguration, file, (Table)element);
+ }
+ return res;
+ }
+
+ private static String[][] classPairs = {
+ { HIBERNATE_TAG_CLASS, HIBERNATE_TAG_NAME, },
+ { HIBERNATE_TAG_CLASS, HIBERNATE_TAG_ENTITY_NAME, },
+ { EJB_TAG_ENTITY, HIBERNATE_TAG_CLASS, },
+ { EJB_TAG_ENTITY, HIBERNATE_TAG_NAME, },
+ };
+
+ /**
+ * Check has this particular rootClass correspondence in the file.
+ * @param consoleConfiguration
+ * @param file
+ * @param rootClass
+ * @return
+ */
+ public static boolean rootClassInFile(ConsoleConfiguration consoleConfiguration, IFile
file, RootClass rootClass) {
+ EntityResolver entityResolver =
consoleConfiguration.getConfiguration().getEntityResolver();
+ Document doc = getDocument(file.getLocation().toFile(), entityResolver);
+ final String clName = getPersistentClassName(rootClass);
+ final String clNameUnq = StringHelper.unqualify(clName);
+ boolean res = false;
+ // TODO: getElements - this is *extremely* inefficient - no need to scan the whole tree
again and again.
+ for (int i = 0; i < classPairs.length; i++) {
+ res = getElements(doc, classPairs[i][0], classPairs[i][1], clNameUnq).hasNext();
+ if (res) break;
+ res = getElements(doc, classPairs[i][0], classPairs[i][1], clName).hasNext();
+ if (res) break;
+ }
+ return res;
+ }
+
+ private static String[][] subClassPairs = {
+ { HIBERNATE_TAG_SUBCLASS, HIBERNATE_TAG_NAME, },
+ { HIBERNATE_TAG_SUBCLASS, HIBERNATE_TAG_ENTITY_NAME, },
+ { HIBERNATE_TAG_JOINED_SUBCLASS, HIBERNATE_TAG_NAME, },
+ { HIBERNATE_TAG_JOINED_SUBCLASS, HIBERNATE_TAG_ENTITY_NAME, },
+ { HIBERNATE_TAG_UNION_SUBCLASS, HIBERNATE_TAG_NAME, },
+ { HIBERNATE_TAG_UNION_SUBCLASS, HIBERNATE_TAG_ENTITY_NAME, },
+ { EJB_TAG_ENTITY, HIBERNATE_TAG_CLASS, },
+ { EJB_TAG_ENTITY, HIBERNATE_TAG_NAME, },
+ };
+
+ /**
+ * Check has this particular subclass correspondence in the file.
+ * @param consoleConfiguration
+ * @param file
+ * @param subclass
+ * @return
+ */
+ public static boolean subclassInFile(ConsoleConfiguration consoleConfiguration, IFile
file, Subclass subclass) {
+ EntityResolver entityResolver =
consoleConfiguration.getConfiguration().getEntityResolver();
+ Document doc = getDocument(file.getLocation().toFile(), entityResolver);
+ final String clName = getPersistentClassName(subclass);
+ final String clNameUnq = StringHelper.unqualify(clName);
+ boolean res = false;
+ // TODO: getElements - this is *extremely* inefficient - no need to scan the whole tree
again and again.
+ for (int i = 0; i < subClassPairs.length; i++) {
+ res = getElements(doc, subClassPairs[i][0], subClassPairs[i][1],
clNameUnq).hasNext();
+ if (res) break;
+ res = getElements(doc, subClassPairs[i][0], subClassPairs[i][1], clName).hasNext();
+ if (res) break;
+ }
+ return res;
+ }
+
+ /**
+ * Check has this particular table correspondence in the file.
+ * @param consoleConfiguration
+ * @param file
+ * @param table
+ * @return
+ */
+ public static boolean tableInFile(ConsoleConfiguration consoleConfiguration, IFile file,
Table table) {
+ EntityResolver entityResolver =
consoleConfiguration.getConfiguration().getEntityResolver();
+ Document doc = getDocument(file.getLocation().toFile(), entityResolver);
+ Iterator<Element> classes = getElements(doc, HIBERNATE_TAG_CLASS);
+ boolean res = false;
+ while (classes.hasNext()) {
+ Element element = classes.next();
+ Attribute tableAttr = element.attribute(HIBERNATE_TAG_TABLE);
+ if (tableAttr != null) {
+ Attribute catalogAttr = element.attribute(HIBERNATE_TAG_CATALOG);
+ if (catalogAttr == null) {
+ catalogAttr = doc.getRootElement().attribute(HIBERNATE_TAG_CATALOG);
+ }
+ Attribute schemaAttr = element.attribute(HIBERNATE_TAG_SCHEMA);
+ if (schemaAttr == null) {
+ schemaAttr = doc.getRootElement().attribute(HIBERNATE_TAG_SCHEMA);
+ }
+ String catalog = catalogAttr != null ? catalogAttr.getValue() : null;
+ String schema = schemaAttr != null ? schemaAttr.getValue() : null;
+ String name = tableAttr.getValue();
+ if (getTableName(catalog, schema, name).equals(getTableName(table))) {
+ res = true;
+ break;
+ }
+ }
+ Attribute classNameAttr = element.attribute(HIBERNATE_TAG_NAME);
+ if (classNameAttr == null) {
+ classNameAttr = element.attribute(HIBERNATE_TAG_ENTITY_NAME);
+ }
+ if (classNameAttr != null) {
+ String physicalTableName =
consoleConfiguration.getConfiguration().getNamingStrategy().classToTableName(classNameAttr.getValue());
+ if (table.getName().equals(physicalTableName)) {
+ res = true;
+ break;
+ }
+ }
+ }
+ if (!res && getElements(doc, HIBERNATE_TAG_TABLE, table.getName()).hasNext())
{
+ res = true;
+ }
+ return res;
+ }
+
+ private static Iterator<Element> getElements(Document doc, String elementName) {
+ return getElements(doc, elementName, null, null);
+ }
+
+ private static Iterator<Element> getElements(Document doc, String attrName, String
attrValue) {
+ return getElements(doc, null, attrName, attrValue);
+ }
+
+ private static Iterator<Element> getElements(Document doc, String elementName,
String attrName, String attrValue) {
+ LVS visitor = new LVS(elementName, attrName, attrValue);
+ doc.accept(visitor);
+ return visitor.iterator();
+ }
+
+ private static class LVS extends VisitorSupport {
+ private String nodeName;
+ private String attrName;
+ private String attrValue;
+ private List<Element> ret = new ArrayList<Element>();
+
+ public LVS(String nodeName, String attrName, String attrValue) {
+ super();
+ this.nodeName = nodeName;
+ this.attrName = attrName;
+ this.attrValue = attrValue;
+ }
+
+ public void visit(Element element) {
+ if (nodeName == null) {
+ if (attrName != null && attrValue != null) {
+ if (inspectAttributeForValue(element, attrName, attrValue)) {
+ ret.add(element);
+ }
+ }
+ } else {
+ if (nodeName.equals(element.getName())) {
+ if (attrName != null) {
+ if (inspectAttributeForValue(element, attrName, attrValue)) {
+ ret.add(element);
+ }
+ } else {
+ ret.add(element);
+ }
+ }
+ }
+ }
+
+ public Iterator<Element> iterator() {
+ return ret.iterator();
+ }
+
+ protected boolean inspectAttributeForValue(Element element, String attrName, String
checkValue) {
+ Attribute attr = element.attribute(attrName);
+ if (attr != null && checkValue.equals(attr.getValue())) {
+ return checkValue.equals(attr.getValue());
+ }
+ return false;
+ }
+ }
+
+ /**
+ * Trying to find hibernate console config mapping file,
+ * which is corresponding to provided element.
+ *
+ * @param configXMLFile
+ * @param entityResolver
+ * @return
+ */
+ public static Document getDocument(java.io.File configXMLFile, EntityResolver
entityResolver) {
+ Document doc = null;
+ if (configXMLFile == null) {
+ return doc;
+ }
+ InputStream stream = null;
+ try {
+ stream = new FileInputStream(configXMLFile);
+ } catch (FileNotFoundException e) {
+ HibernateConsolePlugin.getDefault().logErrorMessage("Configuration file not
found", e); //$NON-NLS-1$
+ }
+ try {
+ List<Throwable> errors = new ArrayList<Throwable>();
+ XMLHelper helper = new XMLHelper();
+ SAXReader saxReader = helper.createSAXReader(configXMLFile.getPath(), errors,
entityResolver);
+ doc = saxReader.read(new InputSource( stream));
+ if (errors.size() != 0) {
+ HibernateConsolePlugin.getDefault().logErrorMessage("invalid
configuration", (Throwable)null); //$NON-NLS-1$
+ }
+ }
+ catch (DocumentException e) {
+ HibernateConsolePlugin.getDefault().logErrorMessage("Could not parse
configuration", e); //$NON-NLS-1$
+ }
+ finally {
+ try {
+ if (stream != null) stream.close();
+ }
+ catch (IOException ioe) {
+ HibernateConsolePlugin.getDefault().logErrorMessage("could not close input
stream for", ioe); //$NON-NLS-1$
+ }
+ }
+ return doc;
+ }
+
+ /**
+ * Trying to find hibernate console config mapping file,
+ * which is corresponding to provided element.
+ *
+ * @param consoleConfiguration
+ * @param proj
+ * @param element
+ * @return
+ */
+ @SuppressWarnings("unchecked")
+ public static IFile searchInMappingFiles(ConsoleConfiguration consoleConfiguration,
IJavaProject proj, Object element) {
+ IFile file = null;
+ if (consoleConfiguration == null) {
+ return file;
+ }
+ java.io.File configXMLFile = consoleConfiguration.getPreferences().getConfigXMLFile();
+ EntityResolver entityResolver =
consoleConfiguration.getConfiguration().getEntityResolver();
+ Document doc = getDocument(configXMLFile, entityResolver);
+ if (doc == null) {
+ return file;
+ }
+ IPackageFragmentRoot[] packageFragmentRoots = new IPackageFragmentRoot[0];
+ try {
+ if (proj != null) {
+ packageFragmentRoots = proj.getAllPackageFragmentRoots();
+ }
+ } catch (JavaModelException e) {
+ HibernateConsolePlugin.getDefault().logErrorMessage(HibernateConsoleMessages.OpenFileActionUtils_problems_while_get_project_package_fragment_roots,
e);
+ }
+ Element sfNode = doc.getRootElement().element(HIBERNATE_TAG_SESSION_FACTORY);
+ Iterator<Element> elements = sfNode.elements(HIBERNATE_TAG_MAPPING).iterator();
+ while (elements.hasNext() && file == null) {
+ Element subelement = elements.next();
+ Attribute resourceAttr = subelement.attribute(HIBERNATE_TAG_RESOURCE);
+ if (resourceAttr == null) {
+ continue;
+ }
+ for (int i = 0; i < packageFragmentRoots.length; i++) {
+ //search in source folders.
+ if (packageFragmentRoots[i].getClass() != PackageFragmentRoot.class) {
+ continue;
+ }
+ IPackageFragmentRoot packageFragmentRoot = packageFragmentRoots[i];
+ IPath path = packageFragmentRoot.getPath().append(resourceAttr.getValue());
+ file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
+ if (file == null) {
+ continue;
+ }
+ if (file.exists() && elementInFile(consoleConfiguration, file, element)) {
+ break;
+ }
+ file = null;
+ }
+ }
+ return file;
+ }
+
+ /**
+ * Trying to find console configuration additional mapping file,
+ * which is corresponding to provided element.
+ *
+ * @param consoleConfiguration
+ * @param element
+ * @return
+ */
+ public static IFile searchInAdditionalMappingFiles(ConsoleConfiguration
consoleConfiguration, Object element) {
+ IFile file = null;
+ if (consoleConfiguration == null) {
+ return file;
+ }
+ java.io.File[] files = consoleConfiguration.getPreferences().getMappingFiles();
+ for (int i = 0; i < files.length; i++) {
+ java.io.File fileTmp = files[i];
+ if (fileTmp == null) {
+ continue;
+ }
+ file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(new
Path(fileTmp.getPath()));
+ if (file == null) {
+ continue;
+ }
+ if (file.exists() && elementInFile(consoleConfiguration, file, element)) {
+ break;
+ }
+ file = null;
+ }
+ return file;
+ }
+
+ /**
+ * Trying to find hibernate console config ejb3 mapping file,
+ * which is corresponding to provided element.
+ *
+ * @param consoleConfiguration
+ * @param proj
+ * @param element
+ * @return
+ */
+ public static IFile searchInEjb3MappingFiles(ConsoleConfiguration consoleConfiguration,
IJavaProject proj, Object element) {
+ IFile file = null;
+ if (consoleConfiguration == null || proj == null) {
+ return file;
+ }
+ final ConsoleConfiguration cc2 = consoleConfiguration;
+ List<String> documentPaths =
(List<String>)consoleConfiguration.getExecutionContext().execute(new
ExecutionContext.Command() {
+ public Object execute() {
+ return OpenMappingUtilsEjb3.enumDocuments(cc2);
+ }
+ });
+ IPath projPath = proj.getPath();
+ IPath projFullPath = proj.getResource().getLocation();
+ IPath outPath = Path.EMPTY;
+ IPackageFragmentRoot[] packageFragmentRoots = new IPackageFragmentRoot[0];
+ try {
+ outPath = proj.getOutputLocation();
+ packageFragmentRoots = proj.getPackageFragmentRoots();
+ } catch (JavaModelException e) {
+ HibernateConsolePlugin.getDefault().logErrorMessage(HibernateConsoleMessages.OpenFileActionUtils_problems_while_get_project_package_fragment_roots,
e);
+ }
+ outPath = outPath.makeRelativeTo(projPath);
+ for (int i = 0; i < packageFragmentRoots.length && file == null; i++) {
+ if (!(packageFragmentRoots[i] instanceof PackageFragmentRoot)) {
+ continue;
+ }
+ if (packageFragmentRoots[i] instanceof JarPackageFragmentRoot) {
+ // TODO: add possibility open resorces from jar files
+ continue;
+ }
+ PackageFragmentRoot packageFragmentRoot =
(PackageFragmentRoot)packageFragmentRoots[i];
+ IPath packageFragmentRootPath = packageFragmentRoot.getResource().getFullPath();
+ Iterator<String> it = documentPaths.iterator();
+ while (it.hasNext()) {
+ String docPath = it.next();
+ IPath path2DocFull = Path.fromOSString(docPath);
+ IPath path2Doc = path2DocFull.makeRelativeTo(projFullPath);
+ IPath resPath = projPath.append(path2Doc);
+ resPath = resPath.makeRelativeTo(projPath);
+ resPath = resPath.makeRelativeTo(outPath);
+ resPath = packageFragmentRootPath.append(resPath);
+ file = ResourcesPlugin.getWorkspace().getRoot().getFile(resPath);
+ if (file == null) {
+ continue;
+ }
+ if (file.exists() && elementInFile(consoleConfiguration, file, element)) {
+ break;
+ }
+ file = null;
+ }
+ }
+ return file;
+ }
+
+ /**
+ * This function is trying to find hibernate console config file,
+ * which is corresponding to provided element.
+ *
+ * @param consoleConfiguration
+ * @param proj
+ * @param element
+ * @return
+ */
+ public static IFile searchFileToOpen(ConsoleConfiguration consoleConfiguration,
IJavaProject proj, Object element) {
+ IFile file = searchInMappingFiles(consoleConfiguration, proj, element);
+ if (file == null) {
+ file = searchInAdditionalMappingFiles(consoleConfiguration, element);
+ }
+ if (file == null) {
+ file = searchInEjb3MappingFiles(consoleConfiguration, proj, element);
+ }
+ return file;
+ }
+
+ /**
+ * Creates FindReplaceDocumentAdapter for provided text editor.
+ *
+ * @param textEditor
+ * @return
+ */
+ public static FindReplaceDocumentAdapter createFindDocAdapter(ITextEditor textEditor) {
+ IDocument document = null;
+ if (textEditor.getDocumentProvider() != null){
+ document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
+ }
+ if (document == null) {
+ return null;
+ }
+ return new FindReplaceDocumentAdapter(document);
+ }
+
+ /**
+ * Opens an editor on the given file resource.
+ * @param file the editor input
+ * @return an open editor or <code>null</code> if an external editor was
opened
+ * @exception PartInitException if the editor could not be initialized
+ */
+ public static IEditorPart openFileInEditor(IFile file) throws PartInitException {
+ IWorkbenchPage page =
+ PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
+ return IDE.openEditor(page, file);
+ }
+
+ /**
+ * Finds a document region, which corresponds of given selection object.
+ * @param findAdapter
+ * @param selection
+ * @return a proper document region
+ */
+ public static IRegion findSelectRegion(IJavaProject proj, FindReplaceDocumentAdapter
findAdapter, Object selection) {
+ IRegion selectRegion = null;
+ if (selection instanceof RootClass || selection instanceof Subclass) {
+ selectRegion = findSelectRegion(proj, findAdapter, (PersistentClass)selection);
+ } else if (selection instanceof Property){
+ selectRegion = findSelectRegion(proj, findAdapter, (Property)selection);
+ }
+ return selectRegion;
+ }
+
+ /**
+ * Finds a document region, which corresponds of given property.
+ * @param findAdapter
+ * @param property
+ * @return a proper document region
+ */
+ public static IRegion findSelectRegion(IJavaProject proj, FindReplaceDocumentAdapter
findAdapter, Property property) {
+ Assert.isNotNull(property.getPersistentClass());
+ IRegion classRegion = findSelectRegion(proj, findAdapter,
property.getPersistentClass());
+ IRegion res = null;
+ if (classRegion == null) {
+ return res;
+ }
+ // in case if we could not find property - we select class
+ res = classRegion;
+ final Cfg2HbmTool tool = new Cfg2HbmTool();
+ final PersistentClass persistentClass = property.getPersistentClass();
+ final String tagName = tool.getTag(persistentClass);
+ IRegion finalRegion = null;
+ IRegion propRegion = null;
+ int startOffset = classRegion.getOffset() + classRegion.getLength();
+ try {
+ String tagClose = "</" + tagName; //$NON-NLS-1$
+ finalRegion = findAdapter.find(startOffset, tagClose, true, true, false, false);
+ if (finalRegion == null) {
+ tagClose = "</" + EJB_TAG_ENTITY; //$NON-NLS-1$
+ finalRegion = findAdapter.find(startOffset, tagClose, true, true, false, false);
+ }
+ propRegion = findAdapter.find(startOffset, generateHbmPropertyPattern(property), true,
true, false, true);
+ if (propRegion == null) {
+ propRegion = findAdapter.find(startOffset, generateEjbPropertyPattern(property),
true, true, false, true);
+ }
+ } catch (BadLocationException e) {
+ //ignore
+ }
+ String className = persistentClass.getClassName();
+ while (propRegion == null) {
+ className = ProjectUtils.getParentTypename(proj, className);
+ if (className == null) {
+ break;
+ }
+ classRegion = findSelectRegion(proj, findAdapter, className);
+ if (classRegion == null) {
+ break;
+ }
+ startOffset = classRegion.getOffset() + classRegion.getLength();
+ try {
+ String tagClose = "</" + EJB_TAG_MAPPED_SUPERCLASS; //$NON-NLS-1$
+ finalRegion = findAdapter.find(startOffset, tagClose, true, true, false, false);
+ propRegion = findAdapter.find(startOffset, generateEjbPropertyPattern(property),
true, true, false, true);
+ } catch (BadLocationException e) {
+ //ignore
+ }
+ }
+ if (propRegion != null) {
+ int length = property.getName().length();
+ int offset = propRegion.getOffset() + propRegion.getLength() - length - 1;
+ res = new Region(offset, length);
+ if (finalRegion != null && propRegion.getOffset() >
finalRegion.getOffset()) {
+ res = null;
+ }
+ }
+ return res;
+ }
+
+ /**
+ * Finds a document region, which corresponds of given persistent class.
+ * @param findAdapter
+ * @param persistentClass
+ * @return a proper document region
+ */
+ public static IRegion findSelectRegion(IJavaProject proj, FindReplaceDocumentAdapter
findAdapter, PersistentClass persistentClass) {
+ IRegion res = null;
+ String[] classPatterns = generatePersistentClassPatterns(persistentClass);
+ IRegion classRegion = null;
+ try {
+ for (int i = 0; (classRegion == null) && (i < classPatterns.length); i++){
+ classRegion = findAdapter.find(0, classPatterns[i], true, true, false, true);
+ }
+ } catch (BadLocationException e) {
+ //ignore
+ }
+ if (classRegion != null) {
+ int length = persistentClass.getNodeName().length();
+ int offset = classRegion.getOffset() + classRegion.getLength() - length - 1;
+ res = new Region(offset, length);
+ }
+ return res;
+ }
+
+ /**
+ * Finds a document region, which corresponds of given persistent class.
+ * @param findAdapter
+ * @param className
+ * @return a proper document region
+ */
+ public static IRegion findSelectRegion(IJavaProject proj, FindReplaceDocumentAdapter
findAdapter, String className) {
+ IRegion res = null;
+ String[] classPatterns = generatePersistentClassPatterns(className);
+ IRegion classRegion = null;
+ try {
+ for (int i = 0; (classRegion == null) && (i < classPatterns.length); i++){
+ classRegion = findAdapter.find(0, classPatterns[i], true, true, false, true);
+ }
+ } catch (BadLocationException e) {
+ //ignore
+ }
+ if (classRegion != null) {
+ int length = getShortClassName(className).length();
+ int offset = classRegion.getOffset() + classRegion.getLength() - length - 1;
+ res = new Region(offset, length);
+ }
+ return res;
+ }
+
+ /**
+ * Creates a xml tag search pattern with given tag name which should contains
+ * proper name-value pair.
+ *
+ * @param tagName
+ * @param name
+ * @param value
+ * @return a result search pattern
+ */
+ public static String createPattern(String tagName, String name, String value) {
+ StringBuffer pattern = new StringBuffer("<"); //$NON-NLS-1$
+ pattern.append(tagName);
+ pattern.append("[\\s]+[.[^>]]*"); //$NON-NLS-1$
+ pattern.append(name);
+ pattern.append("[\\s]*=[\\s]*\""); //$NON-NLS-1$
+ pattern.append(value);
+ pattern.append('\"');
+ return pattern.toString();
+ }
+
+ private static String[][] persistentClassPairs = {
+ { HIBERNATE_TAG_CLASS, HIBERNATE_TAG_NAME, },
+ { HIBERNATE_TAG_CLASS, HIBERNATE_TAG_ENTITY_NAME, },
+ { EJB_TAG_ENTITY, HIBERNATE_TAG_NAME, },
+ { EJB_TAG_ENTITY, EJB_TAG_CLASS, },
+ { EJB_TAG_MAPPED_SUPERCLASS, HIBERNATE_TAG_NAME, },
+ { EJB_TAG_MAPPED_SUPERCLASS, EJB_TAG_CLASS, },
+ };
+
+ /**
+ * Extract short name of the class from fullClassName.
+ *
+ * @param fullClassName
+ * @return a short class name
+ */
+ public static String getShortClassName(String fullClassName) {
+ return fullClassName.substring(fullClassName.lastIndexOf('.') + 1);
+ }
+
+ /**
+ * Generates a persistent class xml tag search patterns.
+ *
+ * @param persClass
+ * @return an arrays of search patterns
+ */
+ public static String[] generatePersistentClassPatterns(PersistentClass persClass) {
+ String fullClassName = null;
+ String shortClassName = null;
+ if (persClass.getEntityName() != null){
+ fullClassName = persClass.getEntityName();
+ } else {
+ fullClassName = persClass.getClassName();
+ }
+ shortClassName = getShortClassName(fullClassName);
+ final Cfg2HbmTool tool = new Cfg2HbmTool();
+ final String tagName = tool.getTag(persClass);
+ persistentClassPairs[0][0] = tagName;
+ persistentClassPairs[1][0] = tagName;
+ List<String> patterns = new ArrayList<String>();
+ for (int i = 0; i < persistentClassPairs.length; i++) {
+ patterns.add(createPattern(persistentClassPairs[i][0], persistentClassPairs[i][1],
shortClassName));
+ patterns.add(createPattern(persistentClassPairs[i][0], persistentClassPairs[i][1],
fullClassName));
+ }
+ return patterns.toArray(new String[0]);
+ }
+
+ /**
+ * Generates a persistent class xml tag search patterns.
+ *
+ * @param fullClassName
+ * @return an arrays of search patterns
+ */
+ public static String[] generatePersistentClassPatterns(String fullClassName) {
+ String shortClassName = getShortClassName(fullClassName);
+ List<String> patterns = new ArrayList<String>();
+ for (int i = 0; i < persistentClassPairs.length; i++) {
+ patterns.add(createPattern(persistentClassPairs[i][0], persistentClassPairs[i][1],
shortClassName));
+ patterns.add(createPattern(persistentClassPairs[i][0], persistentClassPairs[i][1],
fullClassName));
+ }
+ return patterns.toArray(new String[0]);
+ }
+
+ /**
+ * Generates a property xml tag search pattern, which corresponds hibernate hbm syntax.
+ *
+ * @param property
+ * @return a search patterns
+ */
+ public static String generateHbmPropertyPattern(Property property) {
+ final Cfg2HbmTool tool = new Cfg2HbmTool();
+ String toolTag = ""; //$NON-NLS-1$
+ PersistentClass pc = property.getPersistentClass();
+ if (pc != null && pc.getIdentifierProperty() == property) {
+ if (property.isComposite()) {
+ toolTag = "composite-id"; //$NON-NLS-1$
+ } else {
+ toolTag = "id"; //$NON-NLS-1$
+ }
+ } else {
+ toolTag = tool.getTag(property);
+ if ("component".equals(toolTag) &&
"embedded".equals(property.getPropertyAccessorName())) {
//$NON-NLS-1$//$NON-NLS-2$
+ toolTag = "properties"; //$NON-NLS-1$
+ }
+ }
+ return createPattern(toolTag, HIBERNATE_TAG_NAME, property.getName());
+ }
+
+ /**
+ * Generates a property xml tag search pattern, which corresponds ejb3 syntax.
+ *
+ * @param property
+ * @return a search patterns
+ */
+ public static String generateEjbPropertyPattern(Property property) {
+ String toolTag = ""; //$NON-NLS-1$
+ PersistentClass pc = property.getPersistentClass();
+ if (pc != null && pc.getIdentifierProperty() == property) {
+ if (property.isComposite()) {
+ toolTag = "embedded-id"; //$NON-NLS-1$
+ } else {
+ toolTag = "id"; //$NON-NLS-1$
+ }
+ } else {
+ Value value = property.getValue();
+ toolTag = "basic"; //$NON-NLS-1$
+ if (!value.isSimpleValue()) {
+ if (value instanceof Collection) {
+ value = ((Collection)value).getElement();
+ }
+ }
+ if (value instanceof OneToMany) {
+ toolTag = "one-to-many"; //$NON-NLS-1$
+ }
+ else if (value instanceof ManyToOne) {
+ // could be many-to-one | many-to-many
+ toolTag = "many-to-((one)|(many))"; //$NON-NLS-1$
+ }
+ else if (value instanceof OneToOne) {
+ toolTag = "one-to-one"; //$NON-NLS-1$
+ }
+ else if (value instanceof Map) {
+ toolTag = "many-to-many"; //$NON-NLS-1$
+ }
+ else if (value instanceof Component) {
+ if (((Component)value).isEmbedded()) {
+ toolTag = "embedded"; //$NON-NLS-1$
+ }
+ }
+ if (value instanceof ToOne) {
+ if (((ToOne)value).isEmbedded()) {
+ toolTag = "embedded"; //$NON-NLS-1$
+ }
+ }
+ }
+ return createPattern(toolTag, HIBERNATE_TAG_NAME, property.getName());
+ }
+
+ /**
+ * Method gets all ITextEditors from IEditorPart. Shouldn't returns null value.
+ *
+ * @param editorPart
+ * @return
+ */
+ public static ITextEditor[] getTextEditors(IEditorPart editorPart) {
+ // if EditorPart is MultiPageEditorPart then get ITextEditor from it.
+ ITextEditor[] res = new ITextEditor[0];
+ if (editorPart instanceof MultiPageEditorPart) {
+ List<ITextEditor> testEditors = new ArrayList<ITextEditor>();
+ IEditorPart[] editors =
((MultiPageEditorPart)editorPart).findEditors(editorPart.getEditorInput());
+ for (int i = 0; i < editors.length; i++) {
+ if (editors[i] instanceof ITextEditor){
+ testEditors.add((ITextEditor)editors[i]);
+ }
+ }
+ res = testEditors.toArray(res);
+ } else if (editorPart instanceof ITextEditor){
+ res = new ITextEditor[]{(ITextEditor) editorPart};
+ }
+ return res;
+ }
+}
Added:
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/utils/OpenMappingUtilsEjb3.java
===================================================================
---
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/utils/OpenMappingUtilsEjb3.java
(rev 0)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/utils/OpenMappingUtilsEjb3.java 2009-05-22
15:59:07 UTC (rev 15446)
@@ -0,0 +1,278 @@
+package org.hibernate.eclipse.console.utils;
+
+import java.io.IOException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.StringTokenizer;
+
+import javax.persistence.Embeddable;
+import javax.persistence.Entity;
+import javax.persistence.MappedSuperclass;
+import javax.persistence.spi.PersistenceUnitTransactionType;
+
+import org.hibernate.console.ConsoleConfiguration;
+import org.hibernate.eclipse.console.HibernateConsolePlugin;
+import org.hibernate.ejb.Ejb3Configuration;
+import org.hibernate.ejb.HibernatePersistence;
+import org.hibernate.ejb.packaging.JarVisitor;
+import org.hibernate.ejb.packaging.NamedInputStream;
+import org.hibernate.ejb.packaging.PersistenceMetadata;
+import org.hibernate.ejb.packaging.PersistenceXmlLoader;
+import org.hibernate.util.CollectionHelper;
+
+/**
+ * Most functions in this utility class are copy of
+ * org.hibernate.ejb.Ejb3Configuration private functions.
+ * These functions are responsible for bypass all ejb3 configuration files.
+ *
+ * @author Vitali Yemialyanchyk
+ */
+public class OpenMappingUtilsEjb3 {
+
+ public static final String META_INF_PERS_XML = "META-INF/persistence.xml";
//$NON-NLS-1$
+ public static final String META_INF_ORM_XML = "META-INF/orm.xml";
//$NON-NLS-1$
+
+ private OpenMappingUtilsEjb3() {}
+
+ /**
+ * Collect list of paths to ejb3 resource configuration files.
+ * This function code based on code from Ejb3Configuration.
+ * @see Ejb3Configuration configure(String persistenceUnitName, Map integration)
+ *
+ * @param consoleConfiguration
+ * @return
+ */
+ public static List<String> enumDocuments(ConsoleConfiguration
consoleConfiguration) {
+ String persistenceUnitName =
consoleConfiguration.getPreferences().getPersistenceUnitName();
+ Enumeration<URL> xmls = null;
+ try {
+ xmls =
Thread.currentThread().getContextClassLoader().getResources(META_INF_PERS_XML);
+ } catch (IOException e) {
+ //ignore
+ }
+ if (xmls == null || !xmls.hasMoreElements()) {
+ return null;
+ }
+ final String IMPLEMENTATION_NAME = HibernatePersistence.class.getName();
+ List<String> res = null;
+ while (xmls.hasMoreElements() && res == null) {
+ URL url = xmls.nextElement();
+ List<PersistenceMetadata> metadataFiles = null;
+ try {
+ metadataFiles = PersistenceXmlLoader.deploy(
+ url, CollectionHelper.EMPTY_MAP,
+ consoleConfiguration.getConfiguration().getEntityResolver(),
+ PersistenceUnitTransactionType.RESOURCE_LOCAL);
+ } catch (Exception e1) {
+ //ignore
+ }
+ if (metadataFiles == null) {
+ continue;
+ }
+ boolean stopErrorFlag = false;
+ for (PersistenceMetadata metadata : metadataFiles) {
+ boolean tmp = metadata.getProvider() == null;
+ tmp = tmp || IMPLEMENTATION_NAME.equalsIgnoreCase(metadata.getProvider());
+ if (!tmp) {
+ continue;
+ }
+ //correct provider
+ //lazy compute the visitor if possible to avoid useless exceptions if an unexpected
state happens
+ JarVisitor visitor = null;
+ URL visitorJarURL = null;
+ if (metadata.getName() == null) {
+ visitor = getMainJarVisitor(url, metadata, CollectionHelper.EMPTY_MAP);
+ visitorJarURL = JarVisitor.getJarURLFromURLEntry(url, "/" +
META_INF_PERS_XML); //$NON-NLS-1$
+ metadata.setName(visitor.getUnqualifiedJarName());
+ }
+ if (persistenceUnitName == null && xmls.hasMoreElements()) {
+ //throw new PersistenceException( "No name provided and several persistence
units found" );
+ stopErrorFlag = true;
+ break;
+ }
+ else if (persistenceUnitName == null ||
metadata.getName().equals(persistenceUnitName)) {
+ if (visitor == null) {
+ visitor = getMainJarVisitor(url, metadata, CollectionHelper.EMPTY_MAP);
+ visitorJarURL = JarVisitor.getJarURLFromURLEntry(url, "/" +
META_INF_PERS_XML); //$NON-NLS-1$
+ }
+ try {
+ addMetadataFromVisitor(visitor, visitorJarURL.getPath(), metadata);
+ JarVisitor.Filter[] otherXmlFilter = getFilters(metadata,
CollectionHelper.EMPTY_MAP, false);
+ for (String jarFile : metadata.getJarFiles()) {
+ // TODO: test this code
+ //vit//visitor = JarVisitor.getVisitor(jarFile, otherXmlFilter);
+ //vit//addMetadataFromVisitor(visitor, metadata);
+ }
+ } catch (IOException e) {
+ //ignore
+ }
+ res = new ArrayList<String>();
+ Iterator<NamedInputStream> it = metadata.getHbmfiles().iterator();
+ while (it.hasNext()) {
+ NamedInputStream nis = it.next();
+ res.add(nis.getName());
+ try {
+ nis.getStream().close();
+ }
+ catch (IOException ioe) {
+ HibernateConsolePlugin.getDefault().logErrorMessage("could not close input
stream for", ioe); //$NON-NLS-1$
+ }
+ }
+ break;
+ }
+ }
+ if (stopErrorFlag) {
+ break;
+ }
+ }
+ return res;
+ }
+
+ /**
+ * This function code based on code from Ejb3Configuration.
+ * @see JarVisitor Ejb3Configuration.getMainJarVisitor(URL url, PersistenceMetadata
metadata, Map integration)
+ *
+ * @param url
+ * @param metadata
+ * @param integration
+ * @return
+ */
+ public static JarVisitor getMainJarVisitor(URL url, PersistenceMetadata metadata, Map
integration) {
+ URL jarURL = JarVisitor.getJarURLFromURLEntry(url, "/" + META_INF_PERS_XML);
//$NON-NLS-1$
+ JarVisitor.Filter[] persistenceXmlFilter = getFilters(metadata, integration,
metadata.getExcludeUnlistedClasses());
+ JarVisitor visitor = JarVisitor.getVisitor(jarURL, persistenceXmlFilter);
+ return visitor;
+ }
+
+ /**
+ * This function code based on code from Ejb3Configuration.
+ * @see JarVisitor Ejb3Configuration.addMetadataFromVisitor(JarVisitor visitor,
PersistenceMetadata metadata) throws IOException
+ *
+ * @param visitor
+ * @param metadata
+ * @throws IOException
+ */
+ public static void addMetadataFromVisitor(JarVisitor visitor, String addPath,
PersistenceMetadata metadata) throws IOException {
+ Set[] entries = visitor.getMatchingEntries();
+ JarVisitor.Filter[] filters = visitor.getFilters();
+ int size = filters.length;
+ List<String> classes = metadata.getClasses();
+ List<String> packages = metadata.getPackages();
+ List<NamedInputStream> hbmFiles = metadata.getHbmfiles();
+ for (int index = 0; index < size; index++) {
+ Iterator homogeneousEntry = entries[index].iterator();
+ while (homogeneousEntry.hasNext()) {
+ JarVisitor.Entry entry = (JarVisitor.Entry) homogeneousEntry.next();
+ if (filters[index] instanceof JarVisitor.ClassFilter) {
+ //TODO only add entry if there is annotations (Javassist)
+ classes.add(entry.getName());
+ }
+ else if (filters[index] instanceof JarVisitor.PackageFilter) {
+ packages.add(entry.getName());
+ }
+ else if (filters[index] instanceof JarVisitor.FileFilter) {
+ hbmFiles.add(new NamedInputStream(addPath + "/" + entry.getName(),
//$NON-NLS-1$
+ entry.getInputStream()));
+ metadata.getMappingFiles().remove(entry.getName());
+ }
+ }
+ }
+ }
+
+ /**
+ * This function code based on code from Ejb3Configuration.
+ * @see boolean[] Ejb3Configuration.getDetectedArtifacts(Properties properties, Map
overridenProperties, boolean excludeIfNotOverriden)
+ *
+ * @param properties
+ * @param overridenProperties
+ * @param excludeIfNotOverriden
+ * @return
+ */
+ public static boolean[] getDetectedArtifacts(Properties properties, Map
overridenProperties, boolean excludeIfNotOverriden) {
+ //result[0] - detect classes
+ //result[1] - detect hbm
+ boolean[] result = { false, false };
+ String detect = overridenProperties != null ?
+ (String) overridenProperties.get(HibernatePersistence.AUTODETECTION) : null;
+ detect = detect == null ?
+ properties.getProperty( HibernatePersistence.AUTODETECTION) : detect;
+ if (detect == null && excludeIfNotOverriden) {
+ //not overriden through HibernatePersistence.AUTODETECTION so we comply with the spec
excludeUnlistedClasses
+ return result;
+ }
+ else if (detect == null){
+ detect = "class,hbm"; //$NON-NLS-1$
+ }
+ StringTokenizer st = new StringTokenizer(detect, ", ", false); //$NON-NLS-1$
+ while (st.hasMoreElements()) {
+ String element = (String)st.nextElement();
+ if ("class".equalsIgnoreCase(element)) { //$NON-NLS-1$
+ result[0] = true;
+ }
+ if ("hbm".equalsIgnoreCase(element)) { //$NON-NLS-1$
+ result[1] = true;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * This function code based on code from Ejb3Configuration.
+ * @see JarVisitor.Filter[] Ejb3Configuration.getFilters(PersistenceMetadata metadata,
Map overridenProperties, boolean excludeIfNotOverriden)
+ *
+ * @param metadata
+ * @param overridenProperties
+ * @param excludeIfNotOverriden
+ * @return
+ */
+ public static JarVisitor.Filter[] getFilters(PersistenceMetadata metadata, Map
overridenProperties, boolean excludeIfNotOverriden) {
+ Properties properties = metadata.getProps();
+ final List<String> mappingFiles = metadata.getMappingFiles();
+ boolean[] result = getDetectedArtifacts(properties, overridenProperties,
excludeIfNotOverriden);
+
+ int size = ( result[0] ? 2 : 0 ) + 1; //class involves classes and packages, xml files
are always involved because of orm.xml
+ JarVisitor.Filter[] filters = new JarVisitor.Filter[size];
+ if (result[0]) {
+ filters[0] = new JarVisitor.PackageFilter(false, null) {
+ public boolean accept(String javaElementName) {
+ return true;
+ }
+ };
+ filters[1] = new JarVisitor.ClassFilter(
+ false, new Class[]{
+ Entity.class,
+ MappedSuperclass.class,
+ Embeddable.class}
+ ) {
+ public boolean accept(String javaElementName) {
+ return true;
+ }
+ };
+ }
+ if (result[1]) {
+ filters[size - 1] = new JarVisitor.FileFilter(true) {
+ public boolean accept(String javaElementName) {
+ return javaElementName.endsWith("hbm.xml") //$NON-NLS-1$
+ || javaElementName.endsWith(META_INF_ORM_XML)
+ || mappingFiles.contains(javaElementName);
+ }
+ };
+ }
+ else {
+ filters[size - 1] = new JarVisitor.FileFilter(true) {
+ public boolean accept(String javaElementName) {
+ return javaElementName.endsWith(META_INF_ORM_XML)
+ || mappingFiles.contains(javaElementName);
+ }
+ };
+ }
+ return filters;
+ }
+
+}
Modified:
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/utils/ProjectUtils.java
===================================================================
---
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/utils/ProjectUtils.java 2009-05-22
15:09:10 UTC (rev 15445)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/utils/ProjectUtils.java 2009-05-22
15:59:07 UTC (rev 15446)
@@ -21,6 +21,8 @@
*/
package org.hibernate.eclipse.console.utils;
+import java.util.List;
+
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
@@ -36,8 +38,17 @@
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchManager;
+import org.eclipse.jdt.core.ICompilationUnit;
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.dom.AST;
+import org.eclipse.jdt.core.dom.ASTParser;
+import org.eclipse.jdt.core.dom.ITypeBinding;
+import org.eclipse.jdt.core.dom.Type;
+import org.eclipse.jdt.core.dom.TypeDeclaration;
+import org.eclipse.jdt.internal.core.SourceType;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
@@ -192,4 +203,70 @@
}
return proj;
}
-}
\ No newline at end of file
+
+ static public org.eclipse.jdt.core.dom.CompilationUnit getCompilationUnit(
+ ICompilationUnit source, boolean bindings) {
+ ASTParser parser = ASTParser.newParser(AST.JLS3);
+ parser.setSource(source);
+ parser.setResolveBindings(bindings);
+ org.eclipse.jdt.core.dom.CompilationUnit result =
(org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(null);
+ return result;
+ }
+
+ static public ICompilationUnit findCompilationUnit(IJavaProject javaProject,
+ String fullyQualifiedName) {
+ IType lwType = findType(javaProject, fullyQualifiedName);
+ if (lwType != null) {
+ return lwType.getCompilationUnit();
+ }
+ return null;
+ }
+
+ static public IType findType(IJavaProject javaProject,
+ String fullyQualifiedName) {
+ IType lwType = null;
+ try {
+ lwType = javaProject.findType(fullyQualifiedName);
+ } catch (JavaModelException e) {
+ // just ignore it!
+ }
+ return lwType;
+ }
+
+ static public String getParentTypename(IJavaProject proj, String fullyQualifiedName) {
+ String res = null;
+ ICompilationUnit icu = findCompilationUnit(proj, fullyQualifiedName);
+ if (icu == null) {
+ return res;
+ }
+ org.eclipse.jdt.core.dom.CompilationUnit cu = getCompilationUnit(icu, true);
+ if (cu == null) {
+ return res;
+ }
+ List types = cu.types();
+ for (int i = 0; i < types.size() && res == null; i++) {
+ Object obj = types.get(i);
+ if (!(obj instanceof TypeDeclaration)) {
+ continue;
+ }
+ TypeDeclaration td = (TypeDeclaration)obj;
+ Type superType = td.getSuperclassType();
+ if (superType != null) {
+ ITypeBinding tb = superType.resolveBinding();
+ if (tb != null) {
+ if (tb.getJavaElement() instanceof SourceType) {
+ SourceType sourceT = (SourceType)tb.getJavaElement();
+ try {
+ res = sourceT.getFullyQualifiedParameterizedName();
+ }
+ catch (JavaModelException e) {
+ HibernateConsolePlugin.getDefault().logErrorMessage("JavaModelException:
", e); //$NON-NLS-1$
+ }
+ }
+ }
+ }
+ }
+ return res;
+ }
+
+}
Modified:
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/internal/CriteriaQuickAssistProcessor.java
===================================================================
---
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/internal/CriteriaQuickAssistProcessor.java 2009-05-22
15:09:10 UTC (rev 15445)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/internal/CriteriaQuickAssistProcessor.java 2009-05-22
15:59:07 UTC (rev 15446)
@@ -39,8 +39,8 @@
import org.eclipse.ui.texteditor.ITextEditor;
import org.hibernate.console.ImageConstants;
import org.hibernate.eclipse.console.HibernateConsolePlugin;
-import org.hibernate.eclipse.console.actions.OpenFileActionUtils;
import org.hibernate.eclipse.console.utils.EclipseImages;
+import org.hibernate.eclipse.console.utils.OpenMappingUtils;
import org.hibernate.eclipse.jdt.ui.Activator;
@@ -62,7 +62,7 @@
public void apply(IDocument target) {
//IEditorPart editorPart =
HibernateConsolePlugin.getDefault().openCriteriaEditor(getName(), getContents());
IEditorPart editorPart =
Activator.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
- ITextEditor[] textEditors = OpenFileActionUtils.getTextEditors(editorPart);
+ ITextEditor[] textEditors = OpenMappingUtils.getTextEditors(editorPart);
if (textEditors.length == 0) return;
new SaveQueryEditorListener(textEditors[0], getName(), getContents(), position,
SaveQueryEditorListener.CriteriaEditor);
}
Modified:
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/internal/HQLQuickAssistProcessor.java
===================================================================
---
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/internal/HQLQuickAssistProcessor.java 2009-05-22
15:09:10 UTC (rev 15445)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/internal/HQLQuickAssistProcessor.java 2009-05-22
15:59:07 UTC (rev 15446)
@@ -32,8 +32,8 @@
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.texteditor.ITextEditor;
import org.hibernate.console.ImageConstants;
-import org.hibernate.eclipse.console.actions.OpenFileActionUtils;
import org.hibernate.eclipse.console.utils.EclipseImages;
+import org.hibernate.eclipse.console.utils.OpenMappingUtils;
import org.hibernate.eclipse.jdt.ui.Activator;
public class HQLQuickAssistProcessor extends BasicQuickAssistProcessor {
@@ -55,7 +55,7 @@
result[0] = new ExternalActionQuickAssistProposal(contents,
EclipseImages.getImage(ImageConstants.HQL_EDITOR),
JdtUiMessages.HQLQuickAssistProcessor_copy_to_hql_editor, context) {
public void apply(IDocument document) {
IEditorPart editorPart =
Activator.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
- ITextEditor[] textEditors = OpenFileActionUtils.getTextEditors(editorPart);
+ ITextEditor[] textEditors = OpenMappingUtils.getTextEditors(editorPart);
if (textEditors.length == 0) return;
Point position = new Point(stringLiteral.getStartPosition() + 1,
stringLiteral.getLength() - 2);
new SaveQueryEditorListener(textEditors[0], getName(), getContents(), position,
SaveQueryEditorListener.HQLEditor);