Author: vyemialyanchyk
Date: 2009-05-14 10:42:10 -0400 (Thu, 14 May 2009)
New Revision: 15251
Modified:
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/OpenMappingAction.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-4285 - code review - make code more readable:
rename/create functions where it was necessary, use proper interfaces, reduce code size,
add code comments; functionality remains the same
Modified:
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-14
14:10:06 UTC (rev 15250)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/actions/OpenFileActionUtils.java 2009-05-14
14:42:10 UTC (rev 15251)
@@ -23,180 +23,268 @@
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.IResource;
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 {
- private static XMLHelper helper = new XMLHelper();
+
+ 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() {}
- private static final String HIBERNATE_TAG_CLASS =
"class"; //$NON-NLS-1$
- private static final String HIBERNATE_TAG_TABLE = "table";
//$NON-NLS-1$
- private static final String HIBERNATE_TAG_SUBCLASS =
"subclass"; //$NON-NLS-1$
- private static final String HIBERNATE_TAG_JOINED_SUBCLASS =
"joined-subclass"; //$NON-NLS-1$
- private static final String HIBERNATE_TAG_UNION_SUBCLASS =
"union-subclass"; //$NON-NLS-1$
- private static final String HIBERNATE_TAG_NAME = "name"; //$NON-NLS-1$
- private static final String HIBERNATE_TAG_ENTITY_NAME =
"entity-name"; //$NON-NLS-1$
- private static final String HIBERNATE_TAG_SESSION_FACTORY =
"session-factory"; //$NON-NLS-1$
- private static final String HIBERNATE_TAG_MAPPING =
"mapping"; //$NON-NLS-1$
- private static final String HIBERNATE_TAG_RESOURCE =
"resource"; //$NON-NLS-1$
- private static final String HIBERNATE_TAG_CATALOG =
"catalog"; //$NON-NLS-1$
- private static final String HIBERNATE_TAG_SCHEMA =
"schema"; //$NON-NLS-1$
-
- 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();
}
- public static IEditorPart openEditor(IWorkbenchPage page, IResource resource) throws
PartInitException {
- return IDE.openEditor(page, (IFile) resource);
+ /**
+ * 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());
+ }
- public static boolean rootClassHasAnnotations(ConsoleConfiguration consoleConfiguration,
PersistentClass rootClass) {
+ /**
+ * 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;
}
- Document doc = getDocument(consoleConfiguration, configXMLFile);
+ EntityResolver entityResolver =
consoleConfiguration.getConfiguration().getEntityResolver();
+ Document doc = getDocument(configXMLFile, entityResolver);
return getElements(doc, HIBERNATE_TAG_MAPPING, HIBERNATE_TAG_CLASS,
getPersistentClassName(rootClass)).hasNext();
}
- static String getPersistentClassName(PersistentClass rootClass) {
- if (rootClass == null) {
- return ""; //$NON-NLS-1$
- } else {
- return rootClass.getEntityName() != null ? rootClass.getEntityName() :
rootClass.getClassName();
- }
- }
-
- private static String getTableName(String catalog, String schema, String name) {
- return (catalog != null ? catalog + '.' : "") + (schema != null ?
schema + '.' : "") + name; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- private static String getTableName(Table table) {
- return getTableName(table.getCatalog(), table.getSchema(), table.getName());
- }
-
-
- private static boolean elementInResource(ConsoleConfiguration consoleConfiguration,
IResource resource, Object element) {
+ /**
+ * 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 = rootClassInResource(consoleConfiguration, resource, (RootClass)element);
+ res = rootClassInFile(consoleConfiguration, file, (RootClass)element);
} else if (element instanceof Subclass) {
- res = subclassInResource(consoleConfiguration, resource, (Subclass)element);
+ res = subclassInFile(consoleConfiguration, file, (Subclass)element);
} else if (element instanceof Table) {
- res = tableInResource(consoleConfiguration, resource, (Table)element);
+ 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, },
+ };
- // TODO: this is *extremely* inefficient - no need to scan the whole tree again and
again.
- private static boolean rootClassInResource(ConsoleConfiguration consoleConfiguration,
IResource resource, RootClass persistentClass) {
- Document doc = getDocument(consoleConfiguration, resource.getLocation().toFile());
- return getElements(doc, OpenFileActionUtils.HIBERNATE_TAG_CLASS, HIBERNATE_TAG_NAME,
StringHelper.unqualify(getPersistentClassName(persistentClass))).hasNext() ||
- getElements(doc, OpenFileActionUtils.HIBERNATE_TAG_CLASS, HIBERNATE_TAG_NAME,
getPersistentClassName(persistentClass)).hasNext() ||
- getElements(doc, OpenFileActionUtils.HIBERNATE_TAG_CLASS, HIBERNATE_TAG_ENTITY_NAME,
StringHelper.unqualify(getPersistentClassName(persistentClass))).hasNext() ||
- getElements(doc, OpenFileActionUtils.HIBERNATE_TAG_CLASS, HIBERNATE_TAG_ENTITY_NAME,
getPersistentClassName(persistentClass)).hasNext();
+ /**
+ * 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, },
+ };
- // TODO: this is *extremely* inefficient - no need to scan the whole tree again and
again.
- private static boolean subclassInResource(ConsoleConfiguration consoleConfiguration,
IResource resource, Subclass persistentClass) {
- Document doc = getDocument(consoleConfiguration, resource.getLocation().toFile());
- return getElements(doc, HIBERNATE_TAG_SUBCLASS, HIBERNATE_TAG_NAME,
StringHelper.unqualify(getPersistentClassName(persistentClass))).hasNext() ||
- getElements(doc, HIBERNATE_TAG_SUBCLASS, HIBERNATE_TAG_NAME,
getPersistentClassName(persistentClass)).hasNext() ||
- getElements(doc, HIBERNATE_TAG_SUBCLASS, HIBERNATE_TAG_ENTITY_NAME,
StringHelper.unqualify(getPersistentClassName(persistentClass))).hasNext() ||
- getElements(doc, HIBERNATE_TAG_SUBCLASS, HIBERNATE_TAG_ENTITY_NAME,
getPersistentClassName(persistentClass)).hasNext() ||
-
- getElements(doc, HIBERNATE_TAG_JOINED_SUBCLASS, HIBERNATE_TAG_NAME,
StringHelper.unqualify(getPersistentClassName(persistentClass))).hasNext() ||
- getElements(doc, HIBERNATE_TAG_JOINED_SUBCLASS, HIBERNATE_TAG_NAME,
getPersistentClassName(persistentClass)).hasNext() ||
- getElements(doc, HIBERNATE_TAG_JOINED_SUBCLASS, HIBERNATE_TAG_ENTITY_NAME,
StringHelper.unqualify(getPersistentClassName(persistentClass))).hasNext() ||
- getElements(doc, HIBERNATE_TAG_JOINED_SUBCLASS, HIBERNATE_TAG_ENTITY_NAME,
getPersistentClassName(persistentClass)).hasNext() ||
-
- getElements(doc, HIBERNATE_TAG_UNION_SUBCLASS, HIBERNATE_TAG_NAME,
StringHelper.unqualify(getPersistentClassName(persistentClass))).hasNext() ||
- getElements(doc, HIBERNATE_TAG_UNION_SUBCLASS, HIBERNATE_TAG_NAME,
getPersistentClassName(persistentClass)).hasNext() ||
- getElements(doc, HIBERNATE_TAG_UNION_SUBCLASS, HIBERNATE_TAG_ENTITY_NAME,
StringHelper.unqualify(getPersistentClassName(persistentClass))).hasNext() ||
- getElements(doc, HIBERNATE_TAG_UNION_SUBCLASS, HIBERNATE_TAG_ENTITY_NAME,
getPersistentClassName(persistentClass)).hasNext();
+ /**
+ * 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;
}
- private static boolean tableInResource(ConsoleConfiguration consoleConfiguration,
IResource resource, Table table) {
- Document doc = getDocument(consoleConfiguration, resource.getLocation().toFile());
-
- Iterator classes = getElements(doc, OpenFileActionUtils.HIBERNATE_TAG_CLASS);
+ /**
+ * 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 = (Element) classes.next();
-
- Attribute tableAttr = element.attribute( HIBERNATE_TAG_TABLE );
+ Element 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);
- if (
- getTableName(
- (catalogAttr != null ? catalogAttr.getValue() : null),
- (schemaAttr != null ? schemaAttr.getValue() : null),
- tableAttr.getValue()
- ).equals(getTableName(table))
- ) {
- return true;
+ 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);
+ 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)) {
- return true;
+ res = true;
+ break;
}
}
}
-
- if (getElements(doc, HIBERNATE_TAG_TABLE, table.getName()).hasNext()) {
- return true;
+ if (!res && getElements(doc, HIBERNATE_TAG_TABLE, table.getName()).hasNext())
{
+ res = true;
}
-
- return false;
+ return res;
}
- private static Iterator getElements(Document doc, String elementName) {
+ private static Iterator<Element> getElements(Document doc, String elementName) {
return getElements(doc, elementName, null, null);
}
- private static Iterator getElements(Document doc, String attrName, String attrValue) {
+ private static Iterator<Element> getElements(Document doc, String attrName, String
attrValue) {
return getElements(doc, null, attrName, attrValue);
}
- private static Iterator getElements(Document doc, String elementName, String attrName,
String attrValue) {
+ private static Iterator<Element> getElements(Document doc, String elementName,
String attrName, String attrValue) {
LVS visitor = new LVS(elementName, attrName, attrValue);
- doc.accept( visitor );
+ doc.accept(visitor);
return visitor.iterator();
}
- static class LVS extends VisitorSupport {
+ private static class LVS extends VisitorSupport {
private String nodeName;
private String attrName;
private String attrValue;
- private List ret = new ArrayList();
+ private List<Element> ret = new ArrayList<Element>();
public LVS(String nodeName, String attrName, String attrValue) {
super();
@@ -208,14 +296,14 @@
public void visit(Element element) {
if (nodeName == null) {
if (attrName != null && attrValue != null) {
- if (attrIsCorrect(element, attrName, attrValue)) {
+ if (inspectAttributeForValue(element, attrName, attrValue)) {
ret.add(element);
}
}
} else {
if (nodeName.equals(element.getName())) {
if (attrName != null) {
- if (attrIsCorrect(element, attrName, attrValue)) {
+ if (inspectAttributeForValue(element, attrName, attrValue)) {
ret.add(element);
}
} else {
@@ -223,111 +311,402 @@
}
}
}
-
}
- public Iterator iterator() {
+ public Iterator<Element> iterator() {
return ret.iterator();
}
- }
- private static boolean attrIsCorrect(Element element, String attrName, String attrValue)
{
- Attribute attr = element.attribute(attrName);
- if (attr != null && attrValue.equals(attr.getValue())) {
- return attrValue.equals(attr.getValue());
+ 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;
}
- return false;
}
- public static Document getDocument(ConsoleConfiguration consoleConfiguration,
java.io.File configXMLFile) {
+ /**
+ * 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 (consoleConfiguration != null && configXMLFile != null) {
- InputStream stream = null;
- try {
- stream = new FileInputStream( configXMLFile );
- } catch (FileNotFoundException e) {
- HibernateConsolePlugin.getDefault().logErrorMessage("Configuration file not
found", e); //$NON-NLS-1$
+ 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 errors = new ArrayList();
+ 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 {
- List errors = new ArrayList();
- doc = helper.createSAXReader( configXMLFile.getPath(), errors,
consoleConfiguration.getConfiguration().getEntityResolver() )
- .read( new InputSource( stream ) );
- if ( errors.size() != 0 ) {
- HibernateConsolePlugin.getDefault().logErrorMessage("invalid
configuration", (Throwable)null); //$NON-NLS-1$
- }
+ stream.close();
}
- catch (DocumentException e) {
- HibernateConsolePlugin.getDefault().logErrorMessage("Could not parse
configuration", e); //$NON-NLS-1$
+ catch (IOException ioe) {
+ HibernateConsolePlugin.getDefault().logErrorMessage("could not close input
stream for", ioe); //$NON-NLS-1$
}
- finally {
- try {
- stream.close();
- }
- catch (IOException ioe) {
- HibernateConsolePlugin.getDefault().logErrorMessage("could not close input
stream for", ioe); //$NON-NLS-1$
- }
- }
}
return doc;
}
- public static IResource getResource(ConsoleConfiguration consoleConfiguration,
IJavaProject proj, Object element) {
- IResource resource = null;
- if (consoleConfiguration == null) {
- return resource;
+ /**
+ * Trying to find hibernate console config mapping file,
+ * which is corresponding to provided element.
+ *
+ * @param consoleConfiguration
+ * @param proj
+ * @param element
+ * @return
+ */
+ 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();
- Document doc = getDocument(consoleConfiguration, configXMLFile);
- if (proj != null && doc != null) {
- Element sfNode = doc.getRootElement().element( HIBERNATE_TAG_SESSION_FACTORY );
- Iterator elements = sfNode.elements(HIBERNATE_TAG_MAPPING).iterator();
- while (elements.hasNext() && resource == null) {
- Element subelement = (Element) elements.next();
- Attribute file = subelement.attribute( HIBERNATE_TAG_RESOURCE );
- if (file != null) {
- try {
- IPackageFragmentRoot[] packageFragmentRoots =
- proj.getAllPackageFragmentRoots();
- for (int i = 0; i < packageFragmentRoots.length; i++) {
- //search in source folders.
- if (packageFragmentRoots[i].getClass() == PackageFragmentRoot.class) {
- IPackageFragmentRoot packageFragmentRoot = packageFragmentRoots[i];
- IPath path = packageFragmentRoot.getPath().append(file.getValue());
- resource = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
- if (resource != null) {
- if (resource.exists() && elementInResource(consoleConfiguration,
resource, element)) {
- break;
- }
- else {
- resource = null;
- }
- }
- }
- }
- } catch (JavaModelException e) {
- resource = null;
- HibernateConsolePlugin.getDefault().logErrorMessage(HibernateConsoleMessages.OpenFileActionUtils_problems_while_get_project_package_fragment_roots,
e);
- }
+ 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 elements = sfNode.elements(HIBERNATE_TAG_MAPPING).iterator();
+ while (elements.hasNext() && file == null) {
+ Element subelement = (Element)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;
}
}
- if (resource == null) {
- java.io.File[] files = consoleConfiguration.getPreferences().getMappingFiles();
- for (int i = 0; i < files.length; i++) {
- java.io.File file = files[i];
- if (file != null) {
- resource = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(new
Path(file.getPath()));
- if (resource != null) {
- if (resource.exists() && elementInResource(consoleConfiguration, resource,
element)) {
- break;
- }
- else {
- resource = 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 = (ITextEditor[])testEditors.toArray(res);
+ } else if (editorPart instanceof ITextEditor){
+ res = new ITextEditor[]{(ITextEditor) editorPart};
}
- return resource;
+ 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-14
14:10:06 UTC (rev 15250)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/actions/OpenMappingAction.java 2009-05-14
14:42:10 UTC (rev 15251)
@@ -11,17 +11,12 @@
package org.hibernate.eclipse.console.actions;
import java.io.FileNotFoundException;
-import java.util.ArrayList;
-import java.util.List;
import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaModelException;
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.jface.viewers.IStructuredSelection;
@@ -31,7 +26,6 @@
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.SelectionListenerAction;
-import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.texteditor.ITextEditor;
import org.hibernate.console.ConsoleConfiguration;
import org.hibernate.eclipse.console.HibernateConsoleMessages;
@@ -41,53 +35,53 @@
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.RootClass;
-import org.hibernate.mapping.Subclass;
-import org.hibernate.tool.hbm2x.Cfg2HbmTool;
/**
+ * Open Mapping File action
+ *
* @author Dmitry Geraskov
+ * @author Vitali Yemialyanchyk
*/
-
public class OpenMappingAction extends SelectionListenerAction {
- private static final String HIBERNATE_TAG_NAME = "name"; //$NON-NLS-1$
- private static final String HIBERNATE_TAG_ENTITY_NAME = "entity-name";
//$NON-NLS-1$
- private String imageFilePath = "icons/images/mapping.gif"; //$NON-NLS-1$
+ private final String imageFilePath = "icons/images/mapping.gif";
//$NON-NLS-1$
public OpenMappingAction() {
super(HibernateConsoleMessages.OpenMappingAction_open_mapping_file);
setToolTipText(HibernateConsoleMessages.OpenMappingAction_open_mapping_file);
- setEnabled( true );
+ setEnabled(true);
setImageDescriptor(HibernateConsolePlugin.getImageDescriptor(imageFilePath ));
}
public void run() {
IStructuredSelection sel = getStructuredSelection();
- if (sel instanceof TreeSelection){
- for (int i = 0; i < ((TreeSelection)sel).getPaths().length; i++) {
- TreePath path = ((TreeSelection)sel).getPaths()[i];
- ConsoleConfiguration consoleConfiguration =
(ConsoleConfiguration)(path.getSegment(0));
- try {
- run(path, consoleConfiguration);
- } catch (JavaModelException e) {
- HibernateConsolePlugin.getDefault().logErrorMessage(HibernateConsoleMessages.OpenMappingAction_cannot_find_mapping_file,
e);
- } catch (PartInitException e) {
- HibernateConsolePlugin.getDefault().logErrorMessage(HibernateConsoleMessages.OpenMappingAction_cannot_open_mapping_file,
e);
- } catch (FileNotFoundException e) {
- HibernateConsolePlugin.getDefault().logErrorMessage(HibernateConsoleMessages.OpenMappingAction_cannot_find_mapping_file,
e);
- }
+ if (!(sel instanceof TreeSelection)) {
+ return;
+ }
+ TreePath[] paths = ((TreeSelection)sel).getPaths();
+ for (int i = 0; i < paths.length; i++) {
+ TreePath path = paths[i];
+ ConsoleConfiguration consoleConfiguration =
(ConsoleConfiguration)(path.getSegment(0));
+ try {
+ run(path, consoleConfiguration);
+ } catch (JavaModelException e) {
+ HibernateConsolePlugin.getDefault().logErrorMessage(HibernateConsoleMessages.OpenMappingAction_cannot_find_mapping_file,
e);
+ } catch (PartInitException e) {
+ HibernateConsolePlugin.getDefault().logErrorMessage(HibernateConsoleMessages.OpenMappingAction_cannot_open_mapping_file,
e);
+ } catch (FileNotFoundException e) {
+ HibernateConsolePlugin.getDefault().logErrorMessage(HibernateConsoleMessages.OpenMappingAction_cannot_find_mapping_file,
e);
}
}
}
public static IEditorPart run(TreePath path, ConsoleConfiguration consoleConfiguration)
throws PartInitException, JavaModelException, FileNotFoundException {
boolean isPropertySel = (path.getLastSegment().getClass() == Property.class);
- if (isPropertySel){
+ if (isPropertySel) {
Property propertySel = (Property)path.getLastSegment();
PersistentClass persClass = propertySel.getPersistentClass();
- if ( persClass == null
+ if (persClass == null
|| (RootClass.class.isAssignableFrom(persClass.getClass())
- && persClass.getClass() != RootClass.class)){
+ && persClass.getClass() != RootClass.class)) {
Property parentProp = (Property)path.getParentPath().getLastSegment();
return run(propertySel, parentProp, consoleConfiguration);
}
@@ -106,22 +100,22 @@
public static IEditorPart run(Object selection, ConsoleConfiguration
consoleConfiguration) throws PartInitException, JavaModelException, FileNotFoundException
{
IEditorPart editorPart = null;
IJavaProject proj = ProjectUtils.findJavaProject(consoleConfiguration);
- IResource resource = null;
+ IFile file = null;
if (selection instanceof Property) {
Property p = (Property)selection;
if (p.getPersistentClass() != null) {
//use PersistentClass to open editor
- resource = OpenFileActionUtils.getResource(consoleConfiguration, proj,
p.getPersistentClass());
+ file = OpenFileActionUtils.searchFileToOpen(consoleConfiguration, proj,
p.getPersistentClass());
//editorPart = openMapping(p.getPersistentClass(), consoleConfiguration);
}
}
else {
- resource = OpenFileActionUtils.getResource(consoleConfiguration, proj, selection);
+ file = OpenFileActionUtils.searchFileToOpen(consoleConfiguration, proj, selection);
//editorPart = openMapping(selection, consoleConfiguration);
}
- if (resource != null) {
- editorPart = openMapping(resource);
- applySelectionToEditor(selection, editorPart);
+ if (file != null) {
+ editorPart = OpenFileActionUtils.openFileInEditor(file);
+ updateEditorSelection(editorPart, selection);
}
if (editorPart == null) {
//try to find hibernate-annotations
@@ -136,9 +130,9 @@
}
}
if (rootClass != null){
- if (OpenFileActionUtils.rootClassHasAnnotations(consoleConfiguration, rootClass)) {
+ if (OpenFileActionUtils.hasConfigXMLMappingClassAnnotation(consoleConfiguration,
rootClass)) {
String fullyQualifiedName = rootClass.getClassName();
- editorPart = OpenSourceAction.run(selection, proj, fullyQualifiedName);
+ editorPart = OpenSourceAction.run(selection, proj, fullyQualifiedName);
}
}
else {
@@ -150,38 +144,6 @@
}
/**
- * @param selection
- * @param editorPart
- */
- static public boolean applySelectionToEditor(Object selection, IEditorPart editorPart)
{
- ITextEditor[] textEditors = getTextEditors(editorPart);
- if (textEditors.length == 0) {
- return false;
- }
- textEditors[0].selectAndReveal(0, 0);
- FindReplaceDocumentAdapter findAdapter = null;
- ITextEditor textEditor = null;
- for (int i = 0; i < textEditors.length && findAdapter == null; i++) {
- textEditor = textEditors[i];
- findAdapter = getFindDocAdapter(textEditor);
- }
- if (findAdapter == null) {
- return false;
- }
- IRegion selectRegion = null;
- if (selection instanceof RootClass || selection instanceof Subclass) {
- selectRegion = findSelection((PersistentClass)selection, findAdapter);
- } else if (selection instanceof Property){
- selectRegion = findSelection((Property)selection, findAdapter);
- }
- if (selectRegion != null){
- textEditor.selectAndReveal(selectRegion.getOffset(), selectRegion.getLength());
- return true;
- }
- return false;
- }
-
- /**
* @param compositeProperty
* @param parentProperty
* @param consoleConfiguration
@@ -193,14 +155,14 @@
public static IEditorPart run(Property compositeProperty, Property parentProperty,
ConsoleConfiguration consoleConfiguration) throws PartInitException, JavaModelException,
FileNotFoundException{
PersistentClass rootClass = parentProperty.getPersistentClass();
IJavaProject proj = ProjectUtils.findJavaProject(consoleConfiguration);
- IResource resource = OpenFileActionUtils.getResource(consoleConfiguration, proj,
rootClass);
+ IFile file = OpenFileActionUtils.searchFileToOpen(consoleConfiguration, proj,
rootClass);
IEditorPart editorPart = null;
- if (resource != null){
- editorPart = openMapping(resource);
- updateEditorSelection(compositeProperty, parentProperty, editorPart);
+ if (file != null){
+ editorPart = OpenFileActionUtils.openFileInEditor(file);
+ updateEditorSelection(editorPart, compositeProperty, parentProperty);
}
if (editorPart == null && parentProperty.isComposite()) {
- if (OpenFileActionUtils.rootClassHasAnnotations(consoleConfiguration, rootClass)) {
+ if (OpenFileActionUtils.hasConfigXMLMappingClassAnnotation(consoleConfiguration,
rootClass)) {
String fullyQualifiedName =((Component)((Property)
parentProperty).getValue()).getComponentClassName();
editorPart = OpenSourceAction.run(compositeProperty, proj, fullyQualifiedName);
}
@@ -213,12 +175,39 @@
}
/**
+ * @param editorPart
+ * @param selection
+ */
+ public static boolean updateEditorSelection(IEditorPart editorPart, Object selection) {
+ ITextEditor[] textEditors = OpenFileActionUtils.getTextEditors(editorPart);
+ if (textEditors.length == 0) {
+ return false;
+ }
+ textEditors[0].selectAndReveal(0, 0);
+ FindReplaceDocumentAdapter findAdapter = null;
+ ITextEditor textEditor = null;
+ for (int i = 0; i < textEditors.length && findAdapter == null; i++) {
+ textEditor = textEditors[i];
+ findAdapter = OpenFileActionUtils.createFindDocAdapter(textEditor);
+ }
+ if (findAdapter == null) {
+ return false;
+ }
+ IRegion selectRegion = OpenFileActionUtils.findSelectRegion(findAdapter, selection);
+ if (selectRegion != null) {
+ textEditor.selectAndReveal(selectRegion.getOffset(), selectRegion.getLength());
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * @param editorPart
* @param compositeProperty
* @param parentProperty
- * @param editorPart
*/
- static public boolean updateEditorSelection(Property compositeProperty, Property
parentProperty, IEditorPart editorPart) {
- ITextEditor[] textEditors = getTextEditors(editorPart);
+ public static boolean updateEditorSelection(IEditorPart editorPart, Property
compositeProperty, Property parentProperty) {
+ ITextEditor[] textEditors = OpenFileActionUtils.getTextEditors(editorPart);
if (textEditors.length == 0) {
return false;
}
@@ -227,28 +216,30 @@
ITextEditor textEditor = null;
for (int i = 0; i < textEditors.length && findAdapter == null; i++) {
textEditor = textEditors[i];
- findAdapter = getFindDocAdapter(textEditor);
+ findAdapter = OpenFileActionUtils.createFindDocAdapter(textEditor);
}
if (findAdapter == null) {
return false;
}
- IRegion parentRegion = findSelection(parentProperty, findAdapter);
+ IRegion parentRegion = OpenFileActionUtils.findSelectRegion(findAdapter,
parentProperty);
if (parentRegion == null) {
return false;
}
+ int startOffset = parentRegion.getOffset() + parentRegion.getLength();
IRegion propRegion = null;
try {
- propRegion = findAdapter.find(parentRegion.getOffset()+parentRegion.getLength(),
generatePattern(compositeProperty), true, true, false, true);
+ final String hbmPropertyPattern =
OpenFileActionUtils.generateHbmPropertyPattern(compositeProperty);
+ propRegion = findAdapter.find(startOffset, hbmPropertyPattern, true, true, false,
true);
PersistentClass rootClass = parentProperty.getPersistentClass();
if (propRegion == null && parentProperty.isComposite()
&& rootClass.getIdentifierProperty() == parentProperty) {
// try to use key-property
- String pattern =
generatePattern(compositeProperty).replaceFirst("<property",
"<key-property"); //$NON-NLS-1$ //$NON-NLS-2$
- propRegion = findAdapter.find(parentRegion.getOffset()+parentRegion.getLength(),
pattern, true, true, false, true);
+ String pattern = hbmPropertyPattern.replaceFirst("<property",
"<key-property"); //$NON-NLS-1$ //$NON-NLS-2$
+ propRegion = findAdapter.find(startOffset, pattern, true, true, false, true);
if (propRegion == null) {
// try to use key-many-to-one
- pattern =
generatePattern(compositeProperty).replaceFirst("<many-to-one",
"<key-many-to-one"); //$NON-NLS-1$ //$NON-NLS-2$
- propRegion = findAdapter.find(parentRegion.getOffset()+parentRegion.getLength(),
pattern, true, true, false, true);
+ pattern = hbmPropertyPattern.replaceFirst("<many-to-one",
"<key-many-to-one"); //$NON-NLS-1$ //$NON-NLS-2$
+ propRegion = findAdapter.find(startOffset, pattern, true, true, false, true);
}
}
} catch (BadLocationException e) {
@@ -263,181 +254,4 @@
textEditor.selectAndReveal(propRegion.getOffset(), propRegion.getLength());
return true;
}
-
- /**
- * @param textEditor
- * @return
- */
- private static FindReplaceDocumentAdapter getFindDocAdapter(
- ITextEditor textEditor) {
- IDocument document = null;
- if (textEditor.getDocumentProvider() != null){
- document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
- }
- if (document == null) {
- return null;
- }
- FindReplaceDocumentAdapter findAdapter = new FindReplaceDocumentAdapter(document);
- return findAdapter;
- }
-
- static public IEditorPart openMapping(IResource resource) {
- IEditorPart editorPart = null;
- if (resource != null && resource instanceof IFile){
- try {
- editorPart =
OpenFileActionUtils.openEditor(HibernateConsolePlugin.getDefault().getActiveWorkbenchWindow().getActivePage(),
(IFile) resource);
- } catch (PartInitException e) {
- // ignore
- }
- } else {
-
HibernateConsolePlugin.getDefault().log(HibernateConsoleMessages.OpenMappingAction_cannot_open_mapping_file
+ resource);
- }
- return editorPart;
- }
-
- public static IRegion findSelection(Property property, FindReplaceDocumentAdapter
findAdapter) {
- Assert.isNotNull(property.getPersistentClass());
- IRegion classRegion = findSelection(property.getPersistentClass(), findAdapter);
- if (classRegion == null) {
- return null;
- }
- IRegion finalRegion = null;
- IRegion propRegion = null;
- try {
- finalRegion = findAdapter.find(classRegion.getOffset()+classRegion.getLength(),
"</class", true, true, false, false); //$NON-NLS-1$
- propRegion = findAdapter.find(classRegion.getOffset()+classRegion.getLength(),
generatePattern(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;
- }
- public static IRegion findSelection(PersistentClass persClass,
- FindReplaceDocumentAdapter findAdapter) {
- IRegion res = null;
- try {
- String[] classPatterns = generatePatterns(persClass);
- IRegion classRegion = null;
- for (int i = 0; (classRegion == null) && (i < classPatterns.length); i++){
- classRegion = findAdapter.find(0, classPatterns[i], true, true, false, true);
- }
- if (classRegion != null) {
- int length = persClass.getNodeName().length();
- int offset = classRegion.getOffset() + classRegion.getLength() - length - 1;
- res = new Region(offset, length);
- }
- } catch (BadLocationException e) {
- //ignore
- }
- return res;
- }
-
- private static String[] generatePatterns(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);
-
- Cfg2HbmTool tool = new Cfg2HbmTool();
- String[] patterns = new String[4];
- StringBuffer pattern = new StringBuffer("<"); //$NON-NLS-1$
- pattern.append(tool.getTag(persClass));
- pattern.append("[\\s]+[.[^>]]*"); //$NON-NLS-1$
- pattern.append(HIBERNATE_TAG_NAME);
- pattern.append("[\\s]*=[\\s]*\""); //$NON-NLS-1$
- pattern.append(shortClassName);
- pattern.append('\"');
- patterns[0] = pattern.toString();
-
- pattern = new StringBuffer("<"); //$NON-NLS-1$
- pattern.append(tool.getTag(persClass));
- pattern.append("[\\s]+[.[^>]]*"); //$NON-NLS-1$
- pattern.append(HIBERNATE_TAG_NAME);
- pattern.append("[\\s]*=[\\s]*\""); //$NON-NLS-1$
- pattern.append(fullClassName);
- pattern.append('\"');
- patterns[1] = pattern.toString();
-
- pattern = new StringBuffer("<"); //$NON-NLS-1$
- pattern.append(tool.getTag(persClass));
- pattern.append("[\\s]+[.[^>]]*"); //$NON-NLS-1$
- pattern.append(HIBERNATE_TAG_ENTITY_NAME);
- pattern.append("[\\s]*=[\\s]*\""); //$NON-NLS-1$
- pattern.append(shortClassName);
- pattern.append('\"');
- patterns[2] = pattern.toString();
-
- pattern = new StringBuffer("<"); //$NON-NLS-1$
- pattern.append(tool.getTag(persClass));
- pattern.append("[\\s]+[.[^>]]*"); //$NON-NLS-1$
- pattern.append(HIBERNATE_TAG_ENTITY_NAME);
- pattern.append("[\\s]*=[\\s]*\""); //$NON-NLS-1$
- pattern.append(fullClassName);
- pattern.append('\"');
- patterns[3] = pattern.toString();
- return patterns;
- }
-
- private static String generatePattern(Property property){
- Cfg2HbmTool tool = new Cfg2HbmTool();
- StringBuffer pattern = new StringBuffer("<"); //$NON-NLS-1$
- if(property.getPersistentClass() != null &&
- property.getPersistentClass().getIdentifierProperty()==property) {
- if (property.isComposite()){
- pattern.append("composite-id"); //$NON-NLS-1$
- } else {
- pattern.append("id"); //$NON-NLS-1$
- }
- } else{
- String toolTag = tool.getTag(property);
- if ("component".equals(toolTag) &&
"embedded".equals(property.getPropertyAccessorName())){
//$NON-NLS-1$//$NON-NLS-2$
- toolTag = "properties"; //$NON-NLS-1$
- }
- pattern.append(toolTag);
- }
- pattern.append("[\\s]+[.[^>]]*"); //$NON-NLS-1$
- pattern.append(HIBERNATE_TAG_NAME);
- pattern.append("[\\s]*=[\\s]*\""); //$NON-NLS-1$
- pattern.append(property.getName());
- pattern.append('\"');
- return pattern.toString();
- }
-
- /**
- * Method gets all ITextEditors from IEditorPart.
- * Never returns null.
- * @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 testEditors = new ArrayList();
- IEditorPart[] editors = ((MultiPageEditorPart)
editorPart).findEditors(editorPart.getEditorInput());
- for (int i = 0; i < editors.length; i++) {
- if (editors[i] instanceof ITextEditor){
- testEditors.add(editors[i]);
- }
- }
- res = (ITextEditor[])testEditors.toArray(res);
- } else if (editorPart instanceof ITextEditor){
- res = new ITextEditor[]{(ITextEditor) editorPart};
- }
- 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-14
14:10:06 UTC (rev 15250)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/internal/CriteriaQuickAssistProcessor.java 2009-05-14
14:42:10 UTC (rev 15251)
@@ -39,7 +39,7 @@
import org.eclipse.ui.texteditor.ITextEditor;
import org.hibernate.console.ImageConstants;
import org.hibernate.eclipse.console.HibernateConsolePlugin;
-import org.hibernate.eclipse.console.actions.OpenMappingAction;
+import org.hibernate.eclipse.console.actions.OpenFileActionUtils;
import org.hibernate.eclipse.console.utils.EclipseImages;
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 = OpenMappingAction.getTextEditors(editorPart);
+ ITextEditor[] textEditors = OpenFileActionUtils.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-14
14:10:06 UTC (rev 15250)
+++
trunk/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/internal/HQLQuickAssistProcessor.java 2009-05-14
14:42:10 UTC (rev 15251)
@@ -32,7 +32,7 @@
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.texteditor.ITextEditor;
import org.hibernate.console.ImageConstants;
-import org.hibernate.eclipse.console.actions.OpenMappingAction;
+import org.hibernate.eclipse.console.actions.OpenFileActionUtils;
import org.hibernate.eclipse.console.utils.EclipseImages;
import org.hibernate.eclipse.jdt.ui.Activator;
@@ -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 = OpenMappingAction.getTextEditors(editorPart);
+ ITextEditor[] textEditors = OpenFileActionUtils.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);