Example usage for org.hibernate Query getReturnAliases

List of usage examples for org.hibernate Query getReturnAliases

Introduction

In this page you can find the example usage for org.hibernate Query getReturnAliases.

Prototype

@Deprecated
String[] getReturnAliases();

Source Link

Usage

From source file:org.compass.gps.device.hibernate.scrollable.Hibernate3ScrollableResultsGpsDevice.java

License:Apache License

/**
 * Indexes the data/*from  w w w. j av a2 s .co m*/
 */
protected void doIndex(CompassSession session) throws CompassException {
    // reset the snapshot data before we perform the index operation
    snapshot = new HibernateSnapshot();
    for (Iterator it = mappings.iterator(); it.hasNext();) {
        ResultSetToResourceMapping mapping = (ResultSetToResourceMapping) it.next();
        if (mapping.supportsVersioning()) {
            HibernateAliasSnapshot aliasSnapshot = new HibernateAliasSnapshot(mapping.getAlias());
            snapshot.putAliasSnapshot(aliasSnapshot);
        }
    }

    if (log.isInfoEnabled()) {
        log.info(buildMessage("Indexing the database with fetch count [" + fetchCount + "]"));
    }

    IndexExecution[] indexExecutions = doGetIndexExecutions();
    for (int i = 0; i != indexExecutions.length; i++) {
        IndexExecution indexExecution = indexExecutions[i];

        HibernateSessionWrapper sessionWrapper = doGetHibernateSessionWrapper();

        try {
            sessionWrapper.open();

            Session hibernateSession = ((Hibernate3SessionWrapper) sessionWrapper).getSession();

            String queryString = indexExecution.getStatementQuery();

            if (log.isDebugEnabled()) {
                log.debug("queryString: " + queryString);
            }

            Query query = hibernateSession.createQuery(queryString).setCacheMode(CacheMode.IGNORE);
            String[] returnAliases = query.getReturnAliases();

            ScrollableResults rs = query.scroll(ScrollMode.FORWARD_ONLY);
            int count = 0;
            while (rs.next()) {
                processRow(indexExecution.getDescription(), rs, returnAliases, session);
                if (++count % fetchCount == 0) {
                    // release memory
                    hibernateSession.flush();
                    hibernateSession.clear();
                }
            }
            rs.close();

        } catch (Exception e) {
            log.error(buildMessage("Failed to index the database"), e);
            sessionWrapper.closeOnError();
            if (!(e instanceof HibernateGpsDeviceException)) {
                throw new HibernateGpsDeviceException(buildMessage("Failed to index the database"), e);
            }
            throw (HibernateGpsDeviceException) e;
        }

    }

    if (log.isInfoEnabled()) {
        log.info(buildMessage("Finished indexing the database"));
    }

    // save the sanpshot data
    getSnapshotPersister().save(snapshot);
}

From source file:org.compass.gps.device.hibernate.scrollable.Hibernate3ScrollableResultsGpsDevice.java

License:Apache License

/**
 * Performs the data change mirroring operation.
 */// w w w .  jav a  2s.c  o  m
public synchronized void performMirroring() throws HibernateGpsDeviceException {
    if (!shouldMirrorDataChanges() || isPerformingIndexOperation()) {
        return;
    }
    if (snapshot == null) {
        throw new IllegalStateException(buildMessage(
                "Versioning data was not properly initialized, did you index the device or loaded the data?"));
    }

    HibernateSessionWrapper sessionWrapper = doGetHibernateSessionWrapper();

    try {
        sessionWrapper.open();
        for (Iterator it = mappings.iterator(); it.hasNext();) {
            ResultSetToResourceMapping mapping = (ResultSetToResourceMapping) it.next();
            if (!mapping.supportsVersioning()) {
                continue;
            }
            HibernateAliasSnapshot oldAliasSnapshot = snapshot.getAliasSnapshot(mapping.getAlias());
            if (oldAliasSnapshot == null) {
                log.warn(buildMessage("No snapshot for alias [" + mapping.getAlias()
                        + "] even though there should be support for versioning ignoring the alias"));
                continue;
            }
            HibernateAliasSnapshot newAliasSnapshot = new HibernateAliasSnapshot(mapping.getAlias());
            ArrayList createdRows = new ArrayList();
            ArrayList updatedRows = new ArrayList();
            ArrayList deletedRows = new ArrayList();
            if (log.isDebugEnabled()) {
                log.debug(buildMessage("Executing version query [" + mapping.getVersionQuery() + "]"));
            }

            String[] returnAliases = null;

            Session hibernateSession = ((Hibernate3SessionWrapper) sessionWrapper).getSession();

            String queryString = mapping.getVersionQuery();

            if (log.isDebugEnabled()) {
                log.debug("queryString: " + queryString);
            }

            Query query = hibernateSession.createQuery(queryString).setCacheMode(CacheMode.IGNORE);
            returnAliases = query.getReturnAliases();

            ScrollableResults rs = query.scroll(ScrollMode.FORWARD_ONLY);
            int count = 0;
            while (rs.next()) {
                if (log.isDebugEnabled()) {
                    StringBuffer sb = new StringBuffer();
                    sb.append(buildMessage("Version row with values "));
                    for (int i = 0; i != returnAliases.length; i++) {
                        sb.append("[").append(returnAliases[i]).append(":");
                        Object value = rs.get(i);
                        sb.append(value);
                        sb.append("] ");
                    }
                    log.debug(sb.toString());
                }

                HibernateAliasRowSnapshot newRowSnapshot = new HibernateAliasRowSnapshot();
                Hibernate3ScrollableResultsRowMarshallHelper marshallHelper = new Hibernate3ScrollableResultsRowMarshallHelper(
                        mapping, newRowSnapshot, compassGps.getMirrorCompass());
                marshallHelper.marshallResultSet(rs, returnAliases);

                // new and old have the same ids
                HibernateAliasRowSnapshot oldRowSnapshot = oldAliasSnapshot.getRow(newRowSnapshot);

                // new row or updated row
                if (oldRowSnapshot == null) {
                    createdRows.add(newRowSnapshot);
                } else if (oldRowSnapshot.isOlderThan(newRowSnapshot)) {
                    updatedRows.add(newRowSnapshot);
                }

                newAliasSnapshot.putRow(newRowSnapshot);

                if (++count % fetchCount == 0) {
                    // release memory
                    hibernateSession.flush();
                    hibernateSession.clear();
                }
            }
            rs.close();

            for (Iterator oldRowIt = oldAliasSnapshot.rowSnapshotIt(); oldRowIt.hasNext();) {
                HibernateAliasRowSnapshot tmpRow = (HibernateAliasRowSnapshot) oldRowIt.next();
                // deleted row
                if (newAliasSnapshot.getRow(tmpRow) == null) {
                    deletedRows.add(tmpRow);
                }
            }
            if (!createdRows.isEmpty() || !updatedRows.isEmpty()) {
                getSnapshotEventListener().onCreateAndUpdate(new CreateAndUpdateSnapshotEvent(hibernateSession,
                        mapping, createdRows, updatedRows, compassGps));
            }
            if (!deletedRows.isEmpty()) {
                getSnapshotEventListener()
                        .onDelete(new DeleteSnapshotEvent(hibernateSession, mapping, deletedRows, compassGps));
            }
            snapshot.putAliasSnapshot(newAliasSnapshot);
        }
    } catch (Exception e) {
        throw new HibernateGpsDeviceException(buildMessage("Failed while mirroring data changes"), e);
    } finally {
        sessionWrapper.close();
    }
    if (isSaveSnapshotAfterMirror()) {
        getSnapshotPersister().save(snapshot);
    }
}

From source file:org.compass.gps.device.hibernate.scrollable.ScrollableResultsSnapshotEventListener.java

License:Apache License

private void doCreateAndUpdateFor(final List snapshots,
        final CreateAndUpdateSnapshotEvent createAndUpdateSnapshotEvent, final boolean useCreate)
        throws HibernateGpsDeviceException {
    final ResultSetToResourceMapping mapping = createAndUpdateSnapshotEvent.getMapping();
    CompassGpsInterfaceDevice compassGps = createAndUpdateSnapshotEvent.getCompassGps();
    compassGps.executeForMirror(new CompassCallbackWithoutResult() {
        protected void doInCompassWithoutResult(CompassSession session) throws CompassException {
            String query = (String) createAndUpdateQueries.get(mapping.getAlias());

            try {
                Session s = createAndUpdateSnapshotEvent.getSession();
                Query hibernateQuery = s.createQuery(query);
                for (Iterator it = snapshots.iterator(); it.hasNext();) {
                    HibernateAliasRowSnapshot rowSnapshot = (HibernateAliasRowSnapshot) it.next();
                    Resource resource = session.createResource(mapping.getAlias());
                    Hibernate3ScrollableResultsRowMarshallHelper marshallHelper = new Hibernate3ScrollableResultsRowMarshallHelper(
                            mapping, session, resource);
                    //XXX: clearParameters of hibernateQuery?
                    List ids = rowSnapshot.getIds();
                    for (int i = 0; i < ids.size(); i++) {
                        Object idValue = ids.get(i);
                        hibernateQuery.setParameter(i, idValue);
                    }//w w w .java 2 s . c om

                    String[] returnAliases = hibernateQuery.getReturnAliases();
                    ScrollableResults rs = hibernateQuery.scroll(ScrollMode.FORWARD_ONLY);
                    if (!rs.next()) {
                        // it was deleted between the calls, do nothing
                        continue;
                    }
                    rs.close();

                    marshallHelper.marshallResultSet(rs, returnAliases);
                    if (useCreate) {
                        session.create(resource);
                    } else {
                        session.save(resource);
                    }
                    session.evictAll();
                }
            } catch (Exception e) {
                throw new HibernateGpsDeviceException("Failed to execute query for create/update", e);
            } finally {
                //TODO: close Session?
                // maybe keeping Session in the events is not a good idea
                // -> keep the SessionWrapper in event?
                // or close session somewhere else
                //(session will also be closed on committing the transaction)
            }
        }
    });
}

From source file:org.openbravo.client.querylist.QueryListDataSource.java

License:Open Source License

@Override
protected List<Map<String, Object>> getData(Map<String, String> parameters, int startRow, int endRow) {
    // creation of formats is done here because they are not thread safe
    final SimpleDateFormat xmlDateFormat = JsonUtils.createDateFormat();
    final SimpleDateFormat xmlDateTimeFormat = JsonUtils.createDateTimeFormat();

    OBContext.setAdminMode();/*  w  ww .  j a v a2 s.  c  om*/
    try {
        WidgetClass widgetClass = OBDal.getInstance().get(WidgetClass.class, parameters.get("widgetId"));

        // Check security: continue only if the widget instance is visible for current user/role
        WidgetInstance wi = OBDal.getInstance().get(WidgetInstance.class, parameters.get("widgetInstanceId"));

        boolean accessibleWidgetInForm = false;
        if (wi == null) {
            accessibleWidgetInForm = isAccessibleWidgetInForm(widgetClass);
        }
        if (!accessibleWidgetInForm && (wi == null || wi.getWidgetClass().getId() != widgetClass.getId())) {
            // weird stuff: widget class doesn't match widget instance's class, most probably URL is
            // not generated by UI, but user is typing it
            log.error("User " + OBContext.getOBContext().getUser() + " with role "
                    + OBContext.getOBContext().getRole() + " is trying to access widget '"
                    + widgetClass.getWidgetTitle() + "' but widget istance doesn't match with class");
            throw new OBSecurityException(OBMessageUtils.getI18NMessage("OBCQL_NoAccessToWidget",
                    new String[] { widgetClass.getWidgetTitle() }));
        }

        if (!accessibleWidgetInForm && (OBContext.getOBContext() != null
                && ((wi.getVisibleAtUser() != null
                        && !wi.getVisibleAtUser().getId().equals(OBContext.getOBContext().getUser().getId())))
                || (wi.getVisibleAtRole() != null && !wi.getVisibleAtRole().getId()
                        .equals(OBContext.getOBContext().getRole().getId())))) {
            log.error("User " + OBContext.getOBContext().getUser() + " with role "
                    + OBContext.getOBContext().getRole() + " is trying to access widget '"
                    + widgetClass.getWidgetTitle() + "' which is not granted");
            throw new OBSecurityException(OBMessageUtils.getI18NMessage("OBCQL_NoAccessToWidget",
                    new String[] { widgetClass.getWidgetTitle() }));
        }

        boolean isExport = "true".equals(parameters.get("exportToFile"));
        boolean showAll = "true".equals(parameters.get("showAll"));
        String viewMode = parameters.get("viewMode");
        List<OBCQL_QueryColumn> columns = QueryListUtils
                .getColumns(widgetClass.getOBCQLWidgetQueryList().get(0));

        // handle complex criteria
        try {
            JSONArray criterias = (JSONArray) JsonUtils.buildCriteria(parameters).get("criteria");
            for (int i = 0; i < criterias.length(); i++) {
                final JSONObject criteria = criterias.getJSONObject(i);
                parameters.put(criteria.getString("fieldName"), criteria.getString("value"));
                parameters.put(criteria.getString("fieldName") + OPERATOR, criteria.getString("operator"));
            }
        } catch (JSONException e) {
            // Ignore exception.
        }

        OBCQL_WidgetQuery widgetQueryInstance = widgetClass.getOBCQLWidgetQueryList().get(0);
        String HQL = widgetQueryInstance.getHQL();
        // Parse the HQL in case that optional filters are required
        HQL = parseOptionalFilters(HQL, viewMode, parameters, columns, xmlDateFormat);
        boolean fetchingSummaryFields = parameters.containsKey(JsonConstants.SUMMARY_PARAMETER);
        if (fetchingSummaryFields) {
            // if the request comes from the summary row, update the select clause so that it obtains
            // the values for the summary fields
            HQL = updateHQLWithSummaryFields(HQL, parameters.get(JsonConstants.SUMMARY_PARAMETER),
                    widgetQueryInstance);
        }

        if (parameters.containsKey(JsonConstants.SORTBY_PARAMETER)) {
            HQL = updateSortByFields(HQL, parameters.get(JsonConstants.SORTBY_PARAMETER));
        }

        Query widgetQuery = null;
        try {
            widgetQuery = OBDal.getInstance().getSession().createQuery(HQL);
        } catch (Exception e) {
            if (fetchingSummaryFields) {
                log.error("Exception while fetching the summary columns of the widget "
                        + widgetClass.getWidgetTitle()
                        + ". It is not supported using as summaries columns that are defined using a subquery, or that are defined using a summary function. \n Query = "
                        + HQL);
            } else {
                log.error("Exception while executing the HQL query to fetch the data of the widget "
                        + widgetClass.getWidgetTitle() + ". \n Query = " + HQL);
            }
            final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
            return result;
        }
        String[] queryAliases = widgetQuery.getReturnAliases();

        if (!isExport && "widget".equals(viewMode) && !showAll) {
            int rowsNumber = Integer.valueOf(
                    (parameters.get("rowsNumber") != null && !parameters.get("rowsNumber").equals("null"))
                            ? parameters.get("rowsNumber")
                            : "10");
            widgetQuery.setMaxResults(rowsNumber);
        } else if (!isExport) {
            if (startRow > 0) {
                widgetQuery.setFirstResult(startRow);
            }
            if (endRow > startRow) {
                widgetQuery.setMaxResults(endRow - startRow + 1);
            }
        }

        String[] params = widgetQuery.getNamedParameters();
        if (params.length > 0) {
            HashMap<String, Object> parameterValues = getParameterValues(parameters, widgetClass);

            for (int i = 0; i < params.length; i++) {
                String namedParam = params[i];
                boolean isParamSet = false;
                if (parameterValues.containsKey(namedParam)) {
                    Object value = parameterValues.get(namedParam);
                    if (value instanceof Collection<?>) {
                        widgetQuery.setParameterList(namedParam, (Collection<?>) value);
                    } else if (value instanceof Object[]) {
                        widgetQuery.setParameterList(namedParam, (Object[]) value);
                    } else if (value instanceof String
                            && isDate(namedParam, widgetClass.getOBUIAPPParameterEMObkmoWidgetClassIDList())) {
                        widgetQuery.setParameter(namedParam, convertToDate((String) value));
                    } else {
                        widgetQuery.setParameter(namedParam, value);
                    }
                    isParamSet = true;
                }
                if (!isParamSet) {
                    // TODO: throw an exception
                }
            }
        }

        final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

        if (fetchingSummaryFields) {
            // process the response for the summary row
            Map<String, Object> summaryData = new LinkedHashMap<String, Object>();
            try {
                JSONObject summaryFieldsObject = new JSONObject(
                        parameters.get(JsonConstants.SUMMARY_PARAMETER));
                Iterator<?> summaryFieldNameIterator = summaryFieldsObject.keys();
                Object uniqueResult = widgetQuery.uniqueResult();
                if (uniqueResult instanceof Object[]) {
                    // handles the case where the values of several summary fields are request
                    Object[] summaryValues = (Object[]) uniqueResult;
                    int i = 0;
                    while (summaryFieldNameIterator.hasNext()) {
                        String summaryFieldName = (String) summaryFieldNameIterator.next();
                        summaryData.put(summaryFieldName, summaryValues[i++]);
                    }
                } else {
                    // handles the case where the value of just one summary field is request
                    String summaryFieldName = (String) summaryFieldsObject.names().get(0);
                    summaryData.put(summaryFieldName, uniqueResult);
                }
                summaryData.put("isGridSummary", true);
            } catch (Exception e) {
            }
            result.add(summaryData);

        } else {
            // process the response for the grid
            for (Object objResult : widgetQuery.list()) {
                final Map<String, Object> data = new LinkedHashMap<String, Object>();
                Object[] resultList = new Object[1];
                if (objResult instanceof Object[]) {
                    resultList = (Object[]) objResult;
                } else {
                    resultList[0] = objResult;
                }

                for (OBCQL_QueryColumn column : columns) {
                    UIDefinition uiDefinition = UIDefinitionController.getInstance()
                            .getUIDefinition(column.getReference());
                    DomainType domainType = uiDefinition.getDomainType();
                    // TODO: throw an exception if the display expression doesn't match any returned alias.
                    for (int i = 0; i < queryAliases.length; i++) {
                        if (queryAliases[i].equals(column.getDisplayExpression())
                                || (!isExport && queryAliases[i].equals(column.getLinkExpression()))) {
                            Object value = resultList[i];
                            if (domainType instanceof DateDomainType || domainType instanceof DateDomainType) {
                                value = xmlDateFormat.format(value);
                            } else if (value instanceof Timestamp) {
                                value = xmlDateTimeFormat.format(value);
                                value = JsonUtils.convertToCorrectXSDFormat((String) value);
                            }

                            if (domainType instanceof BooleanDomainType) {
                                if (value instanceof String) {
                                    value = ((PrimitiveDomainType) domainType).createFromString((String) value);
                                }
                            }

                            if (!isExport) {
                                data.put(queryAliases[i], value);
                            } else {
                                data.put(QueryListUtils.getColumnLabel(column), value);
                            }
                        }
                    }
                }
                result.add(data);
            }
        }
        return result;
    } finally {
        OBContext.restorePreviousMode();
    }
}

From source file:org.openbravo.erpCommon.ad_process.HeartbeatProcess.java

License:Open Source License

/**
 * Gets a JSON Array with the custom queries and sends back to the heartbeat server the results.
 * The results of the queries are also stored on the heartbeat local log.</p>
 * /*  w w  w.  j a va 2s . c  o m*/
 * The result that is sent to the heartbeat server is a JSON Object that contains the beat type,
 * the beat id and another JSON Object with the results of the queries.</p>
 * 
 * The JSON Object with the results contains one JSON Object for each executed query identified by
 * the Query Id. This JSON Object is formed by 2 JSON Arrays. The first one, identified by
 * "properties" contains a String array with the header of each returned property. The second one
 * identified by "values" contains a JSON Array for each returned row, each row is a JSON Array
 * with the value of each returned property.</p>
 * 
 * Example of a returned JSON Object string:</p>
 * 
 * <code>
 * {<br>
 * &nbsp;beatType:CUSTOMQUERY_BEAT,<br>
 * &nbsp;beatId:1234-5678-90,<br>
 * &nbsp;customQueries:{<br>
 * &nbsp;&nbsp;queryId1:{<br>
 * &nbsp;&nbsp;&nbsp;properties:{"QId1property1","QId1property2"},<br>
 * &nbsp;&nbsp;&nbsp;values:[[row1value1,row1value2],[row2value1, row2value2],[row3value1, row3value2]]<br>
 * &nbsp;&nbsp;},<br>
 * &nbsp;&nbsp;queryId2:{<br>
 * &nbsp;&nbsp;&nbsp;properties:{"QId2property1","QId2property2"},<br>
 * &nbsp;&nbsp;&nbsp;values:[[row1value1,row1value2],[row2value1, row2value2],[row3value1, row3value2]]<br>
 * &nbsp;&nbsp;}<br>
 * &nbsp;}<br>
 * }<br></code></p>
 * 
 * @param jsonArrayCQueries
 *          An array of JSON Objects with all the custom queries to be executed. Each JSON Object
 *          contains the query Id, the query name, the query type and depending of the type the
 *          corresponding code.
 * @param beatId
 *          The identifier of the beat on the heartbeat server.
 * @throws JSONException
 */
@SuppressWarnings("unchecked")
private void processCustomQueries(JSONArray jsonArrayCQueries, String beatId) throws JSONException {
    if ("null".equals(jsonArrayCQueries.get(0)))
        return;

    JSONObject jsonObjectCQReturn = new JSONObject();
    for (int i = 0; i < jsonArrayCQueries.length(); i++) {
        JSONObject jsonCustomQuery = (JSONObject) jsonArrayCQueries.get(i);
        String strQId = jsonCustomQuery.getString("QId");
        String strQName = jsonCustomQuery.getString("QName");
        logger.logln("Processing custom query: " + strQName);
        try {
            String strQType = jsonCustomQuery.getString("QType");
            if ("HQL".equals(strQType)) {
                String strHQL = jsonCustomQuery.getString("QCode");
                HeartbeatLogCustomQuery hbLogCQ = logCustomQuery(strQName, strQType, strHQL);

                Session obSession = OBDal.getInstance().getSession();
                Query customQuery = obSession.createQuery(strHQL);
                String[] properties = customQuery.getReturnAliases();
                JSONArray jsonArrayResultRows = new JSONArray();
                int row = 0;

                for (Object objResult : (List<Object>) customQuery.list()) {
                    row += 1;
                    JSONArray jsonArrayResultRowValues = new JSONArray();

                    Object[] resultList = new Object[1];
                    if (objResult instanceof Object[])
                        resultList = (Object[]) objResult;
                    else
                        resultList[0] = objResult;

                    for (int j = 0; j < resultList.length; j++) {
                        jsonArrayResultRowValues.put(resultList[j]);

                        String fieldName = null;
                        if (properties != null && properties.length > j) {
                            fieldName = properties[j];
                        }
                        if (fieldName == null) {
                            fieldName = "??";
                        }
                        logCustomQueryResult(hbLogCQ, row, fieldName, resultList[j].toString());
                    }
                    jsonArrayResultRows.put(jsonArrayResultRowValues);
                }

                if (customQuery.list().isEmpty())
                    jsonArrayResultRows.put("null");

                JSONObject jsonResult = new JSONObject();
                jsonResult.put("properties", properties == null ? null : Arrays.asList(properties));
                jsonResult.put("values", jsonArrayResultRows);
                jsonObjectCQReturn.put(strQId, jsonResult);
            } else {
                log.warn("unknown Query Type: " + strQType);
                jsonObjectCQReturn.put(strQId, "unknown query type: " + strQType);
            }
        } catch (Exception e) {
            // ignore exception
            jsonObjectCQReturn.put(strQId, "exeption executing query: " + e.getMessage());
            log.warn("Error processing custom query: " + strQName);
        }

    }
    JSONObject jsonObjectReturn = new JSONObject();
    jsonObjectReturn.put("beatId", beatId);
    jsonObjectReturn.put("customQueries", jsonObjectCQReturn);

    try {
        String info = "beatType=" + CUSTOMQUERY_BEAT + "&q=" + jsonObjectReturn.toString();
        sendInfo(info);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

}

From source file:org.openbravo.service.datasource.HQLDataSourceService.java

License:Open Source License

@Override
protected List<Map<String, Object>> getData(Map<String, String> parameters, int startRow, int endRow) {

    Table table = getTableFromParameters(parameters);
    Entity entity = ModelProvider.getInstance().getEntityByTableId(table.getId());
    OBContext.setAdminMode(true);/*from ww w  .j  a  v  a  2s  . c om*/
    boolean justCount = false;
    Query query = getQuery(table, parameters, justCount);

    if (startRow > 0) {
        query.setFirstResult(startRow);
    }
    if (endRow > startRow) {
        query.setMaxResults(endRow - startRow + 1);
    }

    String distinct = parameters.get(JsonConstants.DISTINCT_PARAMETER);
    List<Column> columns = table.getADColumnList();
    List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
    String[] returnAliases = query.getReturnAliases();
    boolean checkIsNotNull = false;
    for (Object row : query.list()) {
        Map<String, Object> record = new HashMap<String, Object>();
        if (distinct != null) {
            Object[] result = (Object[]) row;
            // the whole referenced BaseOBObject is stored in the first position of the result
            BaseOBObject bob = (BaseOBObject) result[0];
            if (bob == null) {
                break;
            }
            record.put(JsonConstants.ID, bob.getId());
            record.put(JsonConstants.IDENTIFIER, IdentifierProvider.getInstance().getIdentifier(bob));
        } else {
            Object[] properties = (Object[]) row;
            for (int i = 0; i < returnAliases.length; i++) {
                Property property = entity.getPropertyByColumnName(returnAliases[i].toLowerCase(),
                        checkIsNotNull);
                if (property == null) {
                    property = entity.getPropertyByColumnName(columns.get(i).getDBColumnName().toLowerCase());
                }
                record.put(property.getName(), properties[i]);
            }
        }
        data.add(record);
    }
    OBContext.restorePreviousMode();
    return data;
}

From source file:org.openbravo.userinterface.selector.CustomQuerySelectorDatasource.java

License:Open Source License

@Override
protected List<Map<String, Object>> getData(Map<String, String> parameters, int startRow, int endRow) {
    // creation of formats is done here because they are not thread safe
    final SimpleDateFormat xmlDateFormat = JsonUtils.createDateFormat();
    final SimpleDateFormat xmlDateTimeFormat = JsonUtils.createDateTimeFormat();
    final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    final List<Object> typedParameters = new ArrayList<Object>();
    // Defaulted to endRow + 2 to check for more records while scrolling.
    int totalRows = endRow + 2, rowCount = 0;

    String selectorId = parameters.get(SelectorConstants.DS_REQUEST_SELECTOR_ID_PARAMETER);

    if (StringUtils.isEmpty(selectorId)) {
        return result;
    }//from w  w  w.j a  va  2  s  .  c  o  m

    OBContext.setAdminMode();
    try {

        Selector sel = OBDal.getInstance().get(Selector.class, selectorId);
        List<SelectorField> fields = OBDao.getActiveOBObjectList(sel,
                Selector.PROPERTY_OBUISELSELECTORFIELDLIST);

        // Forcing object initialization to prevent LazyInitializationException in case session is
        // cleared when number of records is big enough
        Hibernate.initialize(fields);

        // Parse the HQL in case that optional filters are required
        String HQL = parseOptionalFilters(parameters, sel, xmlDateFormat, typedParameters);

        String sortBy = parameters.get("_sortBy");
        HQL += getSortClause(sortBy, sel);

        Query selQuery = OBDal.getInstance().getSession().createQuery(HQL);
        for (int i = 0; i < typedParameters.size(); i++) {
            selQuery.setParameter(ALIAS_PREFIX + Integer.toString(i), typedParameters.get(i));
        }
        String[] queryAliases = selQuery.getReturnAliases();

        if (startRow > 0) {
            selQuery.setFirstResult(startRow);
        }
        if (endRow > startRow) {
            selQuery.setMaxResults(endRow - startRow + 1);
        }

        for (Object objResult : selQuery.list()) {
            rowCount++;
            final Map<String, Object> data = new LinkedHashMap<String, Object>();
            Object[] resultList = new Object[1];
            if (objResult instanceof Object[]) {
                resultList = (Object[]) objResult;
            } else {
                resultList[0] = objResult;
            }

            for (SelectorField field : fields) {
                // TODO: throw an exception if the display expression doesn't match any returned alias.
                for (int i = 0; i < queryAliases.length; i++) {
                    if (queryAliases[i].equals(field.getDisplayColumnAlias())) {
                        Object value = resultList[i];
                        if (value instanceof Date) {
                            value = xmlDateFormat.format(value);
                        }
                        if (value instanceof Timestamp) {
                            value = xmlDateTimeFormat.format(value);
                            value = JsonUtils.convertToCorrectXSDFormat((String) value);
                        }
                        data.put(queryAliases[i], value);
                    }
                }
            }
            result.add(data);
        }
        if ("true".equals(parameters.get(JsonConstants.NOCOUNT_PARAMETER))) {
            if (startRow < endRow) {
                if (rowCount < endRow) {
                    totalRows = rowCount;
                }
                parameters.put(JsonConstants.RESPONSE_TOTALROWS, String.valueOf(totalRows));
            }
        }
    } finally {
        OBContext.restorePreviousMode();
    }
    return result;
}

From source file:org.openswing.swing.util.server.HibernateUtils.java

License:Open Source License

/**
 * Read a block of records from the result set, starting from a Query object.
 * @param action fetching versus: PREVIOUS_BLOCK_ACTION, NEXT_BLOCK_ACTION or LAST_BLOCK_ACTION
 * @param startPos start position of data fetching in result set
 * @param blockSize number of records to read
 * @param query Query object/*from ww w .ja v a  2 s.  c om*/
 * @param sess Session
 */
public static Response getBlockFromQuery(Class valueObjectClass, int action, int startIndex, int blockSize,
        Query query, Session sess) throws Exception {

    // read a block of records...
    ArrayList gridList = new ArrayList();
    boolean moreRows = false;
    int resultSetLength = -1;
    int rowCount = 0;
    if (action == GridParams.LAST_BLOCK_ACTION) {
        // last block requested: the whole result set will be loaded, to determine the result set length
        Iterator it = query.iterate();
        while (it.hasNext()) {
            rowCount++;
            it.next();
        }
        resultSetLength = rowCount;
        action = GridParams.NEXT_BLOCK_ACTION;
        startIndex = Math.max(rowCount - blockSize, 0);
        rowCount = 0;
        query.setFirstResult(startIndex);
        query.setMaxResults(blockSize);
    } else {
        if (action == GridParams.PREVIOUS_BLOCK_ACTION) {
            action = GridParams.NEXT_BLOCK_ACTION;
            startIndex = Math.max(startIndex - blockSize, 0);
        }
        query.setFirstResult(startIndex);
        query.setMaxResults(blockSize + 1);
    }
    List list = query.list();
    gridList.addAll(list);
    if (gridList.size() > blockSize) {
        gridList.remove(gridList.size() - 1);
        moreRows = true;
    }
    if (resultSetLength == -1) {
        resultSetLength = gridList.size();
    }

    if (gridList.size() > 0 && gridList.get(0) instanceof Object[]) {
        return QueryUtil.getQuery(query.getReturnAliases(), valueObjectClass, gridList, moreRows);

    }

    return new VOListResponse(gridList, moreRows, resultSetLength);
}

From source file:org.pentaho.platform.plugin.services.connections.hql.HQLConnection.java

License:Open Source License

public IPentahoResultSet executeQuery(final String query) {
    lastQuery = query;//from   w  w  w.j a  v a 2 s. c om
    Session sess = null;
    IPentahoResultSet localResultSet = null;
    try {
        SessionFactory sf = hibernateConfig.buildSessionFactory();
        // open session
        sess = sf.openSession();
        Query q = sess.createQuery(query);
        if (timeOut >= 0) {
            q.setTimeout(timeOut);
        }
        if (maxRows >= 0) {
            q.setMaxResults(maxRows);
        }
        List list = q.list();
        localResultSet = generateResultSet(list, q.getReturnAliases(), q.getReturnTypes());
    } finally {
        try {
            if (sess != null) {
                sess.close();
            }
        } catch (Exception e) {
            // Doesn't seem like we would get any exception from sess.close()
            logger.error(Messages.getInstance().getErrorString("HQLConnection.ERROR_0001_UNABLE_TO_CLOSE"), e); //$NON-NLS-1$
        }
    }

    return localResultSet;
}

From source file:org.pentaho.reporting.engine.classic.extensions.datasources.hibernate.SimpleHQLDataFactory.java

License:Open Source License

/**
 * Queries a datasource. The string 'query' defines the name of the query. The Parameterset given here may contain
 * more data than actually needed.//  ww  w. j a  va2  s .c  om
 * <p/>
 * The dataset may change between two calls, do not assume anything!
 *
 * @param query
 * @param parameters
 * @return
 */
public synchronized TableModel queryData(final String query, final DataRow parameters)
        throws ReportDataFactoryException {
    try {
        final Query pstmt = getSession().createQuery(query);
        final String[] params = pstmt.getNamedParameters();
        for (int i = 0; i < params.length; i++) {
            final String param = params[i];
            final Object pvalue = parameters.get(param);
            if (pvalue == null) {
                // this should work, but some driver are known to die here.
                // they should be fed with setNull(..) instead; something
                // we cant do as JDK1.2's JDBC does not define it.
                pstmt.setParameter(param, null);
            } else {
                pstmt.setParameter(param, pvalue);
            }
        }

        final Object queryLimit = parameters.get(DataFactory.QUERY_LIMIT);
        if (queryLimit instanceof Number) {
            final Number i = (Number) queryLimit;
            if (i.intValue() >= 0) {
                pstmt.setMaxResults(i.intValue());
            }
        }
        final Object queryTimeout = parameters.get(DataFactory.QUERY_TIMEOUT);
        if (queryTimeout instanceof Number) {
            final Number i = (Number) queryLimit;
            if (i.intValue() >= 0) {
                pstmt.setTimeout(i.intValue());
            }
        }
        final ScrollableResults res = pstmt.scroll(ScrollMode.FORWARD_ONLY);
        return generateDefaultTableModel(res, pstmt.getReturnAliases());
    } catch (Exception e) {
        throw new ReportDataFactoryException("Failed at query: " + query, e);
    }
}