Example usage for org.hibernate QueryException getMessage

List of usage examples for org.hibernate QueryException getMessage

Introduction

In this page you can find the example usage for org.hibernate QueryException getMessage.

Prototype

@Override
    public String getMessage() 

Source Link

Usage

From source file:com.evolveum.midpoint.repo.sql.query.QueryInterpreter.java

License:Apache License

private Criteria interpretQuery(ObjectQuery query, Class<? extends ObjectType> type, PrismContext prismContext,
        Session session) throws QueryException {
    ObjectFilter filter = query.getFilter();
    try {/*from www .  j a v  a2s  .com*/
        QueryContext context = new QueryContext(this, type, query, prismContext, session);

        Restriction restriction = findAndCreateRestriction(filter, context, null);
        Criterion criterion = restriction.interpret(filter);

        Criteria criteria = context.getCriteria(null);
        criteria.add(criterion);

        return criteria;
    } catch (QueryException ex) {
        throw ex;
    } catch (Exception ex) {
        LOGGER.trace(ex.getMessage(), ex);
        throw new QueryException(ex.getMessage(), ex);
    }
}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

private WGResultSetCore executeHQLQuery(String type, String query, Map queryOptions) throws WGAPIException {
    String builtQuery = null;/*  w  w  w.j ava2  s  . co m*/

    Map queryParams = (Map) queryOptions.get(WGDatabase.QUERYOPTION_QUERY_PARAMETERS);
    if (queryParams == null) {
        queryParams = new HashMap();
    }

    List<WGLanguage> languagesPriorityList = null;

    // Determine fetch type. Lazy fetch will only retrieve content keys and
    // get content data in subsequent calls
    List options = WGUtils.deserializeCollection(
            String.valueOf(queryOptions.get(WGDatabase.QUERYOPTION_NATIVEOPTIONS)), ",", true);
    boolean lazyFetch = _hqlLazyByDefault;
    if (options.contains(HQL_FETCHTYPE_STRAIGHT)) {
        lazyFetch = false;
    } else if (options.contains(HQL_FETCHTYPE_LAZY)) {
        lazyFetch = true;
    }

    if (type.equals("fullhql")) {
        builtQuery = query;
    }
    if (type.equals("hql")) {
        List fullQuery = new ArrayList();

        // Filter invisible and unreleased docs
        if (!queryOptions.containsKey(WGDatabase.QUERYOPTION_ENHANCE)
                || String.valueOf(queryOptions.get(WGDatabase.QUERYOPTION_ENHANCE)).equals("true")) {

            fullQuery.add("content.visible=" + getNativeSQLExpression(NATIVESQL_BOOLEAN_TRUE));
            fullQuery.add("(content.validfrom is null OR content.validfrom <= current_timestamp())");
            fullQuery.add("(content.validto is null OR content.validto >= current_timestamp())");

            String role = WGContent.DISPLAYTYPE_SEARCH;
            if (queryOptions.containsKey(WGDatabase.QUERYOPTION_ROLE)) {
                role = (String) queryOptions.get(WGDatabase.QUERYOPTION_ROLE);
            }
            if (role != null && !role.equals(WGContent.DISPLAYTYPE_NONE)) {
                fullQuery.add(":wgaparamRole not in elements(content.ishiddenfrom)");
                queryParams.put("wgaparamRole", role);
            }
        }

        if (queryOptions.containsKey(WGDatabase.QUERYOPTION_ONLYRELEASED)) {
            fullQuery.add("content.status = 'p'");
        }

        // Filter languages
        if (queryOptions.containsKey(WGDatabase.QUERYOPTION_LANGUAGES)) {
            List<WGLanguage> langs = (List<WGLanguage>) queryOptions.get(WGDatabase.QUERYOPTION_LANGUAGES);
            if (langs.size() > 1 && lazyFetch) {
                List languageTerms = new ArrayList();
                for (WGLanguage lang : langs) {
                    languageTerms.add("content.language.name = '" + lang.getName() + "'");
                }
                fullQuery.add("(" + WGUtils.serializeCollection(languageTerms, " OR ") + ")");
                languagesPriorityList = langs;
            } else if (langs.size() == 1) {
                fullQuery.add("content.language.name = :wgaparamLanguage");
                queryParams.put("wgaparamLanguage", langs.get(0).getName());
            } else {
                fullQuery.add("content.language.name = :wgaparamLanguage");
                queryParams.put("wgaparamLanguage", getDb().getDefaultLanguage());
            }

        } else if (queryOptions.containsKey(WGDatabase.QUERYOPTION_ONLYLANGUAGE)) {
            fullQuery.add("content.language.name = '"
                    + queryOptions.get(WGDatabase.QUERYOPTION_ONLYLANGUAGE).toString() + "'");
        }

        // Filter the "current document"
        if (queryOptions.containsKey(WGDatabase.QUERYOPTION_EXCLUDEDOCUMENT)) {
            WGContent content = (WGContent) queryOptions.get(WGDatabase.QUERYOPTION_EXCLUDEDOCUMENT);
            if (content.getDatabase() == this._db && !content.isDummy() && content.isSaved()) {
                WGDocumentCore contentCore = content.getCore();
                if (contentCore instanceof WGDocumentImpl) {
                    Content contentEntity = (Content) ((WGDocumentImpl) content.getCore()).getEntity();
                    if (_ddlVersion >= WGDatabase.CSVERSION_WGA5) {
                        fullQuery.add("not content.id = :wgaparamEntityId");
                        queryParams.put("wgaparamEntityId", contentEntity.getId());
                    } else {
                        fullQuery.add("not content.cuid = :wgaparamEntityId");
                        queryParams.put("wgaparamEntityId", contentEntity.getCuid());
                    }
                }
            }
        }

        // Extract ORDER BY part to get it out of the brackets
        String furtherClauses = "";
        int whereClauseEndIdx = query.toLowerCase().indexOf("group by");
        if (whereClauseEndIdx == -1) {
            whereClauseEndIdx = query.toLowerCase().indexOf("order by");
        }
        if (whereClauseEndIdx != -1) {
            furtherClauses = query.substring(whereClauseEndIdx);
            query = query.substring(0, whereClauseEndIdx);
        }

        fullQuery.add("(" + query + ")");

        builtQuery = composeHQLQuery(fullQuery, furtherClauses, lazyFetch, (languagesPriorityList != null));
    }

    if (builtQuery == null) {
        throw new WGQueryException(query, "Unknown query type: " + type);
    }

    builtQuery = WGUtils.strReplace(builtQuery, "\"", "'", true);

    if (queryOptions != null) {
        queryOptions.put(WGDatabase.QUERYOPTION_RETURNQUERY, builtQuery);
    }

    List results = null;
    try {
        Query hibQuery = getSession().createQuery(builtQuery);
        int maxResults = 0;
        if (queryOptions.containsKey(WGDatabase.QUERYOPTION_MAXRESULTS)) {
            maxResults = ((Number) queryOptions.get(WGDatabase.QUERYOPTION_MAXRESULTS)).intValue();
        }
        if (maxResults > 0) {
            hibQuery.setMaxResults(maxResults);
        }

        HibernateResultSet.injectQueryParams(hibQuery, queryParams);
        if (lazyFetch) {
            if (languagesPriorityList != null) {
                return new WGLanguageChoosingHQLResultSet(this, hibQuery, queryParams, queryOptions,
                        languagesPriorityList);
            } else {
                return new WGLazyHQLResultSet(this, hibQuery, queryParams, queryOptions);
            }
        } else {
            return new WGStraightHQLResultSet(this, hibQuery, queryParams, queryOptions);
        }
    } catch (QueryException e) {
        throw new WGQueryException(builtQuery, e.getMessage(), e);
    } catch (HibernateException e) {
        throw new WGBackendException("Error executing HQL query", e);
    }

}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

public List queryUserProfileNames(String type, String query, Map params) throws WGAPIException {

    if (type == null) {
        type = "hql";
    }/*w  ww.j a  v  a2s  . c  o m*/

    try {
        String fullQuery;
        if (query != null) {
            if (type.equals("hql")) {
                fullQuery = "select profile.name from UserProfile profile where (" + query
                        + ") order by profile.name asc";
            } else if (type.equals("fullhql")) {
                fullQuery = query;
            } else {
                throw new WGQueryException(query, "Unknown query type '" + type + "'");
            }
        } else {
            fullQuery = "select profile.name from UserProfile profile order by profile.name asc";
        }

        Query hqlQuery = getSession().createQuery(fullQuery);
        if (params.containsKey(WGDatabase.QUERYOPTION_MAXRESULTS)) {
            Number maxResults = (Number) params.get(WGDatabase.QUERYOPTION_MAXRESULTS);
            hqlQuery.setMaxResults(maxResults.intValue());
        }

        return hqlQuery.list();

    } catch (QueryException e) {
        throw new WGQueryException(query, e.getMessage(), e);
    } catch (HibernateException e) {
        throw new WGBackendException("Error executing profile query", e);
    }

}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

public Iterator<String> getAllUserProfileNames() throws WGAPIException {

    try {/*from w  w w  .  j  av  a2 s .c  om*/
        String fullQuery = "select profile.name from UserProfile profile order by profile.name asc";

        Query hqlQuery = getSession().createQuery(fullQuery);
        return hqlQuery.iterate();

    } catch (QueryException e) {
        throw new WGQueryException("Querying all user profile names", e.getMessage(), e);
    } catch (HibernateException e) {
        throw new WGBackendException("Error executing profile query", e);
    }

}

From source file:net.databinder.components.hib.QueryPanel.java

License:Open Source License

/**
 * Constructs an {@link QueryPanel}// w w w  .  ja v  a 2  s  .c o m
 * @param id 
 *          the panel identifier. Must not be null.
 */
public QueryPanel(String id) {
    super(id);

    final WebMarkupContainer resultsHolder = new WebMarkupContainer("resultsHolder");
    resultsHolder.add(new Label("executionInfo", new PropertyModel(this, "executionInfo")));
    resultsHolder.add(getResultsTable());
    resultsHolder.setOutputMarkupId(true);
    add(resultsHolder);

    Form form = new Form("form", new CompoundPropertyModel(query));
    form.setOutputMarkupId(true);
    form.add(new TextArea("query"));
    form.add(new AjaxButton("submit", form) {
        private static final long serialVersionUID = 1L;

        protected void onSubmit(AjaxRequestTarget target, Form form) {
            if (resultsHolder.get("results") != null) {
                resultsHolder.remove("results");
            }
            try {
                resultsHolder.add(getResultsTable());
            } catch (QueryException e) {
                note(e);
            } catch (IllegalArgumentException e) {
                note(e);
            } catch (IllegalStateException e) {
                note(e);
            }
            target.addComponent(resultsHolder);
        }

        private void note(Exception e) {
            resultsHolder.add(new Label("results", e.getClass().getSimpleName() + ": " + e.getMessage()));
        }
    });
    add(form);
}

From source file:org.openbravo.test.dal.ComputedColumnsTest.java

License:Open Source License

/**
 * Tests computed columns can not be used in OBCriteria
 *//*from w  ww .  j  a  v  a2  s .  c om*/
@Test
public void testComputedColumnCriteriaFilter() {
    setTestUserContext();

    // try to filter in Criteria by computed column...
    OBCriteria<Order> qOrder = OBDal.getInstance().createCriteria(Order.class);
    qOrder.add(Restrictions.eq(Order.COMPUTED_COLUMN_DELIVERYSTATUS, 100));
    boolean thrown = false;
    try {
        qOrder.count();
    } catch (QueryException e) {
        thrown = e.getMessage().startsWith(EXCEPTION_MSG);
    }

    // ... it shouldn't be possible
    assertTrue("Computed columns sholdn't be usable in OBCriteria", thrown);
}

From source file:org.openbravo.test.dal.ComputedColumnsTest.java

License:Open Source License

/**
 * Direct access to computed columns in HQL was allowed prior to MP27, now it is not anymore and
 * proxy needs to be used./*from  w  w w .j  av a 2  s.co  m*/
 */
@Test
public void testComputedColumnHQLFilterOldWay() {
    setTestUserContext();

    // try to filter in HQL directly by computed column...
    OBQuery<Order> qOrder = OBDal.getInstance().createQuery(Order.class, "as o where o.deliveryStatus = 100");

    boolean thrown = false;
    try {
        qOrder.count();
    } catch (QueryException e) {
        thrown = e.getMessage().startsWith(EXCEPTION_MSG);
    }

    // ... it shouldn't be possible, proxy should be used to reach it
    assertTrue("Computed columns can't be directly used in HQL", thrown);
}

From source file:org.springframework.orm.hibernate3.HibernateQueryException.java

License:Apache License

public HibernateQueryException(QueryException ex) {
    super(ex.getMessage(), ex);
}

From source file:org.unitime.commons.hibernate.util.DatabaseUpdate.java

License:Open Source License

public boolean performUpdate(Element updateElement) {
    int version = Integer.parseInt(updateElement.attributeValue("version"));
    Session hibSession = new _RootDAO().getSession();
    String schema = _RootDAO.getConfiguration().getProperty("default_schema");
    Transaction tx = null;//from   w  w  w  .  ja  v a  2  s  .c  om
    Hashtable variables = new Hashtable();
    try {
        tx = hibSession.beginTransaction();
        sLog.info("  Performing " + updateName() + " update to version " + version + " ("
                + updateElement.attributeValue("comment") + ")");
        for (Iterator i = updateElement.elementIterator(); i.hasNext();) {
            Element queryElement = (Element) i.next();
            String type = queryElement.getName();
            String query = queryElement.getText().trim().replaceAll("%SCHEMA%", schema);
            for (Iterator j = variables.entrySet().iterator(); j.hasNext();) {
                Map.Entry entry = (Map.Entry) j.next();
                query = query.replaceAll("%" + entry.getKey() + "%", entry.getValue().toString());
            }
            String condition = queryElement.attributeValue("condition", "none");
            String action = queryElement.attributeValue("action", "next");
            String value = queryElement.attributeValue("value");
            String into = queryElement.attributeValue("into");
            if (queryElement.attribute("onFail") != null) {
                condition = "fail";
                action = queryElement.attributeValue("onFail");
            }
            if (queryElement.attribute("onEqual") != null) {
                condition = "equal";
                action = queryElement.attributeValue("onEqual");
            }
            if (queryElement.attribute("onNotEqual") != null) {
                condition = "notEqual";
                action = queryElement.attributeValue("onNotEqual");
            }
            if (query.length() == 0)
                continue;
            try {
                if (type.equals("hql") || type.equals("sql") || type.equals(iDialectSQL)) {
                    sLog.debug("  -- HQL: " + query + " (con:" + condition + ", act:" + action + ", val:"
                            + value + ")");
                    Query q = null;
                    try {
                        q = (type.equals("hql") ? hibSession.createQuery(query)
                                : hibSession.createSQLQuery(query));
                    } catch (QueryException e) {
                        // Work-around Hibernate issue HHH-2697 (https://hibernate.onjira.com/browse/HHH-2697)
                        if (!"hql".equals(type)) {
                            final String sql = query;
                            hibSession.doWork(new Work() {
                                @Override
                                public void execute(Connection connection) throws SQLException {
                                    Statement statement = connection.createStatement();
                                    int lines = statement.executeUpdate(sql);
                                    sLog.debug("  -- " + lines + " lines affected.");
                                    statement.close();
                                }
                            });
                        } else
                            throw e;
                    }
                    boolean ok = true;
                    if (into != null) {
                        variables.put(into, q.uniqueResult().toString());
                    } else if ("equal".equals(condition) && value != null) {
                        ok = value.equals(q.uniqueResult().toString());
                    } else if ("notEqual".equals(condition) && value != null) {
                        ok = !value.equals(q.uniqueResult().toString());
                    } else if (q != null) {
                        int lines = q.executeUpdate();
                        sLog.debug("  -- " + lines + " lines affected.");
                        if ("noChange".equals(condition))
                            ok = (lines == 0);
                        else if ("change".equals(condition))
                            ok = (lines > 0);
                    }
                    if (ok) {
                        if ("next".equals(action))
                            continue;
                        if ("done".equals(action))
                            break;
                        if ("fail".equals(action)) {
                            sLog.error("Update to " + updateName() + " version " + version
                                    + " failed (condition not met for query '" + query + "', con:" + condition
                                    + ", act:" + action + ", val:" + value + ").");
                            tx.rollback();
                            return false;
                        }
                    }
                } else {
                    sLog.debug("  -- skip: " + query + " (con:" + condition + ", act:" + action + ", val:"
                            + value + ")");
                }
            } catch (Exception e) {
                sLog.warn("Query '" + query + "' failed, " + e.getMessage(), e);
                if (e.getCause() != null && e.getCause().getMessage() != null)
                    sLog.warn("Cause: " + e.getCause().getMessage());
                if ("fail".equals(condition)) {
                    if ("next".equals(action))
                        continue;
                    if ("done".equals(action))
                        break;
                }
                sLog.error("Update to version " + version + " failed.");
                tx.rollback();
                return false;
            }
        }

        ApplicationConfig versionCfg = ApplicationConfig.getConfig(versionParameterName());
        if (versionCfg == null) {
            versionCfg = new ApplicationConfig(versionParameterName());
            versionCfg.setDescription("Timetabling " + updateName()
                    + " DB version (do not change -- this is used by automatic database update)");
        }
        versionCfg.setValue(String.valueOf(version));
        hibSession.saveOrUpdate(versionCfg);
        sLog.info("    " + updateName() + " Database version increased to: " + version);

        if (tx != null && tx.isActive())
            tx.commit();
        HibernateUtil.clearCache();
        return true;
    } catch (Exception e) {
        if (tx != null && tx.isActive())
            tx.rollback();
        sLog.error("Update to version " + version + " failed, reason:" + e.getMessage(), e);
        return false;
    }
}