Package com.espertech.esper.epl.expression

Examples of com.espertech.esper.epl.expression.ExprValidationException


            if (!prop.isFragment()) {
                Class assigned = prop.getPropertyType();
                if (existing != null && existing instanceof Class) {
                    if (JavaClassHelper.getBoxedType((Class) existing) != JavaClassHelper.getBoxedType(assigned)) {
                        throw new ExprValidationException("Type by name '" + typeToMerge.getName() + "' contributes property '" +
                          prop.getPropertyName() + "' defined as '" + JavaClassHelper.getClassNameFullyQualPretty(assigned) +
                                "' which overides the same property of type '" + JavaClassHelper.getClassNameFullyQualPretty((Class)existing)+ "'");
                    }
                }
                typing.put(prop.getPropertyName(), prop.getPropertyType());
            }
            else {
                if (existing != null) {
                    throw new ExprValidationException("Property by name '" + prop.getPropertyName() + "' is defined twice by adding type '" + typeToMerge.getName() + "'");
                }

                FragmentEventType fragment = typeToMerge.getFragmentType(prop.getPropertyName());
                if (fragment == null) {
                    continue;
View Full Code Here


                    count++;
                }
                catch (ExprValidationException ex) {
                    boolean isNot = item instanceof OnTriggerMergeActionInsert;
                    String message = "Exception encountered in when-" + (isNot?"not-":"") + "matched (clause " + count + "): " + ex.getMessage();
                    throw new ExprValidationException(message, ex);
                }
            }

            if (matchedItem.isMatchedUnmatched()) {
                matched.add(new NamedWindowOnMergeMatch(matchedItem.getOptionalMatchCond(), actions));
View Full Code Here

    }

    public void validateOnExpressionContext(String onExprContextName) throws ExprValidationException {
        if (onExprContextName == null) {
            if (contextName != null) {
                throw new ExprValidationException("Cannot create on-trigger expression: Named window '" + namedWindowName + "' was declared with context '" + contextName + "', please declare the same context name");
            }
            return;
        }
        if (!onExprContextName.equals(contextName)) {
            throw new ExprValidationException("Cannot create on-trigger expression: Named window '" + namedWindowName + "' was declared with context '" + contextName + "', please use the same context instead");
        }
    }
View Full Code Here

     * @throws com.espertech.esper.epl.expression.ExprValidationException if the index fails to be valid
     */
    public synchronized void addExplicitIndex(String namedWindowName, String indexName, List<CreateIndexItem> columns) throws ExprValidationException {

        if (explicitIndexes.containsKey(indexName)) {
            throw new ExprValidationException("Index by name '" + indexName + "' already exists");
        }

        List<IndexedPropDesc> hashProps = new ArrayList<IndexedPropDesc>();
        List<IndexedPropDesc> btreeProps = new ArrayList<IndexedPropDesc>();

        Set<String> indexed = new HashSet<String>();
        for (CreateIndexItem columnDesc : columns) {
            String columnName = columnDesc.getName();

            Class type = JavaClassHelper.getBoxedType(rootView.getEventType().getPropertyType(columnName));
            if (type == null) {
                throw new ExprValidationException("Property named '" + columnName + "' not found on named window '" + namedWindowName + "'");
            }
            if (!indexed.add(columnName)) {
                throw new ExprValidationException("Property named '" + columnName + "' has been declared more then once");
            }

            IndexedPropDesc desc = new IndexedPropDesc(columnName, type);
            if (columnDesc.getType() == CreateIndexType.HASH) {
                hashProps.add(desc);
View Full Code Here

            sqlFragments = PlaceholderParser.parsePlaceholder(databaseStreamSpec.getSqlWithSubsParams());
        }
        catch (PlaceholderParseException ex)
        {
            String text = "Error parsing SQL";
            throw new ExprValidationException(text + ", reason: " + ex.getMessage());
        }

        // Assemble a PreparedStatement and parameter list
        String preparedStatementText = createPreparedStatement(sqlFragments);
        SQLParameterDesc parameterDesc = getParameters(sqlFragments);
        if (log.isDebugEnabled())
        {
            log.debug(".createDBEventStream preparedStatementText=" + preparedStatementText +
                " parameterDesc=" + parameterDesc);
        }

        // Get a database connection
        String databaseName = databaseStreamSpec.getDatabaseName();
        DatabaseConnectionFactory databaseConnectionFactory;
        ColumnSettings metadataSetting;
        try
        {
            databaseConnectionFactory = databaseConfigService.getConnectionFactory(databaseName);
            metadataSetting = databaseConfigService.getQuerySetting(databaseName);
        }
        catch (DatabaseConfigException ex)
        {
            String text = "Error connecting to database '" + databaseName + '\'';
            log.error(text, ex);
            throw new ExprValidationException(text + ", reason: " + ex.getMessage());
        }

        Connection connection;
        try
        {
            connection = databaseConnectionFactory.getConnection();
        }
        catch (DatabaseConfigException ex)
        {
            String text = "Error connecting to database '" + databaseName + '\'';
            log.error(text, ex);
            throw new ExprValidationException(text + ", reason: " + ex.getMessage());
        }

        // On default setting, if we detect Oracle in the connection then don't query metadata from prepared statement
        ConfigurationDBRef.MetadataOriginEnum metaOriginPolicy = metadataSetting.getMetadataRetrievalEnum();
        if (metaOriginPolicy == ConfigurationDBRef.MetadataOriginEnum.DEFAULT)
        {
            String connectionClass = connection.getClass().getName();
            if ((connectionClass.toLowerCase().contains("oracle") || (connectionClass.toLowerCase().contains("timesten"))))
            {
                // switch to sample statement if we are dealing with an oracle connection
                metaOriginPolicy = ConfigurationDBRef.MetadataOriginEnum.SAMPLE;
            }
        }

        QueryMetaData queryMetaData;
        try
        {
            if ((metaOriginPolicy == ConfigurationDBRef.MetadataOriginEnum.METADATA) || (metaOriginPolicy == ConfigurationDBRef.MetadataOriginEnum.DEFAULT))
            {
                queryMetaData = getPreparedStmtMetadata(connection, parameterDesc.getParameters(), preparedStatementText, metadataSetting);
            }
            else
            {
                String sampleSQL;
                boolean isGivenMetadataSQL = true;
                if (databaseStreamSpec.getMetadataSQL() != null)
                {
                    sampleSQL = databaseStreamSpec.getMetadataSQL();
                    isGivenMetadataSQL = true;
                    if (log.isInfoEnabled())
                    {
                        log.info(".createDBStatementView Using provided sample SQL '" + sampleSQL + "'");
                    }
                }
                else
                {
                    // Create the sample SQL by replacing placeholders with null and
                    // SAMPLE_WHERECLAUSE_PLACEHOLDER with a "where 1=0" clause
                    sampleSQL = createSamplePlaceholderStatement(sqlFragments);

                    if (log.isInfoEnabled())
                    {
                        log.info(".createDBStatementView Using un-lexed sample SQL '" + sampleSQL + "'");
                    }

                    // If there is no SAMPLE_WHERECLAUSE_PLACEHOLDER, lexical analyse the SQL
                    // adding a "where 1=0" clause.
                    if (parameterDesc.getBuiltinIdentifiers().length != 1)
                    {
                        sampleSQL = lexSampleSQL(sampleSQL);
                        if (log.isInfoEnabled())
                        {
                            log.info(".createDBStatementView Using lexed sample SQL '" + sampleSQL + "'");
                        }
                    }
                }

                // finally get the metadata by firing the sample SQL
                queryMetaData = getExampleQueryMetaData(connection, parameterDesc.getParameters(), sampleSQL, metadataSetting, isGivenMetadataSQL);
            }
        }
        catch (ExprValidationException ex)
        {
            try
            {
                connection.close();
            }
            catch (SQLException e)
            {
                // don't handle
            }
            throw ex;
        }

        // Close connection
        try
        {
            connection.close();
        }
        catch (SQLException e)
        {
            String text = "Error closing connection";
            log.error(text, e);
            throw new ExprValidationException(text + ", reason: " + e.getMessage());
        }

        // Create event type
        // Construct an event type from SQL query result metadata
        Map<String, Object> eventTypeFields = new HashMap<String, Object>();
        int columnNum = 1;
        for (Map.Entry<String, DBOutputTypeDesc> entry : queryMetaData.getOutputParameters().entrySet())
        {
            String name = entry.getKey();
            DBOutputTypeDesc dbOutputDesc = entry.getValue();

            Class clazz;
            if (dbOutputDesc.getOptionalBinding() != null)
            {
                clazz = dbOutputDesc.getOptionalBinding().getType();
            }
            else
            {
                clazz = SQLTypeMapUtil.sqlTypeToClass(dbOutputDesc.getSqlType(), dbOutputDesc.getClassName());
            }

            if (columnTypeConversionHook != null) {

                Class newValue = columnTypeConversionHook.getColumnType(new SQLColumnTypeContext(databaseStreamSpec.getDatabaseName(), databaseStreamSpec.getSqlWithSubsParams(), name, clazz, dbOutputDesc.getSqlType(), columnNum));
                if (newValue != null) {
                    clazz = newValue;
                }

            }
            eventTypeFields.put(name, clazz);
            columnNum++;
        }

        EventType eventType;
        if (outputRowConversionHook == null) {
            String outputEventType = statementId + "_dbpoll_" + streamNumber;
            eventType = eventAdapterService.createAnonymousMapType(outputEventType, eventTypeFields);
        }
        else {
            Class carrierClass = outputRowConversionHook.getOutputRowType(new SQLOutputRowTypeContext(databaseStreamSpec.getDatabaseName(), databaseStreamSpec.getSqlWithSubsParams(), eventTypeFields));
            if (carrierClass == null) {
                throw new ExprValidationException("Output row conversion hook returned no type");
            }
            eventType = eventAdapterService.addBeanType(carrierClass.getName(), carrierClass, false, false, false);
        }

        // Get a proper connection and data cache
        ConnectionCache connectionCache;
        DataCache dataCache;
        try
        {
            connectionCache = databaseConfigService.getConnectionCache(databaseName, preparedStatementText);
            dataCache = databaseConfigService.getDataCache(databaseName, epStatementAgentInstanceHandle);
        }
        catch (DatabaseConfigException e)
        {
            String text = "Error obtaining cache configuration";
            log.error(text, e);
            throw new ExprValidationException(text + ", reason: " + e.getMessage());
        }

        PollExecStrategyDBQuery dbPollStrategy = new PollExecStrategyDBQuery(eventAdapterService,
                eventType, connectionCache, preparedStatementText, queryMetaData.getOutputParameters(), columnTypeConversionHook, outputRowConversionHook, enableJDBCLogging);
View Full Code Here

        }
        catch (SQLException ex)
        {
            String text = "Error creating statement";
            log.error(text, ex);
            throw new ExprValidationException(text + ", reason: " + ex.getMessage());
        }

        ResultSet result;
        try
        {
            result = statement.executeQuery(sampleSQL);
        }
        catch (SQLException ex)
        {
            String text;
            if (isUsingMetadataSQL)
            {
                text = "Error compiling metadata SQL to retrieve statement metadata, using sql text '" + sampleSQL + "'";
            }
            else
            {
                text = "Error compiling metadata SQL to retrieve statement metadata, consider using the 'metadatasql' syntax, using sql text '" + sampleSQL + "'";
            }

            try {
                statement.close();
            } catch (SQLException e) {
                log.info("Error closing statement: " + e.getMessage(), e);
            }

            log.error(text, ex);
            throw new ExprValidationException(text + ", reason: " + ex.getMessage());
        }

        Map<String, DBOutputTypeDesc> outputProperties;
        try
        {
            outputProperties = compileResultMetaData(result.getMetaData(), metadataSetting);
        }
        catch (SQLException ex)
        {
            try
            {
                result.close();
            }
            catch (SQLException e)
            {
                // don't handle
            }
            try
            {
                statement.close();
            }
            catch (SQLException e)
            {
                // don't handle
            }
            String text = "Error in statement '" + sampleSQL + "', failed to obtain result metadata";
            log.error(text, ex);
            throw new ExprValidationException(text + ", please check the statement, reason: " + ex.getMessage());
        }

        return new QueryMetaData(inputParameters, outputProperties);
    }
View Full Code Here

        {
            input = new NoCaseSensitiveStream(reader);
        }
        catch (IOException ex)
        {
            throw new ExprValidationException("IOException lexing query SQL '" + querySQL + '\'', ex);
        }

        int whereIndex = -1;
        int groupbyIndex = -1;
        int havingIndex = -1;
        int orderByIndex = -1;
        List<Integer> unionIndexes = new ArrayList<Integer>();

        EsperEPL2GrammarLexer lex = new EsperEPL2GrammarLexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lex);
        List tokenList = tokens.getTokens();

        for (int i = 0; i < tokenList.size(); i++)
        {
            Token token = (Token) tokenList.get(i);
            if ((token == null) || token.getText() == null)
            {
                break;
            }
            String text = token.getText().toLowerCase().trim();
            if (text.equals("where"))
            {
                whereIndex = token.getCharPositionInLine() + 1;
            }
            if (text.equals("group"))
            {
                groupbyIndex = token.getCharPositionInLine() + 1;
            }
            if (text.equals("having"))
            {
                havingIndex = token.getCharPositionInLine() + 1;
            }
            if (text.equals("order"))
            {
                orderByIndex = token.getCharPositionInLine() + 1;
            }
            if (text.equals("union"))
            {
                unionIndexes.add(token.getCharPositionInLine() + 1);
            }
        }

        // If we have a union, break string into subselects and process each
        if (unionIndexes.size() != 0)
        {
            StringWriter changedSQL = new StringWriter();
            int lastIndex = 0;
            for (int i = 0; i < unionIndexes.size(); i++)
            {
                int index = unionIndexes.get(i);
                String fragment;
                if (i > 0)
                {
                    fragment = querySQL.substring(lastIndex + 5, index - 1);
                }
                else
                {
                    fragment = querySQL.substring(lastIndex, index - 1);
                }
                String lexedFragment = lexSampleSQL(fragment);

                if (i > 0)
                {
                    changedSQL.append("union ");
                }
                changedSQL.append(lexedFragment);
                lastIndex = index - 1;
            }

            // last part after last union
            String fragment = querySQL.substring(lastIndex + 5, querySQL.length());
            String lexedFragment = lexSampleSQL(fragment);
            changedSQL.append("union ");
            changedSQL.append(lexedFragment);

            return changedSQL.toString();
        }

        // Found a where clause, simplest cases
        if (whereIndex != -1)
        {
            StringWriter changedSQL = new StringWriter();
            String prefix = querySQL.substring(0, whereIndex + 5);
            String suffix = querySQL.substring(whereIndex + 5, querySQL.length());
            changedSQL.write(prefix);
            changedSQL.write("1=0 and ");
            changedSQL.write(suffix);
            return changedSQL.toString();
        }

        // No where clause, find group-by
        int insertIndex;
        if (groupbyIndex != -1)
        {
            insertIndex = groupbyIndex;
        }
        else if (havingIndex != -1)
        {
            insertIndex = havingIndex;
        }
        else if (orderByIndex != -1)
        {
            insertIndex = orderByIndex;
        }
        else
        {
            StringWriter changedSQL = new StringWriter();
            changedSQL.write(querySQL);
            changedSQL.write(" where 1=0 ");
            return changedSQL.toString();
        }

        try
        {
            StringWriter changedSQL = new StringWriter();
            String prefix = querySQL.substring(0, insertIndex - 1);
            changedSQL.write(prefix);
            changedSQL.write("where 1=0 ");
            String suffix = querySQL.substring(insertIndex - 1, querySQL.length());
            changedSQL.write(suffix);
            return changedSQL.toString();
        }
        catch (Exception ex)
        {
            String text = "Error constructing sample SQL to retrieve metadata for JDBC-drivers that don't support metadata, consider using the " + SAMPLE_WHERECLAUSE_PLACEHOLDER + " placeholder or providing a sample SQL";
            log.error(text, ex);
            throw new ExprValidationException(text, ex);
        }
    }
View Full Code Here

        }
        catch (SQLException ex)
        {
            String text = "Error preparing statement '" + preparedStatementText + '\'';
            log.error(text, ex);
            throw new ExprValidationException(text + ", reason: " + ex.getMessage());
        }

        // Interrogate prepared statement - parameters and result
        List<String> inputParameters = new LinkedList<String>();
        try
        {
            ParameterMetaData parameterMetaData = prepared.getParameterMetaData();
            inputParameters.addAll(Arrays.asList(parameters).subList(0, parameterMetaData.getParameterCount()));
        }
        catch (Exception ex)
        {
            try
            {
                prepared.close();
            }
            catch (SQLException e)
            {
                // don't handle
            }
            String text = "Error obtaining parameter metadata from prepared statement, consider turning off metadata interrogation via configuration, for statement '" + preparedStatementText + '\'';
            log.error(text, ex);
            throw new ExprValidationException(text + ", please check the statement, reason: " + ex.getMessage());
        }

        Map<String, DBOutputTypeDesc> outputProperties;
        try
        {
            outputProperties = compileResultMetaData(prepared.getMetaData(), metadataSetting);
        }
        catch (SQLException ex)
        {
            try
            {
                prepared.close();
            }
            catch (SQLException e)
            {
                // don't handle
            }
            String text = "Error in statement '" + preparedStatementText + "', failed to obtain result metadata, consider turning off metadata interrogation via configuration";
            log.error(text, ex);
            throw new ExprValidationException(text + ", please check the statement, reason: " + ex.getMessage());
        }

        if (log.isDebugEnabled())
        {
            log.debug(".createDBEventStream in=" + inputParameters.toString() +
                " out=" + outputProperties.toString());
        }

        // Close statement
        try
        {
            prepared.close();
        }
        catch (SQLException e)
        {
            String text = "Error closing prepared statement";
            log.error(text, e);
            throw new ExprValidationException(text + ", reason: " + e.getMessage());
        }

        return new QueryMetaData(inputParameters, outputProperties);
    }
View Full Code Here

        this.isJoin = isJoin;

        String hintValueMaxAge = HintEnum.RECLAIM_GROUP_AGED.getHintAssignedValue(reclaimGroupAged);
        if (hintValueMaxAge == null)
        {
            throw new ExprValidationException("Required hint value for hint '" + HintEnum.RECLAIM_GROUP_AGED + "' has not been provided");
        }
        evaluationFunctionMaxAge = getEvaluationFunction(variableService, hintValueMaxAge);

        String hintValueFrequency = HintEnum.RECLAIM_GROUP_FREQ.getHintAssignedValue(reclaimGroupAged);
        if ((reclaimGroupFrequency == null) || (hintValueFrequency == null))
View Full Code Here

        final VariableReader variableReader = variableService.getReader(hintValue);
        if (variableReader != null)
        {
            if (!JavaClassHelper.isNumeric(variableReader.getType()))
            {
                throw new ExprValidationException("Variable type of variable '" + variableReader.getVariableName() + "' is not numeric");
            }

            return new AggSvcGroupByReclaimAgedEvalFuncVariable(variableReader);
        }
        else
        {
            Double valueDouble;
            try
            {
                valueDouble = DoubleValue.parseString(hintValue);
            }
            catch (RuntimeException ex)
            {
                throw new ExprValidationException("Failed to parse hint parameter value '" + hintValue + "' as a double-typed seconds value or variable name");
            }
            if (valueDouble <= 0)
            {
                throw new ExprValidationException("Hint parameter value '" + hintValue + "' is an invalid value, expecting a double-typed seconds value or variable name");
            }
            return new AggSvcGroupByReclaimAgedEvalFuncConstant(valueDouble);
        }
    }
View Full Code Here

TOP

Related Classes of com.espertech.esper.epl.expression.ExprValidationException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.