Search in sources :

Example 96 with Or

use of org.wso2.siddhi.query.api.expression.condition.Or in project siddhi by wso2.

the class SimpleQueryTestCase method test3.

@Test
public void test3() throws SiddhiParserException {
    Query query = SiddhiCompiler.parseQuery("from AllStockQuotes#window.time(10 min)\n" + "select symbol as symbol, price, avg(price) as averagePrice \n" + "group by symbol \n" + "having ( price > ( averagePrice*1.02) ) or ( averagePrice > price ) " + "insert into FastMovingStockQuotes \n;");
    Query api = Query.query().from(InputStream.stream("AllStockQuotes").window("time", Expression.Time.minute(10))).select(Selector.selector().select("symbol", Expression.variable("symbol")).select(Expression.variable("price")).select("averagePrice", Expression.function("avg", Expression.variable("price"))).groupBy(Expression.variable("symbol")).having(Expression.or(Expression.compare(Expression.variable("price"), Compare.Operator.GREATER_THAN, Expression.multiply(Expression.variable("averagePrice"), Expression.value(1.02))), Expression.compare(Expression.variable("averagePrice"), Compare.Operator.GREATER_THAN, Expression.variable("price"))))).insertInto("FastMovingStockQuotes");
    AssertJUnit.assertEquals(api, query);
}
Also used : Query(org.wso2.siddhi.query.api.execution.query.Query) Test(org.testng.annotations.Test)

Example 97 with Or

use of org.wso2.siddhi.query.api.expression.condition.Or in project siddhi by wso2.

the class DocumentationUtils method generateDocumentation.

/**
 * Generate documentation related files using metadata
 *
 * @param namespaceMetaDataList      Metadata in this repository
 * @param documentationBaseDirectory The path of the directory in which the documentation will be generated
 * @param documentationVersion       The version of the documentation being generated
 * @param logger                     The logger to log errors
 * @throws MojoFailureException if the Mojo fails to find template file or create new documentation file
 */
public static void generateDocumentation(List<NamespaceMetaData> namespaceMetaDataList, String documentationBaseDirectory, String documentationVersion, Log logger) throws MojoFailureException {
    // Generating data model
    Map<String, Object> rootDataModel = new HashMap<>();
    rootDataModel.put("metaData", namespaceMetaDataList);
    rootDataModel.put("formatDescription", new FormatDescriptionMethod());
    rootDataModel.put("latestDocumentationVersion", documentationVersion);
    String outputFileRelativePath = Constants.API_SUB_DIRECTORY + File.separator + documentationVersion + Constants.MARKDOWN_FILE_EXTENSION;
    generateFileFromTemplate(Constants.MARKDOWN_DOCUMENTATION_TEMPLATE + Constants.MARKDOWN_FILE_EXTENSION + Constants.FREEMARKER_TEMPLATE_FILE_EXTENSION, rootDataModel, documentationBaseDirectory, outputFileRelativePath);
    File newVersionFile = new File(documentationBaseDirectory + File.separator + outputFileRelativePath);
    File latestLabelFile = new File(documentationBaseDirectory + File.separator + Constants.API_SUB_DIRECTORY + File.separator + Constants.LATEST_FILE_NAME + Constants.MARKDOWN_FILE_EXTENSION);
    try {
        Files.copy(newVersionFile, latestLabelFile);
    } catch (IOException e) {
        logger.warn("Failed to generate latest.md file", e);
    }
}
Also used : HashMap(java.util.HashMap) FormatDescriptionMethod(org.wso2.siddhi.doc.gen.core.freemarker.FormatDescriptionMethod) IOException(java.io.IOException) File(java.io.File)

Example 98 with Or

use of org.wso2.siddhi.query.api.expression.condition.Or in project siddhi by wso2.

the class PatternQueryTestCase method testPatternQuery6.

// from every (e1=Stream1[price >= 30]) -> e2=Stream1[ price >= 20] or e3=Stream2[ price >= e1.price] within 3 min
// -> e4=Stream3[price>74] within 2 min
// select e1.symbol, avg(e2.price ) as avgPrice
// insert into OutputStream
@Test
public void testPatternQuery6() {
    Query query = Query.query();
    query.from(InputStream.patternStream(State.next(State.every(State.stream(InputStream.stream("e1", "Stream1").filter(Expression.compare(Expression.variable("price"), Compare.Operator.GREATER_THAN_EQUAL, Expression.value(30))))), State.next(State.logicalOr(State.stream(InputStream.stream("e2", "Stream1").filter(Expression.compare(Expression.variable("price"), Compare.Operator.GREATER_THAN_EQUAL, Expression.value(20)))), State.stream(InputStream.stream("e3", "Stream2").filter(Expression.compare(Expression.variable("price"), Compare.Operator.GREATER_THAN_EQUAL, Expression.variable("price").ofStream("e1")))), Expression.Time.minute(3)), State.stream(InputStream.stream("e4", "Stream3").filter(Expression.compare(Expression.variable("price"), Compare.Operator.GREATER_THAN, Expression.value(74))))))));
    query.select(Selector.selector().select("symbol", Expression.variable("symbol").ofStream("e1")).select("avgPrice", Expression.function("avg", Expression.variable("price").ofStream("e2"))));
    query.insertInto("OutputStream");
}
Also used : Query(org.wso2.siddhi.query.api.execution.query.Query) Test(org.testng.annotations.Test)

Example 99 with Or

use of org.wso2.siddhi.query.api.expression.condition.Or in project carbon-apimgt by wso2.

the class ApiDAOImpl method getAPIsByStatus.

/**
 * @see ApiDAO#getAPIsByStatus(Set, List, List)
 */
@Override
@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
public List<API> getAPIsByStatus(Set<String> roles, List<String> statuses, List<String> labels) throws APIMgtDAOException {
    // check for null at the beginning before constructing the query to retrieve APIs from database
    if (roles == null || statuses == null) {
        String errorMessage = "Role list or API status list should not be null to retrieve APIs.";
        log.error(errorMessage);
        throw new APIMgtDAOException(errorMessage);
    }
    // the below query will be used to retrieve the union of,
    // published/prototyped APIs (statuses) with public visibility and
    // published/prototyped APIs with restricted visibility where APIs are restricted based on roles of the user
    String labelQuery = null;
    if (labels.isEmpty()) {
        labelQuery = "SELECT LABEL_ID FROM  AM_LABELS WHERE TYPE_NAME='STORE'";
    } else {
        labelQuery = "SELECT LABEL_ID FROM  AM_LABELS WHERE NAME IN ( " + DAOUtil.getParameterString(labels.size()) + ") AND TYPE_NAME='STORE'";
    }
    final String query = "Select UUID, PROVIDER, NAME, CONTEXT, VERSION, DESCRIPTION, CURRENT_LC_STATUS, " + "LIFECYCLE_INSTANCE_ID, LC_WORKFLOW_STATUS, SECURITY_SCHEME  FROM (" + API_SUMMARY_SELECT + " WHERE " + "VISIBILITY = '" + API.Visibility.PUBLIC + "' " + "AND " + "CURRENT_LC_STATUS  IN (" + DAOUtil.getParameterString(statuses.size()) + ") AND " + "API_TYPE_ID = (SELECT TYPE_ID FROM AM_API_TYPES WHERE TYPE_NAME = ?)" + "UNION " + API_SUMMARY_SELECT + " WHERE " + "VISIBILITY = '" + API.Visibility.RESTRICTED + "' " + "AND " + "UUID IN (SELECT API_ID FROM AM_API_VISIBLE_ROLES WHERE ROLE IN " + "(" + DAOUtil.getParameterString(roles.size()) + ")) " + " AND CURRENT_LC_STATUS  IN (" + DAOUtil.getParameterString(statuses.size()) + ") AND " + " API_TYPE_ID = (SELECT TYPE_ID FROM AM_API_TYPES WHERE TYPE_NAME = ?)) A" + " JOIN AM_API_LABEL_MAPPING LM ON A.UUID=LM.API_ID WHERE LM.LABEL_ID IN (" + labelQuery + ")";
    try (Connection connection = DAOUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(query)) {
        int i = 0;
        // put desired API status into the query (to get APIs with public visibility)
        for (String status : statuses) {
            statement.setString(++i, status);
        }
        statement.setString(++i, ApiType.STANDARD.toString());
        // put desired roles into the query
        for (String role : roles) {
            statement.setString(++i, role);
        }
        // put desired API status into the query (to get APIs with restricted visibility)
        for (String status : statuses) {
            statement.setString(++i, status);
        }
        statement.setString(++i, ApiType.STANDARD.toString());
        // Set the label names in the query
        for (String label : labels) {
            statement.setString(++i, label);
        }
        return constructAPISummaryList(connection, statement);
    } catch (SQLException e) {
        String errorMessage = "Error while retrieving API list in store.";
        throw new APIMgtDAOException(errorMessage, e);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 100 with Or

use of org.wso2.siddhi.query.api.expression.condition.Or in project carbon-apimgt by wso2.

the class ApplicationDAOImpl method getApplication.

/**
 * Retrieve a given instance of an Application
 *
 * @param appId The UUID that uniquely identifies an Application
 * @return valid {@link Application} object or null
 * @throws APIMgtDAOException   If failed to retrieve application.
 */
@Override
public Application getApplication(String appId) throws APIMgtDAOException {
    final String completeGetAppQuery = GET_APPS_WITH_POLICY_QUERY + " AND APPLICATION.UUID = ?";
    Application application;
    try (Connection conn = DAOUtil.getConnection();
        PreparedStatement ps = conn.prepareStatement(completeGetAppQuery)) {
        ps.setString(1, appId);
        try (ResultSet rs = ps.executeQuery()) {
            application = this.createApplicationFromResultSet(rs);
            if (application == null) {
                throw new APIMgtDAOException("Application is not available in the system.", ExceptionCodes.APPLICATION_NOT_FOUND);
            }
            application.setApplicationKeys(getApplicationKeys(appId));
        }
    } catch (SQLException ex) {
        throw new APIMgtDAOException(DAOUtil.DAO_ERROR_PREFIX + "getting application: " + appId, ex);
    }
    return application;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Application(org.wso2.carbon.apimgt.core.models.Application)

Aggregations

Test (org.testng.annotations.Test)170 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)156 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)152 InputHandler (org.wso2.siddhi.core.stream.input.InputHandler)149 TestUtil (org.wso2.siddhi.core.TestUtil)76 Event (org.wso2.siddhi.core.event.Event)66 ArrayList (java.util.ArrayList)51 QueryCallback (org.wso2.siddhi.core.query.output.callback.QueryCallback)44 HashMap (java.util.HashMap)38 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)30 IOException (java.io.IOException)24 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)24 StreamCallback (org.wso2.siddhi.core.stream.output.StreamCallback)21 Map (java.util.Map)18 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)17 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)16 File (java.io.File)13 List (java.util.List)13 Response (feign.Response)11 Attribute (org.wso2.charon3.core.attributes.Attribute)10