Author: vyemialyanchyk
Date: 2010-03-17 08:09:59 -0400 (Wed, 17 Mar 2010)
New Revision: 20874
Added:
branches/hibernatetools-multiversion/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/actions/ExternalProcessAction.java
branches/hibernatetools-multiversion/hibernatetools/plugins/org.hibernate.eclipse/src/org/hibernate/console/stubs/SessionStub.java
branches/hibernatetools-multiversion/hibernatetools/plugins/org.hibernate.eclipse/src/org/hibernate/console/stubs/SessionStubFactory.java
Modified:
branches/hibernatetools-multiversion/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/ConfigurationActor.java
branches/hibernatetools-multiversion/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/KnownConfigurationsTest.java
Log:
https://jira.jboss.org/jira/browse/JBIDE-6070 - update
Added:
branches/hibernatetools-multiversion/hibernatetools/plugins/org.hibernate.eclipse/src/org/hibernate/console/stubs/SessionStub.java
===================================================================
---
branches/hibernatetools-multiversion/hibernatetools/plugins/org.hibernate.eclipse/src/org/hibernate/console/stubs/SessionStub.java
(rev 0)
+++
branches/hibernatetools-multiversion/hibernatetools/plugins/org.hibernate.eclipse/src/org/hibernate/console/stubs/SessionStub.java 2010-03-17
12:09:59 UTC (rev 20874)
@@ -0,0 +1,356 @@
+package org.hibernate.console.stubs;
+
+import java.sql.Time;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.ui.views.properties.IPropertyDescriptor;
+import org.eclipse.ui.views.properties.PropertyDescriptor;
+import org.hibernate.Criteria;
+import org.hibernate.EntityMode;
+import org.hibernate.Session;
+import org.hibernate.Query;
+import org.hibernate.HibernateException;
+import org.hibernate.SessionFactory;
+import org.hibernate.console.ConsoleMessages;
+import org.hibernate.console.ConsoleQueryParameter;
+import org.hibernate.console.QueryInputModel;
+import org.hibernate.console.execution.ExecutionContext;
+import org.hibernate.console.execution.ExecutionContext.Command;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.metadata.ClassMetadata;
+import org.hibernate.metadata.CollectionMetadata;
+import org.hibernate.proxy.HibernateProxyHelper;
+import org.hibernate.type.Type;
+
+import bsh.EvalError;
+import bsh.Interpreter;
+
+public class SessionStub {
+
+ protected ExecutionContext executionContext;
+ protected Session session;
+
+ protected SessionStub(ExecutionContext executionContext, Session session) {
+ this.executionContext = executionContext;
+ this.session = session;
+ }
+
+ public boolean isOpen() {
+ boolean res = false;
+ if (session != null) {
+ res = session.isOpen();
+ }
+ return res;
+ }
+
+ public void close(List<Throwable> exceptions) {
+ if (session != null && session.isOpen()) {
+ try {
+ session.close();
+ } catch (HibernateException e) {
+ exceptions.add(e);
+ }
+ }
+ }
+
+ public boolean contains(Object obj) {
+ boolean res = false;
+ if (session != null) {
+ res = session.contains(obj);
+ }
+ return res;
+ }
+
+ public boolean hasMetaData(Object obj) {
+ boolean res = false;
+ if (session != null) {
+ res = session.getSessionFactory().getClassMetadata(
+ HibernateProxyHelper.getClassWithoutInitializingProxy(obj)) != null;
+ }
+ return res;
+ }
+
+ public boolean hasMetaData(Object obj, List<Throwable> exceptions) {
+ boolean res = false;
+ if (session != null) {
+ try {
+ res = session.getSessionFactory().getClassMetadata(
+ HibernateProxyHelper.getClassWithoutInitializingProxy(obj)) != null;
+ } catch (HibernateException e) {
+ exceptions.add(e);
+ }
+ }
+ return res;
+ }
+
+ public String getEntityName(Object obj) {
+ String res = null;
+ if (session != null) {
+ res = session.getEntityName(obj);
+ }
+ return res;
+ }
+
+ public String getEntityName(Object obj, List<Throwable> exceptions) {
+ String res = null;
+ if (session != null) {
+ try {
+ res = session.getEntityName(obj);
+ } catch (HibernateException e) {
+ exceptions.add(e);
+ }
+ }
+ return res;
+ }
+
+ public Object getPropertyValue(Object obj, Object id) {
+ Object pv = null;
+ if (session != null) {
+ SessionFactory sf = session.getSessionFactory();
+ ClassMetadata classMetadata;
+ if (session.isOpen()) {
+ classMetadata = sf.getClassMetadata(session.getEntityName(obj));
+ } else {
+ classMetadata = sf.getClassMetadata(HibernateProxyHelper
+ .getClassWithoutInitializingProxy(obj));
+ }
+ if (id.equals(classMetadata.getIdentifierPropertyName())) {
+ pv = classMetadata.getIdentifier(obj, EntityMode.POJO);
+ } else {
+ pv = classMetadata.getPropertyValue(obj, (String) id, EntityMode.POJO);
+ }
+ if (pv instanceof Collection<?>) {
+ CollectionMetadata collectionMetadata = sf.getCollectionMetadata(classMetadata
+ .getEntityName()
+ + "." + id); //$NON-NLS-1$
+ if (collectionMetadata != null) {
+ pv = new CollectionPropertySource((Collection<?>) pv);
+ }
+ }
+ }
+ return pv;
+ }
+
+ public IPropertyDescriptor[] getPropertyDescriptors(final Object obj) {
+ IPropertyDescriptor[] propertyDescriptors = null;
+ if (executionContext != null) {
+ propertyDescriptors = (IPropertyDescriptor[]) executionContext.execute(new Command()
{
+ public Object execute() {
+ SessionFactory sf = session.getSessionFactory();
+ ClassMetadata classMetadata;
+ if (session.isOpen()) {
+ classMetadata = sf.getClassMetadata(session.getEntityName(obj));
+ } else {
+ classMetadata = sf.getClassMetadata(HibernateProxyHelper
+ .getClassWithoutInitializingProxy(obj));
+ }
+ return initializePropertyDescriptors(classMetadata);
+ }
+ });
+ }
+ return propertyDescriptors;
+ }
+
+ protected IPropertyDescriptor[] initializePropertyDescriptors(ClassMetadata
classMetadata) {
+
+ String[] propertyNames = classMetadata.getPropertyNames();
+ int length = propertyNames.length;
+
+ PropertyDescriptor identifier = null;
+
+ if (classMetadata.hasIdentifierProperty()) {
+ identifier = new PropertyDescriptor(classMetadata.getIdentifierPropertyName(),
+ classMetadata.getIdentifierPropertyName());
+ identifier.setCategory(ConsoleMessages.EntityPropertySource_identifier);
+ length++;
+ }
+
+ PropertyDescriptor[] properties = new PropertyDescriptor[length];
+
+ int idx = 0;
+ if (identifier != null) {
+ properties[idx++] = identifier;
+ }
+
+ for (int i = 0; i < propertyNames.length; i++) {
+ PropertyDescriptor prop = new PropertyDescriptor(propertyNames[i], propertyNames[i]);
+ prop.setCategory(ConsoleMessages.EntityPropertySource_properties);
+ properties[i + idx] = prop;
+ }
+
+ return properties;
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<Object> evalCriteria(String criteriaCode, QueryInputModel model, Time
queryTime,
+ List<Throwable> exceptions) {
+ List<Object> res = Collections.emptyList();
+ if (criteriaCode.indexOf("System.exit") >= 0) { // TODO: externalize run
so we don't need this bogus check! //$NON-NLS-1$
+ exceptions.add(new IllegalArgumentException(ConsoleMessages.JavaPage_not_allowed));
+ return res;
+ }
+ try {
+ Interpreter ip = setupInterpreter();
+ final Integer maxResults = model.getMaxResults();
+ long startTime = System.currentTimeMillis();
+ Object o = ip.eval(criteriaCode);
+ // ugly! TODO: make un-ugly!
+ if (o instanceof Criteria) {
+ Criteria criteria = (Criteria) o;
+ if (maxResults != null) {
+ criteria.setMaxResults(maxResults.intValue());
+ }
+ res = criteria.list();
+ } else if (o instanceof List<?>) {
+ res = (List<Object>) o;
+ if (maxResults != null) {
+ res = res.subList(0, Math.min(res.size(), maxResults.intValue()));
+ }
+ } else {
+ res = new ArrayList<Object>();
+ res.add(o);
+ }
+ queryTime.setTime(System.currentTimeMillis() - startTime);
+ } catch (EvalError e) {
+ exceptions.add(e);
+ } catch (HibernateException e) {
+ exceptions.add(e);
+ }
+ return res;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Interpreter setupInterpreter() throws EvalError, HibernateException {
+ Interpreter interpreter = new Interpreter();
+
+ interpreter.set("session", session); //$NON-NLS-1$
+ interpreter.setClassLoader(Thread.currentThread().getContextClassLoader());
+ SessionImplementor si = (SessionImplementor) session;
+
+ Map<String, ?> map = si.getFactory().getAllClassMetadata();
+
+ Iterator<String> iterator = map.keySet().iterator();
+ // TODO: filter non classes.
+ String imports = ""; //$NON-NLS-1$
+ while (iterator.hasNext()) {
+ String element = iterator.next();
+ imports += "import " + element + ";\n"; //$NON-NLS-1$
//$NON-NLS-2$
+ }
+
+ imports += "import org.hibernate.criterion.*;\n"; //$NON-NLS-1$
+ imports += "import org.hibernate.*;\n"; //$NON-NLS-1$
+ // TODO: expose the parameters as values to be used in the code.
+ interpreter.eval(imports);
+
+ return interpreter;
+ }
+
+ public List<Object> evalQuery(String queryString, QueryInputModel model, Time
queryTime,
+ List<Throwable> exceptions) {
+ List<Object> res = Collections.emptyList();
+ Query query = null;
+ try {
+ query = session.createQuery(queryString);
+ } catch (HibernateException e) {
+ exceptions.add(e);
+ } catch (Exception e) {
+ exceptions.add(e);
+ }
+ if (query == null) {
+ return res;
+ }
+ try {
+ res = new ArrayList<Object>();
+ setupParameters(query, model);
+ long startTime = System.currentTimeMillis();
+ // need to be user-controllable to toggle between iterate, scroll etc.
+ Iterator<?> iter = query.list().iterator();
+ queryTime.setTime(System.currentTimeMillis() - startTime);
+ while (iter.hasNext()) {
+ Object element = iter.next();
+ res.add(element);
+ }
+ } catch (HibernateException e) {
+ exceptions.add(e);
+ } catch (IllegalArgumentException e) {
+ exceptions.add(e);
+ }
+ return res;
+ }
+
+ private void setupParameters(Query query, QueryInputModel model) {
+ if (model.getMaxResults() != null) {
+ query.setMaxResults(model.getMaxResults().intValue());
+ }
+ ConsoleQueryParameter[] qp = model.getQueryParameters();
+ for (int i = 0; i < qp.length; i++) {
+ ConsoleQueryParameter parameter = qp[i];
+ try {
+ int pos = Integer.parseInt(parameter.getName());
+ query.setParameter(pos, calcValue(parameter), parameter.getType());
+ } catch (NumberFormatException nfe) {
+ query.setParameter(parameter.getName(), calcValue(parameter), parameter.getType());
+ }
+ }
+ }
+
+ private Object calcValue(ConsoleQueryParameter parameter) {
+ return parameter.getValueForQuery();
+ }
+
+ public List<String> evalQueryPathNames(String queryString, QueryInputModel model,
+ List<Throwable> exceptions) {
+ List<String> res = Collections.emptyList();
+ Query query = null;
+ try {
+ query = session.createQuery(queryString);
+ } catch (HibernateException e) {
+ exceptions.add(e);
+ } catch (Exception e) {
+ exceptions.add(e);
+ }
+ if (query == null) {
+ return res;
+ }
+ try {
+ String[] returnAliases = null;
+ try {
+ returnAliases = query.getReturnAliases();
+ } catch (NullPointerException e) {
+ // ignore -
http://opensource.atlassian.com/projects/hibernate/browse/HHH-2188
+ }
+ if (returnAliases == null) {
+ Type[] t;
+ try {
+ t = query.getReturnTypes();
+ } catch (NullPointerException npe) {
+ t = new Type[] { null };
+ // ignore -
http://opensource.atlassian.com/projects/hibernate/browse/HHH-2188
+ }
+ res = new ArrayList<String>(t.length);
+ for (int i = 0; i < t.length; i++) {
+ Type type = t[i];
+ if (type == null) {
+ res.add("<multiple types>"); //$NON-NLS-1$
+ } else {
+ res.add(type.getName());
+ }
+ }
+ } else {
+ String[] t = returnAliases;
+ res = new ArrayList<String>(t.length);
+ for (int i = 0; i < t.length; i++) {
+ res.add(t[i]);
+ }
+ }
+ } catch (HibernateException e) {
+ exceptions.add(e);
+ }
+ return res;
+ }
+}
Added:
branches/hibernatetools-multiversion/hibernatetools/plugins/org.hibernate.eclipse/src/org/hibernate/console/stubs/SessionStubFactory.java
===================================================================
---
branches/hibernatetools-multiversion/hibernatetools/plugins/org.hibernate.eclipse/src/org/hibernate/console/stubs/SessionStubFactory.java
(rev 0)
+++
branches/hibernatetools-multiversion/hibernatetools/plugins/org.hibernate.eclipse/src/org/hibernate/console/stubs/SessionStubFactory.java 2010-03-17
12:09:59 UTC (rev 20874)
@@ -0,0 +1,155 @@
+package org.hibernate.console.stubs;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.hibernate.SessionFactory;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.console.ConsoleMessages;
+import org.hibernate.console.execution.ExecutionContext;
+import org.hibernate.console.util.ELTransformer;
+import org.hibernate.console.util.QLFormatHelper;
+import org.hibernate.engine.query.HQLQueryPlan;
+import org.hibernate.hql.QueryTranslator;
+import org.hibernate.impl.SessionFactoryImpl;
+import org.hibernate.metadata.ClassMetadata;
+import org.hibernate.metadata.CollectionMetadata;
+import org.hibernate.type.Type;
+
+public class SessionStubFactory {
+
+ protected ExecutionContext executionContext;
+ protected SessionFactory sessionFactory;
+
+ public SessionStubFactory(ExecutionContext executionContext, Configuration cfg) {
+ this.executionContext = executionContext;
+ sessionFactory = cfg.buildSessionFactory();
+ }
+
+ public boolean isSessionFactoryCreated() {
+ return sessionFactory != null;
+ }
+
+ public SessionStub openSession() {
+ if (sessionFactory != null) {
+ return new SessionStub(executionContext, sessionFactory.openSession());
+ }
+ return null;
+ }
+
+ public void close() {
+ if (sessionFactory != null) {
+ sessionFactory.close();
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<String> getClasses() {
+ List<String> res = Collections.emptyList();
+ if (sessionFactory != null) {
+ res = new ArrayList<String>();
+ res.addAll(sessionFactory.getAllClassMetadata().keySet());
+ }
+ return res;
+ }
+
+ // TODO: get rid of this - ClassMetadata - should not be public
+ @SuppressWarnings("unchecked")
+ public Map<String, ClassMetadata> getClassMetaData() {
+ if (sessionFactory == null) {
+ return new HashMap<String, ClassMetadata>();
+ }
+ return sessionFactory.getAllClassMetadata();
+ }
+ // TODO: get rid of this - ClassMetadata - should not be public
+ @SuppressWarnings("unchecked")
+ public Map<String, CollectionMetadata> getCollectionMetaData() {
+ if (sessionFactory == null) {
+ return new HashMap<String, CollectionMetadata>();
+ }
+ return sessionFactory.getAllCollectionMetadata();
+ }
+
+ /**
+ * Given a ConsoleConfiguration and a query this method validates the query through
hibernate if
+ * a sessionfactory is available.
+ *
+ * @param query
+ * @param allowEL
+ * if true, EL syntax will be replaced as a named variable
+ */
+ public void checkQuery(String query, boolean allowEL) {
+ if (sessionFactory != null) {
+ if (allowEL) {
+ query = ELTransformer.removeEL(query);
+ }
+ new HQLQueryPlan(query, false, Collections.EMPTY_MAP,
+ (SessionFactoryImpl) sessionFactory);
+ }
+ }
+
+ public String generateSQL(String query) {
+ try {
+ SessionFactoryImpl sfimpl = (SessionFactoryImpl) sessionFactory; // hack - to get to
the
+ // actual queries..
+ StringBuffer str = new StringBuffer(256);
+ HQLQueryPlan plan = new HQLQueryPlan(query, false, Collections.EMPTY_MAP, sfimpl);
+
+ QueryTranslator[] translators = plan.getTranslators();
+ for (int i = 0; i < translators.length; i++) {
+ QueryTranslator translator = translators[i];
+ if (translator.isManipulationStatement()) {
+ str.append(ConsoleMessages.DynamicSQLPreviewView_manipulation_of + i
+ + ":"); //$NON-NLS-1$
+ Iterator<?> iterator = translator.getQuerySpaces().iterator();
+ while (iterator.hasNext()) {
+ Object qspace = iterator.next();
+ str.append(qspace);
+ if (iterator.hasNext()) {
+ str.append(", ");} //$NON-NLS-1$
+ }
+
+ } else {
+ Type[] returnTypes = translator.getReturnTypes();
+ str.append(i + ": "); //$NON-NLS-1$
+ for (int j = 0; j < returnTypes.length; j++) {
+ Type returnType = returnTypes[j];
+ str.append(returnType.getName());
+ if (j < returnTypes.length - 1) {
+ str.append(", ");} //$NON-NLS-1$
+ }
+ }
+ str.append("\n-----------------\n"); //$NON-NLS-1$
+ Iterator<?> sqls = translator.collectSqlStrings().iterator();
+ while (sqls.hasNext()) {
+ String sql = (String) sqls.next();
+ str.append(QLFormatHelper.formatForScreen(sql));
+ str.append("\n\n"); //$NON-NLS-1$
+ }
+ }
+ return str.toString();
+ } catch (Throwable t) {
+ // StringWriter sw = new StringWriter();
+ StringBuffer msgs = new StringBuffer();
+
+ Throwable cause = t;
+ while (cause != null) {
+ msgs.append(t);
+ if (cause.getCause() == cause) {
+ cause = null;
+ } else {
+ cause = cause.getCause();
+ if (cause != null)
+ msgs.append(ConsoleMessages.DynamicSQLPreviewView_caused_by);
+ }
+ }
+ // t.printStackTrace(new PrintWriter(sw));
+ // return sw.getBuffer().toString();
+ return msgs.toString();
+ }
+ }
+}
Added:
branches/hibernatetools-multiversion/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/actions/ExternalProcessAction.java
===================================================================
---
branches/hibernatetools-multiversion/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/actions/ExternalProcessAction.java
(rev 0)
+++
branches/hibernatetools-multiversion/hibernatetools/plugins/org.hibernate.eclipse.console/src/org/hibernate/eclipse/console/actions/ExternalProcessAction.java 2010-03-17
12:09:59 UTC (rev 20874)
@@ -0,0 +1,40 @@
+package org.hibernate.eclipse.console.actions;
+
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.hibernate.console.ConsoleConfiguration;
+
+public class ExternalProcessAction extends ConsoleConfigurationBasedAction {
+
+ public static final String EXTERNALPROCESS_ACTIONID =
"actionid.externalprocess"; //$NON-NLS-1$
+
+ private StructuredViewer viewer;
+
+ /**
+ * @param text
+ */
+ protected ExternalProcessAction(String text) {
+ super(text);
+ setId(EXTERNALPROCESS_ACTIONID);
+ }
+
+ /**
+ * @param selectionProvider
+ */
+ public ExternalProcessAction(StructuredViewer selectionProvider) {
+ super("Run ExternalProcess");
+ this.viewer = selectionProvider;
+ setId(EXTERNALPROCESS_ACTIONID);
+ }
+
+ public void doRun() {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
org.hibernate.eclipse.console.actions.SessionFactoryBasedAction#updateState(org.hibernate.console.ConsoleConfiguration)
+ */
+ protected boolean updateState(ConsoleConfiguration consoleConfiguration) {
+ return consoleConfiguration.hasConfiguration();
+ }
+}
Modified:
branches/hibernatetools-multiversion/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/ConfigurationActor.java
===================================================================
---
branches/hibernatetools-multiversion/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/ConfigurationActor.java 2010-03-17
11:23:37 UTC (rev 20873)
+++
branches/hibernatetools-multiversion/hibernatetools/plugins/org.hibernate.eclipse.jdt.ui/src/org/hibernate/eclipse/jdt/ui/wizards/ConfigurationActor.java 2010-03-17
12:09:59 UTC (rev 20874)
@@ -592,7 +592,11 @@
sValue.setTypeName(tb.getBinaryName());
sValue.setFetchMode(FetchMode.JOIN);
RootClass associatedClass = rootClasses.get(ref.fullyQualifiedName);
- sValue.setReferencedEntityName(associatedClass.getEntityName());
+ if (associatedClass != null){
+ sValue.setReferencedEntityName(associatedClass.getEntityName());
+ } else {
+ sValue.setReferencedPropertyName(ref.fullyQualifiedName);
+ }
buildProperty(sValue);
prop.setCascade("none");//$NON-NLS-1$
} else {
Modified:
branches/hibernatetools-multiversion/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/KnownConfigurationsTest.java
===================================================================
---
branches/hibernatetools-multiversion/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/KnownConfigurationsTest.java 2010-03-17
11:23:37 UTC (rev 20873)
+++
branches/hibernatetools-multiversion/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/KnownConfigurationsTest.java 2010-03-17
12:09:59 UTC (rev 20874)
@@ -8,7 +8,6 @@
import junit.framework.TestCase;
-import org.hibernate.SessionFactory;
import org.hibernate.console.ConsoleConfiguration;
import org.hibernate.console.KnownConfigurations;
import org.hibernate.console.KnownConfigurationsAdapter;