Search in sources :

Example 81 with NucleusUserException

use of org.datanucleus.exceptions.NucleusUserException in project datanucleus-core by datanucleus.

the class AbstractQueryResult method getSizeUsingMethod.

/**
 * Method to get the size using the "resultSizeMethod".
 * This implementation supports "COUNT" method.
 * Override this in subclasses to implement other methods.
 * @return The size
 */
protected int getSizeUsingMethod() {
    if (resultSizeMethod.equalsIgnoreCase("COUNT")) {
        if (query != null && query.getCompilation() != null) {
            ExecutionContext ec = query.getExecutionContext();
            if (query.getCompilation().getQueryLanguage().equalsIgnoreCase(Query.LANGUAGE_JDOQL)) {
                // JDOQL : "count([DISTINCT ]this)" query
                Query countQuery = query.getStoreManager().newQuery(Query.LANGUAGE_JDOQL, ec, query);
                if (query.getResultDistinct()) {
                    countQuery.setResult("COUNT(DISTINCT this)");
                } else {
                    countQuery.setResult("count(this)");
                }
                // Ordering not relevant to a count
                countQuery.setOrdering(null);
                // Don't want range to interfere with the query
                countQuery.setRange(null);
                Map queryParams = query.getInputParameters();
                long count;
                if (queryParams != null) {
                    count = ((Long) countQuery.executeWithMap(queryParams)).longValue();
                } else {
                    count = ((Long) countQuery.execute()).longValue();
                }
                if (query.getRange() != null) {
                    // Query had a range, so update the returned count() to allow for the required range
                    long rangeStart = query.getRangeFromIncl();
                    long rangeEnd = query.getRangeToExcl();
                    count -= rangeStart;
                    if (count > (rangeEnd - rangeStart)) {
                        count = rangeEnd - rangeStart;
                    }
                }
                countQuery.closeAll();
                return (int) count;
            } else if (query.getCompilation().getQueryLanguage().equalsIgnoreCase(Query.LANGUAGE_JPQL)) {
                // JPQL : "count()" query
                Query countQuery = query.getStoreManager().newQuery(Query.LANGUAGE_JPQL, ec, query);
                countQuery.setResult("count(" + query.getCompilation().getCandidateAlias() + ")");
                countQuery.setOrdering(null);
                // Don't want range to interfere with the query
                countQuery.setRange(null);
                Map queryParams = query.getInputParameters();
                long count;
                if (queryParams != null) {
                    count = ((Long) countQuery.executeWithMap(queryParams)).longValue();
                } else {
                    count = ((Long) countQuery.execute()).longValue();
                }
                if (query.getRange() != null) {
                    // Query had a range, so update the returned count() to allow for the required range
                    long rangeStart = query.getRangeFromIncl();
                    long rangeEnd = query.getRangeToExcl();
                    count -= rangeStart;
                    if (count > (rangeEnd - rangeStart)) {
                        count = rangeEnd - rangeStart;
                    }
                }
                countQuery.closeAll();
                return (int) count;
            }
        }
        throw new NucleusUserException("datanucleus.query.resultSizeMethod of \"COUNT\" is only valid for use with JDOQL or JPQL currently");
    }
    throw new NucleusUserException("DataNucleus doesnt currently support any method \"" + resultSizeMethod + "\" for determining the size of the query results");
}
Also used : ExecutionContext(org.datanucleus.ExecutionContext) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) Map(java.util.Map)

Example 82 with NucleusUserException

use of org.datanucleus.exceptions.NucleusUserException in project datanucleus-core by datanucleus.

the class Query method checkParameterTypesAgainstCompilation.

/**
 * Method to do checks of the input parameters with respect to their types being consistent
 * with the types of the parameters in the compilation.
 * Checks for unused input parameters. Doesn't check for missing parameters.
 * @param parameterValues The input parameter values keyed by their name (or position)
 */
protected void checkParameterTypesAgainstCompilation(Map parameterValues) {
    if (compilation == null) {
        return;
    } else if (parameterValues == null || parameterValues.isEmpty()) {
        return;
    }
    // Check for unused parameters
    boolean checkUnusedParams = checkUnusedParameters();
    Iterator it = parameterValues.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry entry = (Map.Entry) it.next();
        Object paramKey = entry.getKey();
        Symbol sym = null;
        // Find the symbol for the parameter in the compilation (or subquery compilations)
        sym = deepFindSymbolForParameterInCompilation(compilation, paramKey);
        if (sym != null) {
            Class expectedValueType = sym.getValueType();
            if (entry.getValue() != null && expectedValueType != null && !QueryUtils.queryParameterTypesAreCompatible(expectedValueType, entry.getValue().getClass())) {
                // Supplied parameter value is of inconsistent type
                throw new NucleusUserException("Parameter \"" + paramKey + "\" was specified as " + entry.getValue().getClass().getName() + " but should have been " + expectedValueType.getName());
            }
        } else // TODO Also do this for positional params if not found ?
        if (paramKey instanceof String) {
            if ((fromInclParam == null && toExclParam == null) || (!paramKey.equals(fromInclParam) && !paramKey.equals(toExclParam))) {
                if (checkUnusedParams) {
                    throw new QueryInvalidParametersException(Localiser.msg("021116", paramKey));
                }
            }
        }
    }
}
Also used : Symbol(org.datanucleus.query.compiler.Symbol) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) Iterator(java.util.Iterator) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 83 with NucleusUserException

use of org.datanucleus.exceptions.NucleusUserException in project datanucleus-core by datanucleus.

the class Query method getParameterMapForValues.

/**
 * Convenience method to convert the input parameters into a parameter map keyed by the parameter
 * name. If the parameters for this query are explicit then they are keyed by the names defined
 * as input via "declareParameters()".
 * @param parameterValues Parameter values
 * @return The parameter map.
 */
protected Map getParameterMapForValues(Object[] parameterValues) {
    // Generate a parameter map from the parameter names to these input values
    Map parameterMap = new HashMap();
    int position = 0;
    if (explicitParameters != null) {
        // Explicit parameters
        StringTokenizer t1 = new StringTokenizer(explicitParameters, ",");
        while (t1.hasMoreTokens()) {
            StringTokenizer t2 = new StringTokenizer(t1.nextToken(), " ");
            if (t2.countTokens() != 2) {
                // Invalid spec; should be "{type_decl} {param_name}"
                throw new NucleusUserException(Localiser.msg("021101", explicitParameters));
            }
            // Parameter type declaration
            t2.nextToken();
            String parameterName = t2.nextToken();
            if (!JDOQLQueryHelper.isValidJavaIdentifierForJDOQL(parameterName)) {
                // Invalid parameter name for Java
                throw new NucleusUserException(Localiser.msg("021102", parameterName));
            }
            if (parameterMap.containsKey(parameterName)) {
                // Duplicate definition of a parameter
                throw new NucleusUserException(Localiser.msg("021103", parameterName));
            }
            if (parameterValues.length < position + 1) {
                // Too many parameters defined and not enough values
                throw new NucleusUserException(Localiser.msg("021108", "" + (position + 1), "" + parameterValues.length));
            }
            parameterMap.put(parameterName, parameterValues[position++]);
        }
        if (parameterMap.size() != parameterValues.length) {
            // Too many values and not enough parameters declared
            throw new NucleusUserException(Localiser.msg("021108", "" + parameterMap.size(), "" + parameterValues.length));
        }
    } else {
        // Positional implicit parameters (JDO input)
        for (int i = 0; i < parameterValues.length; ++i) {
            // Dummy parameter name for DataNucleus, utilised by the implementation
            parameterMap.put(Integer.valueOf(i), parameterValues[i]);
        }
    }
    return parameterMap;
}
Also used : StringTokenizer(java.util.StringTokenizer) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 84 with NucleusUserException

use of org.datanucleus.exceptions.NucleusUserException in project datanucleus-core by datanucleus.

the class StateManagerImpl method initialiseForHollowAppId.

// ============================================= DEPRECATED METHODS ==============================================
/**
 * Initialises a state manager to manage a HOLLOW / P_CLEAN instance having the given FieldValues.
 * This constructor is used for creating new instances of existing persistent objects using application identity,
 * and consequently shouldn't be used when the StoreManager controls the creation of such objects (such as in an ODBMS).
 * @param fv the initial field values of the object.
 * @param pcClass Class of the object that this will manage the state for
 * @deprecated Remove use of this and use initialiseForHollow
 */
public void initialiseForHollowAppId(FieldValues fv, Class pcClass) {
    if (cmd.getIdentityType() != IdentityType.APPLICATION) {
        throw new NucleusUserException("This constructor is only for objects using application identity.").setFatal();
    }
    myLC = myEC.getNucleusContext().getApiAdapter().getLifeCycleState(LifeCycleState.HOLLOW);
    persistenceFlags = Persistable.LOAD_REQUIRED;
    // Create new PC
    myPC = HELPER.newInstance(pcClass, this);
    if (myPC == null) {
        if (!HELPER.getRegisteredClasses().contains(pcClass)) {
            // probably never will get here, as EnhancementHelper.newInstance() internally already throws JDOFatalUserException when class is not registered
            throw new NucleusUserException(Localiser.msg("026018", pcClass.getName())).setFatal();
        }
        // Provide advisory information since we can't create an instance of this class, so maybe they have an error in their data ?
        throw new NucleusUserException(Localiser.msg("026019", pcClass.getName())).setFatal();
    }
    // as a minimum the PK fields are loaded here
    loadFieldValues(fv);
    // Create the ID now that we have the PK fields loaded
    myID = myEC.getNucleusContext().getIdentityManager().getApplicationId(myPC, cmd);
}
Also used : NucleusUserException(org.datanucleus.exceptions.NucleusUserException)

Example 85 with NucleusUserException

use of org.datanucleus.exceptions.NucleusUserException in project datanucleus-core by datanucleus.

the class StateManagerImpl method makeTransactional.

/**
 * Method to change the object state to transactional.
 */
public void makeTransactional() {
    preStateChange();
    try {
        if (myLC == null) {
            // Initialise the StateManager in T_CLEAN state
            final ObjectProvider thisOP = this;
            myLC = myEC.getNucleusContext().getApiAdapter().getLifeCycleState(LifeCycleState.T_CLEAN);
            try {
                if (myLC.isPersistent()) {
                    myEC.addObjectProviderToCache(this);
                }
                // Everything OK so far. Now we can set SM reference in PC
                // It can be done only after myLC is set to deligate validation to the LC and objectId verified for uniqueness
                replaceStateManager(myPC, thisOP);
            } catch (SecurityException e) {
                throw new NucleusUserException(e.getMessage());
            } catch (NucleusException ne) {
                if (myEC.findObjectProvider(myEC.getObjectFromCache(myID)) == this) {
                    myEC.removeObjectProviderFromCache(this);
                }
                throw ne;
            }
            flags |= FLAG_RESTORE_VALUES;
        } else {
            myLC = myLC.transitionMakeTransactional(this, true);
        }
    } finally {
        postStateChange();
    }
}
Also used : NucleusUserException(org.datanucleus.exceptions.NucleusUserException) NucleusException(org.datanucleus.exceptions.NucleusException)

Aggregations

NucleusUserException (org.datanucleus.exceptions.NucleusUserException)258 NucleusException (org.datanucleus.exceptions.NucleusException)65 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)51 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)46 SQLExpression (org.datanucleus.store.rdbms.sql.expression.SQLExpression)46 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)41 DatastoreClass (org.datanucleus.store.rdbms.table.DatastoreClass)36 ArrayList (java.util.ArrayList)34 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)30 ObjectProvider (org.datanucleus.state.ObjectProvider)30 ClassNotResolvedException (org.datanucleus.exceptions.ClassNotResolvedException)26 Expression (org.datanucleus.query.expression.Expression)24 InvokeExpression (org.datanucleus.query.expression.InvokeExpression)23 SQLException (java.sql.SQLException)22 PersistableMapping (org.datanucleus.store.rdbms.mapping.java.PersistableMapping)21 NullLiteral (org.datanucleus.store.rdbms.sql.expression.NullLiteral)21 SQLLiteral (org.datanucleus.store.rdbms.sql.expression.SQLLiteral)21 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)20 SQLExpressionFactory (org.datanucleus.store.rdbms.sql.expression.SQLExpressionFactory)20 BigInteger (java.math.BigInteger)19