├── docs ├── images │ ├── favicon.ico │ ├── siddhi-logo.png │ ├── siddhi-logo-w.png │ ├── siddhi-logo.svg │ └── siddhi-logo-w.svg ├── javascripts │ └── extra.js ├── stylesheets │ └── extra.css ├── index.md ├── api │ ├── 1.0.0.md │ ├── 1.0.1.md │ ├── 1.0.2.md │ ├── 1.0.3.md │ └── 1.0.4.md └── license.md ├── .gitignore ├── issue_template.md ├── findbugs-exclude.xml ├── component ├── src │ ├── test │ │ ├── resources │ │ │ ├── log4j.properties │ │ │ └── testng.xml │ │ └── java │ │ │ └── org │ │ │ └── wso2 │ │ │ └── extension │ │ │ └── siddhi │ │ │ └── execution │ │ │ └── env │ │ │ ├── util │ │ │ ├── LoggerCallBack.java │ │ │ └── LoggerAppender.java │ │ │ ├── GetOriginIPFromXForwardedFunctionTestCase.java │ │ │ ├── GetSystemPropertyFunctionExtensionTestCase.java │ │ │ ├── GetEnvironmentPropertyFunctionExtensionTestCase.java │ │ │ └── ResourceIdentifierStreamProcessorTestCase.java │ └── main │ │ └── java │ │ └── org │ │ └── wso2 │ │ └── extension │ │ └── siddhi │ │ └── execution │ │ └── env │ │ ├── GetOriginIPFromXForwardedFunction.java │ │ ├── GetEnvironmentPropertyFunction.java │ │ ├── GetSystemPropertyFunction.java │ │ ├── GetUserAgentPropertyFunction.java │ │ ├── ResourceIdentifierStreamProcessor.java │ │ └── GetYAMLPropertyFunction.java └── pom.xml ├── mkdocs.yml ├── pull_request_template.md ├── pom.xml ├── README.md └── LICENSE /docs/images/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/this/siddhi-execution-env/master/docs/images/favicon.ico -------------------------------------------------------------------------------- /docs/images/siddhi-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/this/siddhi-execution-env/master/docs/images/siddhi-logo.png -------------------------------------------------------------------------------- /docs/images/siddhi-logo-w.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/this/siddhi-execution-env/master/docs/images/siddhi-logo-w.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.ear 17 | *.zip 18 | *.tar.gz 19 | *.rar 20 | 21 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 22 | hs_err_pid* 23 | 24 | # IDE files 25 | .idea/ 26 | *.iml 27 | 28 | # doc site 29 | site/ 30 | 31 | # remove target 32 | 33 | target/ -------------------------------------------------------------------------------- /issue_template.md: -------------------------------------------------------------------------------- 1 | **Description:** 2 | 3 | 4 | **Suggested Labels:** 5 | 6 | 7 | **Suggested Assignees:** 8 | 9 | 10 | **Affected Product Version:** 11 | 12 | **OS, DB, other environment details and versions:** 13 | 14 | **Steps to reproduce:** 15 | 16 | 17 | **Related Issues:** 18 | -------------------------------------------------------------------------------- /docs/javascripts/extra.js: -------------------------------------------------------------------------------- 1 | /* 2 | ~ Copyright (c) WSO2 Inc. (http://wso2.com) All Rights Reserved. 3 | ~ 4 | ~ Licensed under the Apache License, Version 2.0 (the "License"); 5 | ~ you may not use this file except in compliance with the License. 6 | ~ You may obtain a copy of the License at 7 | ~ 8 | ~ http://www.apache.org/licenses/LICENSE-2.0 9 | ~ 10 | ~ Unless required by applicable law or agreed to in writing, software 11 | ~ distributed under the License is distributed on an "AS IS" BASIS, 12 | ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | ~ See the License for the specific language governing permissions and 14 | ~ limitations under the License. 15 | */ 16 | 17 | var logoTitle = document.querySelector('.md-logo').title; 18 | var extentionTitle = logoTitle.slice(7); 19 | var header = document.querySelector('.md-header-nav__title'); 20 | 21 | header.innerHTML = '' + extentionTitle + '' + headerContent; 22 | 23 | -------------------------------------------------------------------------------- /findbugs-exclude.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /component/src/test/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | # 4 | # WSO2 Inc. licenses this file to you under the Apache License, 5 | # Version 2.0 (the "License"); you may not use this file except 6 | # in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | # 18 | log4j.rootLogger=INFO, stdout, testNG 19 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 20 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 21 | log4j.appender.stdout.layout.ConversionPattern=%m%n 22 | #log4j.appender.stdout.layout.ConversionPattern=[%t] %-5p %c %x - %m%n 23 | 24 | log4j.appender.testNG=org.wso2.extension.siddhi.execution.env.util.LoggerAppender 25 | log4j.appender.testNG.layout=org.apache.log4j.EnhancedPatternLayout 26 | log4j.appender.testNG.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m% 27 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: Siddhi Execution Env 2 | site_description: Siddhi Execution Env Extension 3 | site_author: WSO2 4 | site_url: https://wso2-extensions.github.io/siddhi-execution-env/ 5 | extra_css: 6 | - stylesheets/extra.css 7 | extra_javascript: 8 | - javascripts/extra.js 9 | repo_name: Siddhi-Execution-Env 10 | repo_url: https://github.com/wso2-extensions/siddhi-execution-env 11 | copyright: Copyright © 2011 - 2018 WSO2 12 | theme: 13 | name: material 14 | logo: images/siddhi-logo-w.svg 15 | favicon: images/favicon.ico 16 | palette: 17 | primary: teal 18 | accent: teal 19 | google_analytics: 20 | - UA-103065-28 21 | - auto 22 | extra: 23 | social: 24 | - type: github 25 | link: https://github.com/wso2/siddhi 26 | - type: linkedin 27 | link: https://www.linkedin.com/groups/13553064 28 | markdown_extensions: 29 | - admonition 30 | - toc(permalink=true) 31 | - codehilite(guess_lang=false) 32 | pages: 33 | - Welcome: index.md 34 | - API Docs: 35 | - 1.0.13: api/1.0.13.md 36 | - 1.0.12: api/1.0.12.md 37 | - 1.0.11: api/1.0.11.md 38 | - 1.0.10: api/1.0.10.md 39 | - 1.0.9: api/1.0.9.md 40 | - 1.0.8: api/1.0.8.md 41 | - 1.0.7: api/1.0.7.md 42 | - 1.0.6: api/1.0.6.md 43 | - 1.0.5: api/1.0.5.md 44 | - 1.0.4: api/1.0.4.md 45 | - 1.0.3: api/1.0.3.md 46 | - 1.0.2: api/1.0.2.md 47 | - 1.0.1: api/1.0.1.md 48 | - 1.0.0: api/1.0.0.md 49 | - latest: api/latest.md 50 | - License: license.md 51 | -------------------------------------------------------------------------------- /docs/stylesheets/extra.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | .md-header-nav__button.md-logo img { 20 | width: 140px; 21 | height: 33px; 22 | margin-right: 0; 23 | } 24 | 25 | .md-content__icon, 26 | .md-footer-nav__button, 27 | .md-header-nav__button, 28 | .md-nav__button, 29 | .md-nav__title::before, 30 | .md-search-result__article--document::before { 31 | margin: 0.3rem; 32 | padding: 0; 33 | } 34 | 35 | .extention-title { 36 | font-weight: 700; 37 | margin-right: 50px; 38 | } 39 | 40 | .md-header-nav__title { 41 | padding-left: 5px; 42 | } 43 | 44 | @media (max-width: 1219px) { 45 | 46 | .extention-title { 47 | display: none; 48 | } 49 | 50 | html .md-nav--primary .md-nav__title--site .md-nav__button { 51 | width: 13.4rem; 52 | } 53 | } -------------------------------------------------------------------------------- /component/src/test/java/org/wso2/extension/siddhi/execution/env/util/LoggerCallBack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package org.wso2.extension.siddhi.execution.env.util; 20 | 21 | import java.util.regex.Pattern; 22 | 23 | /** 24 | * Logger event call back will be matching the pattern with each log event and 25 | * invoke receiver method for each matching event. 26 | */ 27 | public abstract class LoggerCallBack { 28 | private String regexPattern; 29 | 30 | public LoggerCallBack(String regexPattern) { 31 | this.regexPattern = regexPattern; 32 | } 33 | 34 | public abstract void receive(String logEventMessage); 35 | 36 | public void receiveLoggerEvent(String logEventMessage) { 37 | boolean isMatcherFound = Pattern.compile(regexPattern).matcher(logEventMessage).find(); 38 | if (isMatcherFound) { 39 | receive(logEventMessage); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /component/src/test/resources/testng.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /component/src/test/java/org/wso2/extension/siddhi/execution/env/util/LoggerAppender.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package org.wso2.extension.siddhi.execution.env.util; 20 | 21 | import org.apache.log4j.AppenderSkeleton; 22 | import org.apache.log4j.spi.LoggingEvent; 23 | 24 | /** 25 | * The custom log4j appender for appending the log event generated while running the tests in TestNG. 26 | * Configuration for the appender defined in the test/resource/log4j.property file. 27 | * 28 | * log4j.appender.testNG=org.wso2.extension.siddhi.execution.env.util.LoggerAppender 29 | * log4j.appender.testNG.layout=org.apache.log4j.EnhancedPatternLayout 30 | * log4j.appender.testNG.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m% 31 | * 32 | * To enable the appender, set in the root logger, 33 | * log4j.rootLogger=INFO, stdout, testNG 34 | */ 35 | 36 | public class LoggerAppender extends AppenderSkeleton { 37 | private static LoggerCallBack loggerCallBack; 38 | 39 | public static void setLoggerCallBack(LoggerCallBack loggerCallBack) { 40 | LoggerAppender.loggerCallBack = loggerCallBack; 41 | } 42 | 43 | @Override 44 | protected void append(final LoggingEvent event) { 45 | if (loggerCallBack != null) { 46 | loggerCallBack.receiveLoggerEvent((String) event.getMessage()); 47 | } 48 | } 49 | 50 | @Override 51 | public void close() { 52 | } 53 | 54 | @Override 55 | public boolean requiresLayout() { 56 | return true; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /pull_request_template.md: -------------------------------------------------------------------------------- 1 | ## Purpose 2 | > Describe the problems, issues, or needs driving this feature/fix and include links to related issues in the following format: Resolves issue1, issue2, etc. 3 | 4 | ## Goals 5 | > Describe the solutions that this feature/fix will introduce to resolve the problems described above 6 | 7 | ## Approach 8 | > Describe how you are implementing the solutions. Include an animated GIF or screenshot if the change affects the UI (email documentation@wso2.com to review all UI text). Include a link to a Markdown file or Google doc if the feature write-up is too long to paste here. 9 | 10 | ## User stories 11 | > Summary of user stories addressed by this change> 12 | 13 | ## Release note 14 | > Brief description of the new feature or bug fix as it will appear in the release notes 15 | 16 | ## Documentation 17 | > Link(s) to product documentation that addresses the changes of this PR. If no doc impact, enter “N/A” plus brief explanation of why there’s no doc impact 18 | 19 | ## Training 20 | > Link to the PR for changes to the training content in https://github.com/wso2/WSO2-Training, if applicable 21 | 22 | ## Certification 23 | > Type “Sent” when you have provided new/updated certification questions, plus four answers for each question (correct answer highlighted in bold), based on this change. Certification questions/answers should be sent to certification@wso2.com and NOT pasted in this PR. If there is no impact on certification exams, type “N/A” and explain why. 24 | 25 | ## Marketing 26 | > Link to drafts of marketing content that will describe and promote this feature, including product page changes, technical articles, blog posts, videos, etc., if applicable 27 | 28 | ## Automation tests 29 | - Unit tests 30 | > Code coverage information 31 | - Integration tests 32 | > Details about the test cases and coverage 33 | 34 | ## Security checks 35 | - Followed secure coding standards in http://wso2.com/technical-reports/wso2-secure-engineering-guidelines? yes/no 36 | - Ran FindSecurityBugs plugin and verified report? yes/no 37 | - Confirmed that this PR doesn't commit any keys, passwords, tokens, usernames, or other secrets? yes/no 38 | 39 | ## Samples 40 | > Provide high-level details about the samples related to this feature 41 | 42 | ## Related PRs 43 | > List any other related PRs 44 | 45 | ## Migrations (if applicable) 46 | > Describe migration steps and platforms on which migration has been tested 47 | 48 | ## Test environment 49 | > List all JDK versions, operating systems, databases, and browser/versions on which this feature/fix was tested 50 | 51 | ## Learning 52 | > Describe the research phase and any blog posts, patterns, libraries, or add-ons you used to solve the problem. -------------------------------------------------------------------------------- /docs/images/siddhi-logo.svg: -------------------------------------------------------------------------------- 1 | 18 | 19 | 20 | 21 | 22 | 23 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 21 | 4.0.0 22 | 23 | 24 | org.wso2 25 | wso2 26 | 5 27 | 28 | 29 | org.wso2.extension.siddhi.execution.env 30 | siddhi-execution-env-parent 31 | pom 32 | 1.0.14-SNAPSHOT 33 | WSO2 Siddhi Execution Extension - env Pom 34 | http://wso2.org 35 | 36 | 37 | 38 | default 39 | 40 | true 41 | 42 | 43 | component 44 | 45 | 46 | 47 | 48 | 4.2.17 49 | 1.2.17.wso2v1 50 | 6.11 51 | 0.7.9 52 | 1.3.0.wso2v1 53 | 1.17 54 | [4.0.0, 5.0.0) 55 | [1.17.0,2.0.0) 56 | 3.0.0 57 | findbugs-exclude.xml 58 | 59 | 60 | scm:git:https://github.com/wso2-extensions/siddhi-execution-env.git 61 | https://github.com/wso2-extensions/siddhi-execution-env.git 62 | scm:git:https://github.com/wso2-extensions/siddhi-execution-env.git 63 | 64 | HEAD 65 | 66 | 67 | 68 | 69 | org.wso2.siddhi 70 | siddhi-core 71 | ${siddhi.version} 72 | 73 | 74 | org.wso2.siddhi 75 | siddhi-query-api 76 | ${siddhi.version} 77 | 78 | 79 | org.apache.log4j.wso2 80 | log4j 81 | ${log4j.version} 82 | 83 | 84 | org.testng 85 | testng 86 | ${testng.version} 87 | test 88 | 89 | 90 | org.wso2.siddhi 91 | siddhi-query-compiler 92 | ${siddhi.version} 93 | 94 | 95 | org.wso2.siddhi 96 | siddhi-annotations 97 | ${siddhi.version} 98 | 99 | 100 | ua.parser.wso2 101 | ua-parser 102 | ${orbit.version.ua_parser} 103 | 104 | 105 | org.yaml 106 | snakeyaml 107 | ${org.snakeyaml.version} 108 | 109 | 110 | org.awaitility 111 | awaitility 112 | test 113 | ${awaitility.version} 114 | 115 | 116 | 117 | 118 | 119 | 120 | org.apache.maven.plugins 121 | maven-release-plugin 122 | 123 | clean install -Pdocumentation-deploy 124 | true 125 | 126 | 127 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Siddhi Execution Extension - Env 2 | ====================================== 3 | 4 | The **siddhi-execution-env extension** is an extension to Siddhi that provides the capability to read environment properties inside Siddhi stream definitions and use it inside queries. Functions of the env extension are as follows.. 5 | 6 | Find some useful links below: 7 | 8 | * Source code 9 | * Releases 10 | * Issue tracker 11 | 12 | ## Latest API Docs 13 | 14 | Latest API Docs is 1.0.13. 15 | 16 | ## How to use 17 | 18 | **Using the extension in WSO2 Stream Processor** 19 | 20 | * You can use this extension in the latest WSO2 Stream Processor that is a part of WSO2 Analytics offering, with editor, debugger and simulation support. 21 | 22 | * This extension is shipped by default with WSO2 Stream Processor, if you wish to use an alternative version of this extension you can replace the component jar that can be found in the `/lib` 23 | directory. 24 | 25 | **Using the extension as a java library** 26 | 27 | * This extension can be added as a maven dependency along with other Siddhi dependencies to your project. 28 | 29 | ``` 30 | 31 | org.wso2.extension.siddhi.execution.env 32 | siddhi-execution-env 33 | x.x.x 34 | 35 | ``` 36 | 37 | ## Jenkins Build Status 38 | 39 | --- 40 | 41 | | Branch | Build Status | 42 | | :------ |:------------ | 43 | | master | [![Build Status](https://wso2.org/jenkins/view/All%20Builds/job/siddhi/job/siddhi-execution-env/badge/icon)](https://wso2.org/jenkins/view/All%20Builds/job/siddhi/job/siddhi-execution-env/) | 44 | 45 | --- 46 | 47 | ## Features 48 | 49 | * getEnvironmentProperty *(Function)*

This function returns the Java environment property that corresponds with the key provided

50 | * getOriginIPFromXForwarded *(Function)*

This function returns the public origin IP from the given X-Forwarded header.

51 | * getSystemProperty *(Function)*

This function returns the system property referred to via the system property key.

52 | * getUserAgentProperty *(Function)*

This function returns the value that corresponds with a specified property name of a specified user agent

53 | * getYAMLProperty *(Function)*

This function returns the YAML property requested or the default values specified if such avariable is not specified in the 'deployment.yaml'.

54 | * resourceIdentifier *(Stream Processor)*

The resource identifier stream processor is an extension to register a resource name with a reference in a static map and serve a static resources count for a specific resource name.

55 | * resourceBatch *(Window)*

This extension is a resource batch (tumbling) window that holds a number of events based on the resource count inferred from the 'env:resourceIdentifier' extension, and with a specific attribute as the grouping key. The window is updated each time a batch of events arrive with a matching value for the grouping key, and where the number of events is equal to the resource count.

56 | 57 | ## How to Contribute 58 | 59 | * Please report issues at GitHub Issue Tracker. 60 | 61 | * Send your contributions as pull requests to master branch. 62 | 63 | ## Contact us 64 | 65 | * Post your questions with the "Siddhi" tag in Stackoverflow. 66 | 67 | * Siddhi developers can be contacted via the mailing lists: 68 | 69 | Developers List : [dev@wso2.org](mailto:dev@wso2.org) 70 | 71 | Architecture List : [architecture@wso2.org](mailto:architecture@wso2.org) 72 | 73 | ## Support 74 | 75 | * We are committed to ensuring support for this extension in production. Our unique approach ensures that all support leverages our open development methodology and is provided by the very same engineers who build the technology. 76 | 77 | * For more details and to take advantage of this unique opportunity contact us via http://wso2.com/support/. 78 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | Siddhi Execution Extension - Env 2 | ====================================== 3 | 4 | The **siddhi-execution-env extension** is an extension to Siddhi that provides the capability to read environment properties inside Siddhi stream definitions and use it inside queries. Functions of the env extension are as follows.. 5 | 6 | Find some useful links below: 7 | 8 | * Source code 9 | * Releases 10 | * Issue tracker 11 | 12 | ## Latest API Docs 13 | 14 | Latest API Docs is 1.0.13. 15 | 16 | ## How to use 17 | 18 | **Using the extension in WSO2 Stream Processor** 19 | 20 | * You can use this extension in the latest WSO2 Stream Processor that is a part of WSO2 Analytics offering, with editor, debugger and simulation support. 21 | 22 | * This extension is shipped by default with WSO2 Stream Processor, if you wish to use an alternative version of this extension you can replace the component jar that can be found in the `/lib` 23 | directory. 24 | 25 | **Using the extension as a java library** 26 | 27 | * This extension can be added as a maven dependency along with other Siddhi dependencies to your project. 28 | 29 | ``` 30 | 31 | org.wso2.extension.siddhi.execution.env 32 | siddhi-execution-env 33 | x.x.x 34 | 35 | ``` 36 | 37 | ## Jenkins Build Status 38 | 39 | --- 40 | 41 | | Branch | Build Status | 42 | | :------ |:------------ | 43 | | master | [![Build Status](https://wso2.org/jenkins/view/All%20Builds/job/siddhi/job/siddhi-execution-env/badge/icon)](https://wso2.org/jenkins/view/All%20Builds/job/siddhi/job/siddhi-execution-env/) | 44 | 45 | --- 46 | 47 | ## Features 48 | 49 | * getEnvironmentProperty *(Function)*

This function returns the Java environment property that corresponds with the key provided

50 | * getOriginIPFromXForwarded *(Function)*

This function returns the public origin IP from the given X-Forwarded header.

51 | * getSystemProperty *(Function)*

This function returns the system property referred to via the system property key.

52 | * getUserAgentProperty *(Function)*

This function returns the value that corresponds with a specified property name of a specified user agent

53 | * getYAMLProperty *(Function)*

This function returns the YAML property requested or the default values specified if such avariable is not specified in the 'deployment.yaml'.

54 | * resourceIdentifier *(Stream Processor)*

The resource identifier stream processor is an extension to register a resource name with a reference in a static map and serve a static resources count for a specific resource name.

55 | * resourceBatch *(Window)*

This extension is a resource batch (tumbling) window that holds a number of events based on the resource count inferred from the 'env:resourceIdentifier' extension, and with a specific attribute as the grouping key. The window is updated each time a batch of events arrive with a matching value for the grouping key, and where the number of events is equal to the resource count.

56 | 57 | ## How to Contribute 58 | 59 | * Please report issues at GitHub Issue Tracker. 60 | 61 | * Send your contributions as pull requests to master branch. 62 | 63 | ## Contact us 64 | 65 | * Post your questions with the "Siddhi" tag in Stackoverflow. 66 | 67 | * Siddhi developers can be contacted via the mailing lists: 68 | 69 | Developers List : [dev@wso2.org](mailto:dev@wso2.org) 70 | 71 | Architecture List : [architecture@wso2.org](mailto:architecture@wso2.org) 72 | 73 | ## Support 74 | 75 | * We are committed to ensuring support for this extension in production. Our unique approach ensures that all support leverages our open development methodology and is provided by the very same engineers who build the technology. 76 | 77 | * For more details and to take advantage of this unique opportunity contact us via http://wso2.com/support/. 78 | -------------------------------------------------------------------------------- /component/src/test/java/org/wso2/extension/siddhi/execution/env/GetOriginIPFromXForwardedFunctionTestCase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package org.wso2.extension.siddhi.execution.env; 20 | 21 | import org.apache.log4j.Logger; 22 | import org.testng.AssertJUnit; 23 | import org.testng.annotations.BeforeMethod; 24 | import org.testng.annotations.Test; 25 | import org.wso2.siddhi.core.SiddhiAppRuntime; 26 | import org.wso2.siddhi.core.SiddhiManager; 27 | import org.wso2.siddhi.core.event.Event; 28 | import org.wso2.siddhi.core.query.output.callback.QueryCallback; 29 | import org.wso2.siddhi.core.stream.input.InputHandler; 30 | import org.wso2.siddhi.core.util.EventPrinter; 31 | 32 | import java.util.concurrent.atomic.AtomicInteger; 33 | 34 | public class GetOriginIPFromXForwardedFunctionTestCase { 35 | private static Logger logger = Logger.getLogger(GetOriginIPFromXForwardedFunctionTestCase.class); 36 | private AtomicInteger count = new AtomicInteger(0); 37 | private volatile boolean eventArrived; 38 | 39 | @BeforeMethod 40 | public void init() { 41 | count.set(0); 42 | eventArrived = false; 43 | } 44 | 45 | @Test 46 | public void testDefaultBehaviour1() throws Exception { 47 | logger.info("GetOriginIPFromXForwardedFunction default behaviour testCase"); 48 | SiddhiManager siddhiManager = new SiddhiManager(); 49 | String stream = "define stream inputStream (xForwardedHeader string);\n"; 50 | String query = ("@info(name = 'query1') from inputStream \n" 51 | + "select env:getOriginIPFromXForwarded(xForwardedHeader) as originIP \n" + 52 | "insert into outputStream;"); 53 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 54 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 55 | @Override 56 | public void receive(long timeStamp, Event[] inEvents, 57 | Event[] removeEvents) { 58 | EventPrinter.print(timeStamp, inEvents, removeEvents); 59 | for (Event event : inEvents) { 60 | count.incrementAndGet(); 61 | switch (count.get()) { 62 | case 1: 63 | AssertJUnit.assertEquals(null, event.getData(0)); 64 | eventArrived = true; 65 | break; 66 | case 2: 67 | AssertJUnit.assertEquals("203.160.190.196", event.getData(0)); 68 | eventArrived = true; 69 | break; 70 | case 3: 71 | AssertJUnit.assertEquals(null, event.getData(0)); 72 | eventArrived = true; 73 | break; 74 | case 4: 75 | AssertJUnit.assertEquals("203.160.190.198", event.getData(0)); 76 | eventArrived = true; 77 | break; 78 | case 5: 79 | AssertJUnit.assertEquals("199.207.253.101", event.getData(0)); 80 | eventArrived = true; 81 | break; 82 | case 6: 83 | AssertJUnit.assertEquals("208.160.190.198", event.getData(0)); 84 | eventArrived = true; 85 | break; 86 | case 7: 87 | AssertJUnit.assertEquals("210.160.190.198", event.getData(0)); 88 | eventArrived = true; 89 | break; 90 | case 8: 91 | AssertJUnit.assertEquals("70.41.3.18", event.getData(0)); 92 | eventArrived = true; 93 | break; 94 | case 9: 95 | AssertJUnit.assertEquals("70.41.3.18", event.getData(0)); 96 | eventArrived = true; 97 | break; 98 | case 10: 99 | AssertJUnit.assertEquals("70.41.3.18", event.getData(0)); 100 | eventArrived = true; 101 | break; 102 | case 11: 103 | AssertJUnit.assertEquals("14.3.49.206", event.getData(0)); 104 | eventArrived = true; 105 | break; 106 | case 12: 107 | AssertJUnit.assertEquals("210.160.190.217", event.getData(0)); 108 | eventArrived = true; 109 | break; 110 | case 13: 111 | AssertJUnit.assertEquals("210.160.180.117", event.getData(0)); 112 | eventArrived = true; 113 | break; 114 | } 115 | } 116 | } 117 | }); 118 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("inputStream"); 119 | siddhiAppRuntime.start(); 120 | inputHandler.send(new Object[]{" "}); 121 | inputHandler.send(new Object[]{"203.160.190.196,10.1.1.1"}); 122 | inputHandler.send(new String[]{"192.168.1.103"}); 123 | inputHandler.send(new String[]{"192.168.1.103, 203.160.190.198"}); 124 | inputHandler.send(new String[]{"10.3.49.206, 199.207.253.101"}); 125 | inputHandler.send(new String[]{"10.3.49.206, 192.168.1.103, 208.160.190.198"}); 126 | inputHandler.send(new String[]{"10.3.50.233, 192.168.1.103, 210.160.190.198"}); 127 | inputHandler.send(new String[]{"10.4.49.234, 70.41.3.18 , 210.160.190.200"}); 128 | inputHandler.send(new String[]{"10.5.49.216, 70.41.3.18, 192.168.1.103, 210.160.190.208"}); 129 | inputHandler.send(new String[]{"10.3.39.226, 70.41.3.18, 192.168.1.103, a.a.a.a"}); 130 | inputHandler.send(new String[]{"14.3.49.206, , 192.168.1.103, 210.160.190.208"}); 131 | inputHandler.send(new String[]{", a.a.a.a, 192.168.1.103, 210.160.190.217"}); 132 | inputHandler.send(new String[]{",, 192.168.1.103, 210.160.180.117"}); 133 | AssertJUnit.assertEquals(13, count.get()); 134 | AssertJUnit.assertTrue(eventArrived); 135 | siddhiAppRuntime.shutdown(); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /docs/images/siddhi-logo-w.svg: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 34 | 36 | 37 | 39 | image/svg+xml 40 | 42 | 43 | 44 | 45 | 47 | 67 | 71 | 75 | 76 | 81 | 86 | 90 | 94 | 98 | 99 | 103 | 107 | 108 | 112 | 116 | 120 | 121 | 126 | 131 | 135 | 139 | 143 | 144 | 148 | 152 | 153 | 157 | 161 | 162 | 163 | -------------------------------------------------------------------------------- /docs/api/1.0.0.md: -------------------------------------------------------------------------------- 1 | # API Docs - v1.0.0 2 | 3 | ## Env 4 | 5 | ### getEnvironmentProperty *(Function)* 6 | 7 |

This function returns Java environment property corresponding to the key provided

8 | 9 | Syntax 10 | ``` 11 | env:getEnvironmentProperty( key, default.value) 12 | ``` 13 | 14 | QUERY PARAMETERS 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
keyThis specifies Key of the property to be read.STRINGNoNo
default.valueThis specifies the default Value to be returned if the property value is not available.nullSTRINGYesNo
41 | 42 | Examples 43 | EXAMPLE 1 44 | ``` 45 | define stream keyStream (key string); 46 | from keyStream env:getEnvironmentProperty(key) as FunctionOutput 47 | insert into outputStream; 48 | ``` 49 |

This query returns Java environment property corresponding to the key from keyStream as FunctionOutput to the outputStream

50 | 51 | ### getSystemProperty *(Function)* 52 | 53 |

This function returns the system property pointed by the system property key

54 | 55 | Syntax 56 | ``` 57 | env:getSystemProperty( key, default.value) 58 | ``` 59 | 60 | QUERY PARAMETERS 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
keyThis specifies Key of the property to be read.STRINGNoNo
default.valueThis specifies the default Value to be returned if the property value is not available.nullSTRINGYesNo
87 | 88 | Examples 89 | EXAMPLE 1 90 | ``` 91 | define stream keyStream (key string); 92 | from keyStream env:getSystemProperty(key) as FunctionOutput 93 | insert into outputStream; 94 | ``` 95 |

This query returns system property corresponding to the key from keyStream as FunctionOutput to the outputStream

96 | 97 | ### getYAMLProperty *(Function)* 98 | 99 |

This function returns the YAML property requested or the default values specified if such avariable is not available in the deployment.yaml

100 | 101 | Syntax 102 | ``` 103 | env:getYAMLProperty( key, data.type, default.value) 104 | ``` 105 | 106 | QUERY PARAMETERS 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
keyThis specifies Key of the property to be read.STRINGNoNo
data.typeA string constant parameter expressing the data type of the propertyusing one of the following string values: int, long, float, double, string, bool.stringSTRINGNoNo
default.valueThis specifies the default Value to be returned if the property value is not available.nullINT
LONG
DOUBLE
FLOAT
STRING
BOOL
YesNo
141 | 142 | Examples 143 | EXAMPLE 1 144 | ``` 145 | define stream keyStream (key string); 146 | from keyStream env:getYAMLProperty(key) as FunctionOutput 147 | insert into outputStream; 148 | ``` 149 |

This query returns corresponding YAML property for the corresponding key from keyStream as FunctionOutput to the outputStream

150 | 151 | -------------------------------------------------------------------------------- /docs/api/1.0.1.md: -------------------------------------------------------------------------------- 1 | # API Docs - v1.0.1 2 | 3 | ## Env 4 | 5 | ### getEnvironmentProperty *(Function)* 6 | 7 |

This function returns Java environment property corresponding to the key provided

8 | 9 | Syntax 10 | ``` 11 | env:getEnvironmentProperty( key, default.value) 12 | ``` 13 | 14 | QUERY PARAMETERS 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
keyThis specifies Key of the property to be read.STRINGNoNo
default.valueThis specifies the default Value to be returned if the property value is not available.nullSTRINGYesNo
41 | 42 | Examples 43 | EXAMPLE 1 44 | ``` 45 | define stream keyStream (key string); 46 | from keyStream env:getEnvironmentProperty(key) as FunctionOutput 47 | insert into outputStream; 48 | ``` 49 |

This query returns Java environment property corresponding to the key from keyStream as FunctionOutput to the outputStream

50 | 51 | ### getSystemProperty *(Function)* 52 | 53 |

This function returns the system property pointed by the system property key

54 | 55 | Syntax 56 | ``` 57 | env:getSystemProperty( key, default.value) 58 | ``` 59 | 60 | QUERY PARAMETERS 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
keyThis specifies Key of the property to be read.STRINGNoNo
default.valueThis specifies the default Value to be returned if the property value is not available.nullSTRINGYesNo
87 | 88 | Examples 89 | EXAMPLE 1 90 | ``` 91 | define stream keyStream (key string); 92 | from keyStream env:getSystemProperty(key) as FunctionOutput 93 | insert into outputStream; 94 | ``` 95 |

This query returns system property corresponding to the key from keyStream as FunctionOutput to the outputStream

96 | 97 | ### getYAMLProperty *(Function)* 98 | 99 |

This function returns the YAML property requested or the default values specified if such avariable is not available in the deployment.yaml

100 | 101 | Syntax 102 | ``` 103 | env:getYAMLProperty( key, data.type, default.value) 104 | ``` 105 | 106 | QUERY PARAMETERS 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
keyThis specifies Key of the property to be read.STRINGNoNo
data.typeA string constant parameter expressing the data type of the propertyusing one of the following string values: int, long, float, double, string, bool.stringSTRINGNoNo
default.valueThis specifies the default Value to be returned if the property value is not available.nullINT
LONG
DOUBLE
FLOAT
STRING
BOOL
YesNo
141 | 142 | Examples 143 | EXAMPLE 1 144 | ``` 145 | define stream keyStream (key string); 146 | from keyStream env:getYAMLProperty(key) as FunctionOutput 147 | insert into outputStream; 148 | ``` 149 |

This query returns corresponding YAML property for the corresponding key from keyStream as FunctionOutput to the outputStream

150 | 151 | -------------------------------------------------------------------------------- /docs/api/1.0.2.md: -------------------------------------------------------------------------------- 1 | # API Docs - v1.0.2 2 | 3 | ## Env 4 | 5 | ### getEnvironmentProperty *(Function)* 6 | 7 |

This function returns Java environment property corresponding to the key provided

8 | 9 | Syntax 10 | ``` 11 | env:getEnvironmentProperty( key, default.value) 12 | ``` 13 | 14 | QUERY PARAMETERS 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
keyThis specifies Key of the property to be read.STRINGNoNo
default.valueThis specifies the default Value to be returned if the property value is not available.nullSTRINGYesNo
41 | 42 | Examples 43 | EXAMPLE 1 44 | ``` 45 | define stream keyStream (key string); 46 | from keyStream env:getEnvironmentProperty(key) as FunctionOutput 47 | insert into outputStream; 48 | ``` 49 |

This query returns Java environment property corresponding to the key from keyStream as FunctionOutput to the outputStream

50 | 51 | ### getSystemProperty *(Function)* 52 | 53 |

This function returns the system property pointed by the system property key

54 | 55 | Syntax 56 | ``` 57 | env:getSystemProperty( key, default.value) 58 | ``` 59 | 60 | QUERY PARAMETERS 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
keyThis specifies Key of the property to be read.STRINGNoNo
default.valueThis specifies the default Value to be returned if the property value is not available.nullSTRINGYesNo
87 | 88 | Examples 89 | EXAMPLE 1 90 | ``` 91 | define stream keyStream (key string); 92 | from keyStream env:getSystemProperty(key) as FunctionOutput 93 | insert into outputStream; 94 | ``` 95 |

This query returns system property corresponding to the key from keyStream as FunctionOutput to the outputStream

96 | 97 | ### getYAMLProperty *(Function)* 98 | 99 |

This function returns the YAML property requested or the default values specified if such avariable is not available in the deployment.yaml

100 | 101 | Syntax 102 | ``` 103 | env:getYAMLProperty( key, data.type, default.value) 104 | ``` 105 | 106 | QUERY PARAMETERS 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
keyThis specifies Key of the property to be read.STRINGNoNo
data.typeA string constant parameter expressing the data type of the propertyusing one of the following string values: int, long, float, double, string, bool.stringSTRINGNoNo
default.valueThis specifies the default Value to be returned if the property value is not available.nullINT
LONG
DOUBLE
FLOAT
STRING
BOOL
YesNo
141 | 142 | Examples 143 | EXAMPLE 1 144 | ``` 145 | define stream keyStream (key string); 146 | from keyStream env:getYAMLProperty(key) as FunctionOutput 147 | insert into outputStream; 148 | ``` 149 |

This query returns corresponding YAML property for the corresponding key from keyStream as FunctionOutput to the outputStream

150 | 151 | -------------------------------------------------------------------------------- /component/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 21 | 22 | siddhi-execution-env-parent 23 | org.wso2.extension.siddhi.execution.env 24 | 1.0.14-SNAPSHOT 25 | 26 | 4.0.0 27 | siddhi-execution-env 28 | siddhi-execution-env 29 | bundle 30 | 31 | 32 | org.wso2.siddhi 33 | siddhi-core 34 | 35 | 36 | org.wso2.siddhi 37 | siddhi-query-api 38 | 39 | 40 | org.apache.log4j.wso2 41 | log4j 42 | 43 | 44 | org.testng 45 | testng 46 | test 47 | 48 | 49 | org.wso2.siddhi 50 | siddhi-query-compiler 51 | 52 | 53 | org.wso2.siddhi 54 | siddhi-annotations 55 | 56 | 57 | ua.parser.wso2 58 | ua-parser 59 | 60 | 61 | org.yaml 62 | snakeyaml 63 | 64 | 65 | org.awaitility 66 | awaitility 67 | test 68 | 69 | 70 | 71 | 72 | documentation-deploy 73 | 74 | 75 | 76 | org.wso2.siddhi 77 | siddhi-doc-gen 78 | ${siddhi.version} 79 | 80 | 81 | compile 82 | 83 | deploy-mkdocs-github-pages 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | org.apache.felix 96 | maven-bundle-plugin 97 | true 98 | 99 | 100 | ${project.artifactId} 101 | ${project.artifactId} 102 | 103 | ua_parser.*;version="${orbit.version.ua_parser}" 104 | 105 | 106 | org.wso2.extension.siddhi.execution.env.* 107 | 108 | 109 | org.wso2.siddhi.*;version="${siddhi.import.version.range}", 110 | org.yaml.*;version="${org.snakeyaml.package.import.version.range}" 111 | 112 | 113 | META-INF=target/classes/META-INF 114 | 115 | 116 | 117 | 118 | 119 | org.apache.maven.plugins 120 | maven-compiler-plugin 121 | 122 | 1.8 123 | 1.8 124 | 125 | 126 | 127 | org.apache.maven.plugins 128 | maven-surefire-plugin 129 | 130 | false 131 | 132 | src/test/resources/testng.xml 133 | 134 | ${surefireArgLine} -ea -Xmx512m 135 | 136 | 137 | 138 | org.jacoco 139 | jacoco-maven-plugin 140 | ${jacoco.maven.version} 141 | 142 | 143 | jacoco-initialize 144 | 145 | prepare-agent 146 | 147 | 148 | ${basedir}/target/coverage-reports/jacoco.exec 149 | surefireArgLine 150 | 151 | 152 | 153 | jacoco-site 154 | post-integration-test 155 | 156 | report 157 | 158 | 159 | ${basedir}/target/coverage-reports/jacoco.exec 160 | ${basedir}/target/coverage-reports/ 161 | 162 | 163 | 164 | 165 | 166 | org.wso2.siddhi 167 | siddhi-doc-gen 168 | ${siddhi.version} 169 | 170 | 171 | compile 172 | 173 | generate-md-docs 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | -------------------------------------------------------------------------------- /component/src/test/java/org/wso2/extension/siddhi/execution/env/GetSystemPropertyFunctionExtensionTestCase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package org.wso2.extension.siddhi.execution.env; 20 | 21 | import org.apache.log4j.Logger; 22 | import org.testng.AssertJUnit; 23 | import org.testng.annotations.Test; 24 | import org.wso2.siddhi.core.SiddhiAppRuntime; 25 | import org.wso2.siddhi.core.SiddhiManager; 26 | import org.wso2.siddhi.core.event.Event; 27 | import org.wso2.siddhi.core.exception.SiddhiAppCreationException; 28 | import org.wso2.siddhi.core.query.output.callback.QueryCallback; 29 | import org.wso2.siddhi.core.stream.input.InputHandler; 30 | import org.wso2.siddhi.core.util.EventPrinter; 31 | 32 | /** 33 | * Test case for GetSystemPropertyFunction function extension. 34 | */ 35 | 36 | public class GetSystemPropertyFunctionExtensionTestCase { 37 | 38 | private static Logger logger = Logger.getLogger(GetEnvironmentPropertyFunctionExtensionTestCase.class); 39 | 40 | @Test 41 | public void testDefaultBehaviour() throws Exception { 42 | logger.info("GetSystemPropertyFunctionExtensionTestDefaultBehaviour TestCase"); 43 | 44 | SiddhiManager siddhiManager = new SiddhiManager(); 45 | 46 | String stream = "define stream inputStream (key string);\n"; 47 | 48 | String query = ("@info(name = 'query1') from inputStream " 49 | + "select env:getSystemProperty(key) as propertyValue " 50 | + "insert into outputStream;"); 51 | 52 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 53 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 54 | @Override 55 | public void receive(long timeStamp, Event[] inEvents, 56 | Event[] removeEvents) { 57 | EventPrinter.print(timeStamp, inEvents, removeEvents); 58 | String result; 59 | for (Event event : inEvents) { 60 | result = (String) event.getData(0); 61 | AssertJUnit.assertEquals(System.getenv("JAVA_HOME"), result); 62 | } 63 | } 64 | }); 65 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("inputStream"); 66 | siddhiAppRuntime.start(); 67 | inputHandler.send(new String[]{"JAVA_HOME"}); 68 | siddhiAppRuntime.shutdown(); 69 | } 70 | 71 | @Test 72 | public void testDefaultBehaviourWithWithDefaultValueProvided() throws Exception { 73 | logger.info("GetSystemPropertyFunctionExtensionTestDefaultBehaviourWithWithDefaultValueProvided TestCase"); 74 | 75 | SiddhiManager siddhiManager = new SiddhiManager(); 76 | 77 | String stream = "define stream inputStream (key string);\n"; 78 | 79 | String query = ("@info(name = 'query1') from inputStream " 80 | + "select env:getSystemProperty(key,'defaultValue') as propertyValue " 81 | + "insert into outputStream;"); 82 | 83 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 84 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 85 | @Override 86 | public void receive(long timeStamp, Event[] inEvents, 87 | Event[] removeEvents) { 88 | EventPrinter.print(timeStamp, inEvents, removeEvents); 89 | String result; 90 | for (Event event : inEvents) { 91 | result = (String) event.getData(0); 92 | AssertJUnit.assertEquals(System.getenv("JAVA_HOME"), result); 93 | } 94 | } 95 | }); 96 | InputHandler inputHandler = siddhiAppRuntime 97 | .getInputHandler("inputStream"); 98 | siddhiAppRuntime.start(); 99 | inputHandler.send(new String[]{"JAVA_HOME"}); 100 | siddhiAppRuntime.shutdown(); 101 | } 102 | 103 | @Test 104 | public void testDefaultBehaviourWithWithDefaultValueProvided2() throws Exception { 105 | logger.info("GetSystemPropertyFunctionExtensionTestDefaultBehaviourWithWithDefaultValueProvided TestCase2"); 106 | 107 | SiddhiManager siddhiManager = new SiddhiManager(); 108 | 109 | String stream = "define stream inputStream (key string);\n"; 110 | 111 | String query = ("@info(name = 'query1') from inputStream " 112 | + "select env:getSystemProperty(key,'defaultValue') as propertyValue " 113 | + "insert into outputStream;"); 114 | 115 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 116 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 117 | @Override 118 | public void receive(long timeStamp, Event[] inEvents, 119 | Event[] removeEvents) { 120 | EventPrinter.print(timeStamp, inEvents, removeEvents); 121 | String result; 122 | for (Event event : inEvents) { 123 | result = (String) event.getData(0); 124 | AssertJUnit.assertEquals("defaultValue", result); 125 | } 126 | } 127 | }); 128 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("inputStream"); 129 | siddhiAppRuntime.start(); 130 | inputHandler.send(new String[]{"NOT_JAVA_HOME"}); 131 | siddhiAppRuntime.shutdown(); 132 | } 133 | 134 | @Test(expectedExceptions = SiddhiAppCreationException.class) 135 | public void exceptionTestCaseNonStringKey() { 136 | logger.info("GetSystemPropertyFunctionExtension exceptionTestCaseNonStringKey"); 137 | 138 | SiddhiManager siddhiManager = new SiddhiManager(); 139 | 140 | String stream = "define stream inputStream (key string);\n"; 141 | 142 | String query = ("@info(name = 'query1') from inputStream " 143 | + "select env:getSystemProperty(5) as functionOutput " 144 | + "insert into outputStream;"); 145 | 146 | siddhiManager.createSiddhiAppRuntime(stream + query); 147 | } 148 | 149 | 150 | @Test(expectedExceptions = SiddhiAppCreationException.class) 151 | public void exceptionTestCaseNullKey() { 152 | logger.info("GetSystemPropertyFunctionExtension exceptionTestCaseNullKey"); 153 | 154 | SiddhiManager siddhiManager = new SiddhiManager(); 155 | 156 | String stream = "define stream inputStream (key string);\n"; 157 | 158 | String query = ("@info(name = 'query1') from inputStream " 159 | + "select env:getSystemProperty() as functionOutput " 160 | + "insert into outputStream;"); 161 | 162 | siddhiManager.createSiddhiAppRuntime(stream + query); 163 | } 164 | 165 | @Test(expectedExceptions = SiddhiAppCreationException.class) 166 | public void exceptionTestCaseNonStringDefault() { 167 | logger.info("GetSystemPropertyFunctionExtension exceptionTestCaseNonStringDefault"); 168 | 169 | SiddhiManager siddhiManager = new SiddhiManager(); 170 | 171 | String stream = "define stream inputStream (key string);\n"; 172 | 173 | String query = ("@info(name = 'query1') from inputStream " 174 | + "select env:getSystemProperty(key, 5) as functionOutput " 175 | + "insert into outputStream;"); 176 | 177 | siddhiManager.createSiddhiAppRuntime(stream + query); 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /component/src/test/java/org/wso2/extension/siddhi/execution/env/GetEnvironmentPropertyFunctionExtensionTestCase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package org.wso2.extension.siddhi.execution.env; 20 | 21 | 22 | import org.apache.log4j.Logger; 23 | import org.testng.AssertJUnit; 24 | import org.testng.annotations.Test; 25 | import org.wso2.siddhi.core.SiddhiAppRuntime; 26 | import org.wso2.siddhi.core.SiddhiManager; 27 | import org.wso2.siddhi.core.event.Event; 28 | import org.wso2.siddhi.core.exception.SiddhiAppCreationException; 29 | import org.wso2.siddhi.core.query.output.callback.QueryCallback; 30 | import org.wso2.siddhi.core.stream.input.InputHandler; 31 | import org.wso2.siddhi.core.util.EventPrinter; 32 | 33 | /** 34 | * Test case for GetEnvironmentPropertyFunction function extension. 35 | */ 36 | 37 | public class GetEnvironmentPropertyFunctionExtensionTestCase { 38 | 39 | private static Logger logger = Logger.getLogger(GetEnvironmentPropertyFunctionExtensionTestCase.class); 40 | 41 | @Test 42 | public void testDefaultBehaviour() throws Exception { 43 | logger.info("GetEnvironmentPropertyFunctionExtensionTestDefaultBehaviour TestCase"); 44 | 45 | SiddhiManager siddhiManager = new SiddhiManager(); 46 | 47 | String stream = "define stream inputStream (key string);\n"; 48 | 49 | String query = ("@info(name = 'query1') from inputStream " 50 | + "select env:getEnvironmentProperty(key) as propertyValue " 51 | + "insert into outputStream;"); 52 | 53 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 54 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 55 | @Override 56 | public void receive(long timeStamp, Event[] inEvents, 57 | Event[] removeEvents) { 58 | EventPrinter.print(timeStamp, inEvents, removeEvents); 59 | String result; 60 | for (Event event : inEvents) { 61 | result = (String) event.getData(0); 62 | AssertJUnit.assertEquals(System.getProperty("os.name"), result); 63 | } 64 | } 65 | }); 66 | InputHandler inputHandler = siddhiAppRuntime 67 | .getInputHandler("inputStream"); 68 | siddhiAppRuntime.start(); 69 | inputHandler.send(new String[]{"os.name"}); 70 | siddhiAppRuntime.shutdown(); 71 | } 72 | 73 | @Test 74 | public void testDefaultBehaviourWithWithDefaultValueProvided() throws Exception { 75 | logger.info("GetEnvironmentPropertyFunctionExtensionTestDefaultBehaviourWithWithDefaultValueProvided TestCase"); 76 | 77 | SiddhiManager siddhiManager = new SiddhiManager(); 78 | 79 | String stream = "define stream inputStream (key string);\n"; 80 | 81 | String query = ("@info(name = 'query1') from inputStream " 82 | + "select env:getEnvironmentProperty(key,'defaultValue') as propertyValue " 83 | + "insert into outputStream;"); 84 | 85 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 86 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 87 | @Override 88 | public void receive(long timeStamp, Event[] inEvents, 89 | Event[] removeEvents) { 90 | EventPrinter.print(timeStamp, inEvents, removeEvents); 91 | String result; 92 | for (Event event : inEvents) { 93 | result = (String) event.getData(0); 94 | AssertJUnit.assertEquals(System.getProperty("os.name"), result); 95 | } 96 | } 97 | }); 98 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("inputStream"); 99 | siddhiAppRuntime.start(); 100 | inputHandler.send(new String[]{"os.name"}); 101 | siddhiAppRuntime.shutdown(); 102 | } 103 | 104 | @Test 105 | public void testDefaultBehaviourWithWithDefaultValueProvided2() throws Exception { 106 | logger.info("GetEnvironmentPropertyFunctionExtensionTestDefaultBehaviourWithWithDefaultValueProvided " + 107 | "TestCase2"); 108 | 109 | SiddhiManager siddhiManager = new SiddhiManager(); 110 | 111 | String stream = "define stream inputStream (key string);\n"; 112 | 113 | String query = ("@info(name = 'query1') from inputStream " 114 | + "select env:getEnvironmentProperty(key,'defaultValue') as propertyValue " 115 | + "insert into outputStream;"); 116 | 117 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 118 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 119 | @Override 120 | public void receive(long timeStamp, Event[] inEvents, 121 | Event[] removeEvents) { 122 | EventPrinter.print(timeStamp, inEvents, removeEvents); 123 | String result; 124 | for (Event event : inEvents) { 125 | result = (String) event.getData(0); 126 | AssertJUnit.assertEquals("defaultValue", result); 127 | } 128 | } 129 | }); 130 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("inputStream"); 131 | siddhiAppRuntime.start(); 132 | inputHandler.send(new String[]{"not.os.name"}); 133 | siddhiAppRuntime.shutdown(); 134 | } 135 | 136 | @Test(expectedExceptions = SiddhiAppCreationException.class) 137 | public void exceptionTestCaseNonStringKey() { 138 | logger.info("GetEnvironmentPropertyFunctionExtension exceptionTestCaseNonStringKey"); 139 | 140 | SiddhiManager siddhiManager = new SiddhiManager(); 141 | 142 | String stream = "define stream inputStream (key string);\n"; 143 | 144 | String query = ("@info(name = 'query1') from inputStream " 145 | + "select env:getEnvironmentProperty(5) as functionOutput " 146 | + "insert into outputStream;"); 147 | 148 | siddhiManager.createSiddhiAppRuntime(stream + query); 149 | } 150 | 151 | 152 | @Test(expectedExceptions = SiddhiAppCreationException.class) 153 | public void exceptionTestCaseNullKey() { 154 | logger.info("GetEnvironmentPropertyFunctionExtension exceptionTestCaseNullKey"); 155 | 156 | SiddhiManager siddhiManager = new SiddhiManager(); 157 | 158 | String stream = "define stream inputStream (key string);\n"; 159 | 160 | String query = ("@info(name = 'query1') from inputStream " 161 | + "select env:getEnvironmentProperty() as functionOutput " 162 | + "insert into outputStream;"); 163 | 164 | siddhiManager.createSiddhiAppRuntime(stream + query); 165 | } 166 | 167 | @Test(expectedExceptions = SiddhiAppCreationException.class) 168 | public void exceptionTestCaseNonStringDefault() { 169 | logger.info("GetEnvironmentPropertyFunctionExtension exceptionTestCaseNonStringDefault"); 170 | 171 | SiddhiManager siddhiManager = new SiddhiManager(); 172 | 173 | String stream = "define stream inputStream (key string);\n"; 174 | 175 | String query = ("@info(name = 'query1') from inputStream " 176 | + "select env:getEnvironmentProperty(key , 5) as functionOutput " 177 | + "insert into outputStream;"); 178 | 179 | siddhiManager.createSiddhiAppRuntime(stream + query); 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /component/src/main/java/org/wso2/extension/siddhi/execution/env/GetOriginIPFromXForwardedFunction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package org.wso2.extension.siddhi.execution.env; 20 | 21 | import org.wso2.siddhi.annotation.Example; 22 | import org.wso2.siddhi.annotation.Extension; 23 | import org.wso2.siddhi.annotation.Parameter; 24 | import org.wso2.siddhi.annotation.ReturnAttribute; 25 | import org.wso2.siddhi.annotation.util.DataType; 26 | import org.wso2.siddhi.core.config.SiddhiAppContext; 27 | import org.wso2.siddhi.core.executor.ExpressionExecutor; 28 | import org.wso2.siddhi.core.executor.function.FunctionExecutor; 29 | import org.wso2.siddhi.core.util.config.ConfigReader; 30 | import org.wso2.siddhi.query.api.definition.Attribute; 31 | import org.wso2.siddhi.query.api.exception.SiddhiAppValidationException; 32 | 33 | import java.util.Map; 34 | import java.util.regex.Matcher; 35 | import java.util.regex.Pattern; 36 | 37 | /** 38 | * This class provides a function to get immediate public IP of the origin from X-Forwarded-For header. 39 | */ 40 | @Extension( 41 | name = "getOriginIPFromXForwarded", 42 | namespace = "env", 43 | description = "This function returns the public origin IP from the given X-Forwarded header.", 44 | returnAttributes = @ReturnAttribute( 45 | description = "The public IP related to the origin that is retrieved using the given 'X-Forwarded' " + 46 | "header.", 47 | type = {DataType.STRING}), 48 | parameters = { 49 | @Parameter(name = "xforwardedheader", 50 | description = "The 'X-Forwarded-For' header of the request.", 51 | type = {DataType.STRING} 52 | ) 53 | }, 54 | examples = { 55 | @Example( 56 | syntax = "define stream InputStream (xForwardedHeader string);\n" + 57 | "from InputStream " + 58 | "select env:getOriginIPFromXForwarded(xForwardedHeader) as originIP \n" + 59 | "insert into OutputStream;", 60 | description = "This query returns the public origin IP from the given X-Forwarded header as" + 61 | " 'originIP', and inserts it to the 'OutputStream' stream." 62 | ) 63 | } 64 | ) 65 | public class GetOriginIPFromXForwardedFunction extends FunctionExecutor { 66 | 67 | private static final String IP_ADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + 68 | "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + 69 | "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + 70 | "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; 71 | private static final String PRIVATE_IP_ADDRESS_PATTERN = "(^127\\..*)|(^10\\..*)|(^172\\.1[6-9]\\..*)|" + 72 | "(^172\\.2[0-9]\\..*)|(^172\\.3[0-1]\\..*)|(^192\\.168\\..*)"; 73 | private static Pattern ipPAddressPattern = Pattern.compile(IP_ADDRESS_PATTERN); 74 | private static Pattern privateIPPAddressPattern = Pattern.compile(PRIVATE_IP_ADDRESS_PATTERN); 75 | 76 | /** 77 | * The initialization method for GetOriginIPFromXForwardedFunction, 78 | * this method will be called before the other methods. 79 | * 80 | * @param attributeExpressionExecutors the executors of each function parameter. 81 | * @param siddhiAppContext the context of the execution plan. 82 | */ 83 | protected void init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader reader, 84 | SiddhiAppContext siddhiAppContext) { 85 | if (attributeExpressionExecutors.length != 1) { 86 | throw new SiddhiAppValidationException("Invalid no of arguments passed to env:getOriginIPFromXForwarded" + 87 | "() function, required 1, but found " + attributeExpressionExecutors.length); 88 | } 89 | 90 | Attribute.Type attributeType = attributeExpressionExecutors[0].getReturnType(); 91 | if (attributeType != Attribute.Type.STRING) { 92 | throw new SiddhiAppValidationException("Invalid parameter type found for first argument " + 93 | "'xForwardedHeader' of env:getOriginIPFromXForwarded() function, required " + Attribute.Type 94 | .STRING + ", but found " + attributeType.toString()); 95 | } 96 | 97 | } 98 | 99 | /** 100 | * The main execution method which will be called upon event arrival 101 | * when there are more than one function parameter. 102 | * 103 | * @param data the runtime values of function parameters. 104 | * @return the function result. 105 | */ 106 | @Override 107 | protected Object execute(Object[] data) { 108 | //we only allow single parameter for this function 109 | return null; 110 | } 111 | 112 | /** 113 | * The main execution method which will be called upon event arrival 114 | * when there are zero or one function parameter. 115 | * 116 | * @param data null if the function parameter count is zero or 117 | * runtime data value of the function parameter. 118 | * @return the function result. 119 | */ 120 | @Override 121 | protected Object execute(Object data) { 122 | String xForwardedFor = data.toString(); 123 | if (xForwardedFor.isEmpty()) { 124 | return null; 125 | } 126 | String extractedIPs[] = xForwardedFor.split(",", -1); 127 | Matcher privateIPAddressMatcher; 128 | Matcher ipAddressMatcher; 129 | String filteredPublicIp = null; 130 | String extractedIP; 131 | for (int i = 0, extractedIPsLength = extractedIPs.length; i < extractedIPsLength; i++) { 132 | extractedIP = extractedIPs[i].trim(); 133 | privateIPAddressMatcher = privateIPPAddressPattern.matcher(extractedIP); 134 | if (!privateIPAddressMatcher.matches()) { 135 | ipAddressMatcher = ipPAddressPattern.matcher(extractedIP); 136 | if (ipAddressMatcher.matches()) { 137 | filteredPublicIp = extractedIP; 138 | break; 139 | } 140 | 141 | } 142 | } 143 | return filteredPublicIp; 144 | } 145 | 146 | /** 147 | * This will be called only once and this can be used to acquire 148 | * required resources for the processing element. 149 | * This will be called after initializing the system and before 150 | * starting to process the events. 151 | */ 152 | 153 | @Override 154 | public Attribute.Type getReturnType() { 155 | return Attribute.Type.STRING; 156 | } 157 | 158 | /** 159 | * Used to collect the serializable state of the processing element, that need to be 160 | * persisted for the reconstructing the element to the same state on a different point of time. 161 | * 162 | * @return stateful objects of the processing element as an array. 163 | */ 164 | @Override 165 | public Map currentState() { 166 | return null; 167 | } 168 | 169 | /** 170 | * Used to restore serialized state of the processing element, for reconstructing 171 | * the element to the same state as if was on a previous point of time. 172 | * 173 | * @param state the stateful objects of the element as an array on 174 | * the same order provided by currentState(). 175 | */ 176 | @Override 177 | public void restoreState(Map state) { 178 | 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /component/src/main/java/org/wso2/extension/siddhi/execution/env/GetEnvironmentPropertyFunction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | package org.wso2.extension.siddhi.execution.env; 19 | 20 | import org.wso2.siddhi.annotation.Example; 21 | import org.wso2.siddhi.annotation.Extension; 22 | import org.wso2.siddhi.annotation.Parameter; 23 | import org.wso2.siddhi.annotation.ReturnAttribute; 24 | import org.wso2.siddhi.annotation.util.DataType; 25 | import org.wso2.siddhi.core.config.SiddhiAppContext; 26 | import org.wso2.siddhi.core.exception.SiddhiAppRuntimeException; 27 | import org.wso2.siddhi.core.executor.ExpressionExecutor; 28 | import org.wso2.siddhi.core.executor.function.FunctionExecutor; 29 | import org.wso2.siddhi.core.util.config.ConfigReader; 30 | import org.wso2.siddhi.query.api.definition.Attribute; 31 | import org.wso2.siddhi.query.api.exception.SiddhiAppValidationException; 32 | 33 | import java.util.Map; 34 | 35 | /** 36 | * Siddhi Function getEnvironmentProperty to read Java environment Properties. 37 | */ 38 | 39 | @Extension( 40 | name = "getEnvironmentProperty", 41 | namespace = "env", 42 | description = "This function returns the Java environment property that corresponds with the key provided", 43 | returnAttributes = @ReturnAttribute( 44 | description = "A string value is returned.", 45 | type = {org.wso2.siddhi.annotation.util.DataType.STRING}), 46 | parameters = { 47 | @Parameter(name = "key", 48 | description = "This specifies the key of the property to be read.", 49 | type = {DataType.STRING}, 50 | optional = false), 51 | @Parameter(name = "default.value", 52 | description = "This specifies the default value to be returned if the property value is not" + 53 | " available.", 54 | type = {DataType.STRING}, 55 | optional = true, 56 | defaultValue = "null") 57 | }, 58 | examples = { 59 | @Example( 60 | syntax = "define stream keyStream (key string);\n" + 61 | "from keyStream env:getEnvironmentProperty(key) as FunctionOutput \n" + 62 | "insert into outputStream;", 63 | description = "This query returns the Java environment property that corresponds with " + 64 | "the key from the 'keyStream' as 'FunctionOutput' to the outputStream." 65 | ) 66 | } 67 | ) 68 | public class GetEnvironmentPropertyFunction extends FunctionExecutor { 69 | 70 | /** 71 | * The initialization method for GetEnvironmentPropertyFunction, 72 | * this method will be called before the other methods. 73 | * 74 | * @param attributeExpressionExecutors the executors of each function parameter. 75 | * @param siddhiAppContext the context of the execution plan. 76 | */ 77 | 78 | protected void init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader reader, 79 | SiddhiAppContext siddhiAppContext) { 80 | int attributeExpressionExecutorsLength = attributeExpressionExecutors.length; 81 | if ((attributeExpressionExecutorsLength > 0) && (attributeExpressionExecutorsLength < 3)) { 82 | Attribute.Type typeofKeyAttribute = attributeExpressionExecutors[0].getReturnType(); 83 | if (typeofKeyAttribute != Attribute.Type.STRING) { 84 | throw new SiddhiAppValidationException("Invalid parameter type found " + 85 | "for the argument key of getEnvironmentProperty() function, " + 86 | "required " + Attribute.Type.STRING + 87 | ", but found " + typeofKeyAttribute.toString()); 88 | } 89 | if (attributeExpressionExecutorsLength == 2) { 90 | Attribute.Type typeofDefaultValueAttribute = attributeExpressionExecutors[1].getReturnType(); 91 | if (typeofDefaultValueAttribute != Attribute.Type.STRING) { 92 | throw new SiddhiAppValidationException("Invalid parameter type found " + 93 | "for the argument default.value of getEnvironmentProperty() function, " + 94 | "required " + Attribute.Type.STRING + 95 | ", but found " + typeofDefaultValueAttribute.toString()); 96 | } 97 | } 98 | } else { 99 | throw new SiddhiAppValidationException("Invalid no of arguments passed to " + 100 | "env:getEnvironmentProperty(Key,default.value) function, " + 101 | "required 1 or 2, but found " + attributeExpressionExecutors.length); 102 | } 103 | } 104 | 105 | /** 106 | * The main execution method which will be called upon event arrival 107 | * when there are more than one function parameter. 108 | * 109 | * @param data the runtime values of function parameters. 110 | * @return the function result. 111 | */ 112 | @Override 113 | protected Object execute(Object[] data) { 114 | 115 | String key = (String) data[0]; 116 | String defaultValue = (String) data[1]; 117 | 118 | return System.getProperty(key, defaultValue); 119 | } 120 | 121 | /** 122 | * The main execution method which will be called upon event arrival 123 | * when there are zero or one function parameter. 124 | * 125 | * @param data null if the function parameter count is zero or 126 | * runtime data value of the function parameter. 127 | * @return the function result. 128 | */ 129 | @Override 130 | protected Object execute(Object data) { 131 | if (data != null) { 132 | if (data instanceof String) { 133 | String inputString = (String) data; 134 | return System.getProperty(inputString); 135 | } else { 136 | throw new SiddhiAppRuntimeException("Input to the getEnvironmentProperty() function must be a String"); 137 | } 138 | } else { 139 | throw new SiddhiAppRuntimeException("Input to the getEnvironmentProperty() function cannot be null"); 140 | } 141 | } 142 | 143 | /** 144 | * This will be called only once and this can be used to acquire 145 | * required resources for the processing element. 146 | * This will be called after initializing the system and before 147 | * starting to process the events. 148 | */ 149 | 150 | @Override 151 | public Attribute.Type getReturnType() { 152 | return Attribute.Type.STRING; 153 | } 154 | 155 | /** 156 | * Used to collect the serializable state of the processing element, that need to be 157 | * persisted for the reconstructing the element to the same state on a different point of time. 158 | * 159 | * @return stateful objects of the processing element as an array. 160 | */ 161 | @Override 162 | public Map currentState() { 163 | return null; 164 | } 165 | 166 | /** 167 | * Used to restore serialized state of the processing element, for reconstructing 168 | * the element to the same state as if was on a previous point of time. 169 | * 170 | * @param state the stateful objects of the element as an array on 171 | * the same order provided by currentState(). 172 | */ 173 | @Override 174 | public void restoreState(Map state) { 175 | //Implement restore state logic. 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /component/src/main/java/org/wso2/extension/siddhi/execution/env/GetSystemPropertyFunction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package org.wso2.extension.siddhi.execution.env; 20 | 21 | import org.wso2.siddhi.annotation.Example; 22 | import org.wso2.siddhi.annotation.Extension; 23 | import org.wso2.siddhi.annotation.Parameter; 24 | import org.wso2.siddhi.annotation.ReturnAttribute; 25 | import org.wso2.siddhi.annotation.util.DataType; 26 | import org.wso2.siddhi.core.config.SiddhiAppContext; 27 | import org.wso2.siddhi.core.exception.SiddhiAppRuntimeException; 28 | import org.wso2.siddhi.core.executor.ExpressionExecutor; 29 | import org.wso2.siddhi.core.executor.function.FunctionExecutor; 30 | import org.wso2.siddhi.core.util.config.ConfigReader; 31 | import org.wso2.siddhi.query.api.definition.Attribute; 32 | import org.wso2.siddhi.query.api.exception.SiddhiAppValidationException; 33 | 34 | import java.util.Map; 35 | 36 | 37 | /** 38 | * Siddhi Function getSystemProperty to read Operating system Properties. 39 | */ 40 | 41 | @Extension( 42 | name = "getSystemProperty", 43 | namespace = "env", 44 | description = "This function returns the system property referred to via the system property key.", 45 | returnAttributes = @ReturnAttribute( 46 | description = "A string value is returned.", 47 | type = {org.wso2.siddhi.annotation.util.DataType.STRING}), 48 | parameters = { 49 | @Parameter(name = "key", 50 | description = "This specifies the key of the property to be read.", 51 | type = {DataType.STRING}, 52 | optional = false), 53 | @Parameter(name = "default.value", 54 | description = "This specifies the default value to be returned " + 55 | "if the property value is not available.", 56 | type = {DataType.STRING}, 57 | optional = true, 58 | defaultValue = "null") 59 | }, 60 | examples = { 61 | @Example( 62 | syntax = "define stream KeyStream (key string);\n" + 63 | "from KeyStream env:getSystemProperty(key) as FunctionOutput \n" + 64 | "insert into OutputStream;", 65 | description = "This query returns the system property that corresponds with the key from" + 66 | " the 'KeyStream' stream as the 'FunctionOutput' to the 'OutputStream' stream." 67 | ) 68 | } 69 | ) 70 | 71 | public class GetSystemPropertyFunction extends FunctionExecutor { 72 | 73 | /** 74 | * The initialization method for GetSystemPropertyFunction, this method will be called before the other methods. 75 | * 76 | * @param attributeExpressionExecutors the executors of each function parameter. 77 | * @param siddhiAppContext the context of the execution plan. 78 | */ 79 | 80 | protected void init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader reader, 81 | SiddhiAppContext siddhiAppContext) { 82 | int attributeExpressionExecutorsLength = attributeExpressionExecutors.length; 83 | if ((attributeExpressionExecutorsLength > 0) && (attributeExpressionExecutorsLength < 3)) { 84 | Attribute.Type typeofKeyAttribute = attributeExpressionExecutors[0].getReturnType(); 85 | if (typeofKeyAttribute != Attribute.Type.STRING) { 86 | throw new SiddhiAppValidationException("Invalid parameter type found " + 87 | "for the argument key of getSystemProperty() function, " + 88 | "required " + Attribute.Type.STRING + 89 | ", but found " + typeofKeyAttribute.toString()); 90 | } 91 | if (attributeExpressionExecutorsLength == 2) { 92 | Attribute.Type typeofDefaultValueAttribute = attributeExpressionExecutors[1].getReturnType(); 93 | if (typeofDefaultValueAttribute != Attribute.Type.STRING) { 94 | throw new SiddhiAppValidationException("Invalid parameter type found " + 95 | "for the argument default.value of getSystemProperty() function, " + 96 | "required " + Attribute.Type.STRING + 97 | ", but found " + typeofDefaultValueAttribute.toString()); 98 | } 99 | } 100 | } else { 101 | throw new SiddhiAppValidationException("Invalid no of arguments passed to " + 102 | "env:getSystemProperty(Key, default.value) function, " + 103 | "required 1 or 2, but found " + attributeExpressionExecutors.length); 104 | } 105 | } 106 | 107 | /** 108 | * The main execution method which will be called upon event arrival 109 | * when there are more than one function parameter. 110 | * 111 | * @param data the runtime values of function parameters. 112 | * @return the function result. 113 | */ 114 | @Override 115 | protected Object execute(Object[] data) { 116 | 117 | String key = (String) data[0]; 118 | String defaultValue = (String) data[1]; 119 | 120 | String returnValue = System.getenv(key); 121 | 122 | return (returnValue != null) ? returnValue : defaultValue; 123 | } 124 | 125 | /** 126 | * The main execution method which will be called upon event arrival 127 | * when there are zero or one function parameter. 128 | * 129 | * @param data null if the function parameter count is zero or 130 | * runtime data value of the function parameter. 131 | * @return the function result. 132 | */ 133 | @Override 134 | protected Object execute(Object data) { 135 | if (data != null) { 136 | if (data instanceof String) { 137 | String key = (String) data; 138 | return System.getenv(key); 139 | } else { 140 | throw new SiddhiAppRuntimeException("Input to the getSystemProperty() function must be a String"); 141 | } 142 | } else { 143 | throw new SiddhiAppRuntimeException("Input to the getSystemProperty() function cannot be null"); 144 | } 145 | } 146 | 147 | /** 148 | * This will be called only once and this can be used to acquire 149 | * required resources for the processing element. 150 | * This will be called after initializing the system and before 151 | * starting to process the events. 152 | */ 153 | 154 | @Override 155 | public Attribute.Type getReturnType() { 156 | return Attribute.Type.STRING; 157 | } 158 | 159 | /** 160 | * Used to collect the serializable state of the processing element, that need to be 161 | * persisted for the reconstructing the element to the same state on a different point of time. 162 | * 163 | * @return stateful objects of the processing element as an array. 164 | */ 165 | @Override 166 | public Map currentState() { 167 | return null; 168 | } 169 | 170 | /** 171 | * Used to restore serialized state of the processing element, for reconstructing 172 | * the element to the same state as if was on a previous point of time. 173 | * 174 | * @param state the stateful objects of the element as an array on 175 | * the same order provided by currentState(). 176 | */ 177 | @Override 178 | public void restoreState(Map state) { 179 | //Implement restore state logic. 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /component/src/main/java/org/wso2/extension/siddhi/execution/env/GetUserAgentPropertyFunction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | package org.wso2.extension.siddhi.execution.env; 19 | 20 | import org.wso2.siddhi.annotation.Example; 21 | import org.wso2.siddhi.annotation.Extension; 22 | import org.wso2.siddhi.annotation.Parameter; 23 | import org.wso2.siddhi.annotation.ReturnAttribute; 24 | import org.wso2.siddhi.annotation.SystemParameter; 25 | import org.wso2.siddhi.annotation.util.DataType; 26 | import org.wso2.siddhi.core.config.SiddhiAppContext; 27 | import org.wso2.siddhi.core.exception.SiddhiAppCreationException; 28 | import org.wso2.siddhi.core.exception.SiddhiAppRuntimeException; 29 | import org.wso2.siddhi.core.executor.ConstantExpressionExecutor; 30 | import org.wso2.siddhi.core.executor.ExpressionExecutor; 31 | import org.wso2.siddhi.core.executor.function.FunctionExecutor; 32 | import org.wso2.siddhi.core.util.config.ConfigReader; 33 | import org.wso2.siddhi.query.api.definition.Attribute; 34 | import org.wso2.siddhi.query.api.exception.SiddhiAppValidationException; 35 | import ua_parser.Client; 36 | import ua_parser.OS; 37 | import ua_parser.Parser; 38 | import ua_parser.UserAgent; 39 | 40 | import java.io.FileInputStream; 41 | import java.io.FileNotFoundException; 42 | import java.io.IOException; 43 | import java.io.InputStream; 44 | import java.util.Arrays; 45 | import java.util.List; 46 | import java.util.Locale; 47 | import java.util.Map; 48 | 49 | /** 50 | * Siddhi Function getUserAgentPropertyFunction to extract properties from the user agent. 51 | */ 52 | @Extension( 53 | name = "getUserAgentProperty", 54 | namespace = "env", 55 | description = "This function returns the value that corresponds with a specified property name of a specified" + 56 | " user agent", 57 | returnAttributes = @ReturnAttribute( 58 | description = "The property to be extracted from the user agent.", 59 | type = {DataType.STRING}), 60 | parameters = { 61 | @Parameter(name = "user.agent", 62 | description = "This specifies the user agent from which the property needs to be extracted.", 63 | type = {DataType.STRING}), 64 | @Parameter(name = "property.name", 65 | description = "This specifies the property name that needs to be extracted. " + 66 | "Supported property names are 'browser', 'os', and 'device'.", 67 | type = {DataType.STRING}) 68 | }, 69 | systemParameter = { 70 | @SystemParameter( 71 | name = "regexFilePath", 72 | description = "The location of the yaml file that contains the regex to process the user " + 73 | "agent.", 74 | defaultValue = "Default regexes included in the ua_parser library", 75 | possibleParameters = "N/A" 76 | ) 77 | }, 78 | examples = { 79 | @Example( 80 | syntax = "define stream UserAgentStream (userAgent string);\n" + 81 | "from UserAgentStream \n" + 82 | "select env:getUserAgentProperty(userAgent, \"browser\") as " + 83 | "functionOutput \n" + 84 | "insert into OutputStream;", 85 | description = "This query returns the browser name of the 'userAgent' from the" + 86 | " 'UserAgentStream' stream as 'functionOutput', and inserts it into the " + 87 | "'OutputStream'stream." 88 | ) 89 | } 90 | ) 91 | public class GetUserAgentPropertyFunction extends FunctionExecutor { 92 | 93 | private static final String BROWSER = "browser"; 94 | private static final String OPERATING_SYSTEM = "os"; 95 | private static final String DEVICE = "device"; 96 | private final List listOfProperties = Arrays.asList(DEVICE, OPERATING_SYSTEM, BROWSER); 97 | private Parser uaParser; 98 | private String propertyName; 99 | 100 | @Override 101 | 102 | protected void init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader configReader, SiddhiAppContext 103 | siddhiAppContext) { 104 | 105 | int attributeExpressionExecutorsLength = attributeExpressionExecutors.length; 106 | if (attributeExpressionExecutorsLength == 2) { 107 | Attribute.Type typeofUserAgentAttribute = attributeExpressionExecutors[0].getReturnType(); 108 | if (typeofUserAgentAttribute != Attribute.Type.STRING) { 109 | throw new SiddhiAppValidationException("Invalid parameter type found " + 110 | "for the first argument 'user.agent' of getUserAgentProperty() function, " + 111 | "required " + Attribute.Type.STRING + 112 | ", but found '" + typeofUserAgentAttribute.toString() + "'."); 113 | } 114 | if (attributeExpressionExecutors[1] instanceof ConstantExpressionExecutor) { 115 | propertyName = ((ConstantExpressionExecutor) attributeExpressionExecutors[1]) 116 | .getValue().toString(); 117 | 118 | if (!listOfProperties.contains(propertyName.toLowerCase(Locale.ENGLISH))) { 119 | throw new SiddhiAppValidationException("Invalid parameter found " + 120 | "for the second argument 'property.name' of getUserAgentProperty() function, " + 121 | "required one of " + listOfProperties.toString() + ", but found " + propertyName); 122 | } 123 | } else { 124 | throw new SiddhiAppValidationException("Second parameter 'property.name' of getUserAgentProperty() " + 125 | "should be a constant, but found a dynamic attribute."); 126 | } 127 | } else { 128 | throw new SiddhiAppValidationException("Invalid no of arguments passed to " + 129 | "env:getUserAgentProperty(user.agent,property.name) function, " + 130 | "required 2, but found " + attributeExpressionExecutors.length); 131 | } 132 | String regexFilePath = configReader.readConfig("regexFilePath", ""); 133 | try { 134 | if (!regexFilePath.isEmpty()) { 135 | InputStream inputStream = new FileInputStream(regexFilePath); 136 | uaParser = new Parser(inputStream); 137 | } else { 138 | uaParser = new Parser(); 139 | } 140 | } catch (FileNotFoundException e) { 141 | throw new SiddhiAppCreationException("Regexes file is not found in the given location '" + regexFilePath + 142 | "', failed to initiate user agent parser.", e); 143 | } catch (IllegalArgumentException e) { 144 | throw new SiddhiAppCreationException("Invalid Regexes file found at " + regexFilePath + ", failed to " + 145 | "initiate user agent parser.", e); 146 | } catch (IOException e) { 147 | throw new SiddhiAppCreationException("Failed to initiate user agent parser for the Siddhi app.", e); 148 | } 149 | 150 | } 151 | 152 | protected Object execute(Object[] data) { 153 | String userAgent = (String) data[0]; 154 | switch (propertyName.toLowerCase(Locale.ENGLISH)) { 155 | case BROWSER: 156 | UserAgent agent = uaParser.parseUserAgent(userAgent); 157 | return agent.family; 158 | case OPERATING_SYSTEM: 159 | OS operatingSystem = uaParser.parseOS(userAgent); 160 | return operatingSystem.family; 161 | case DEVICE: 162 | Client clientParser = uaParser.parse(userAgent); 163 | return clientParser.device.family; 164 | // Default condition will never occur. 165 | default: 166 | return null; 167 | } 168 | } 169 | 170 | @Override 171 | protected Object execute(Object data) { 172 | // This function is never reached. 173 | throw new SiddhiAppRuntimeException("Number of parameters passed to getUserAgentProperty() function " + 174 | "is invalid"); 175 | } 176 | 177 | @Override 178 | public Attribute.Type getReturnType() { 179 | return Attribute.Type.STRING; 180 | } 181 | 182 | @Override 183 | public Map currentState() { 184 | return null; 185 | } 186 | 187 | @Override 188 | public void restoreState(Map state) { 189 | 190 | } 191 | 192 | } 193 | -------------------------------------------------------------------------------- /component/src/main/java/org/wso2/extension/siddhi/execution/env/ResourceIdentifierStreamProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package org.wso2.extension.siddhi.execution.env; 20 | 21 | import org.wso2.siddhi.annotation.Example; 22 | import org.wso2.siddhi.annotation.Extension; 23 | import org.wso2.siddhi.annotation.Parameter; 24 | import org.wso2.siddhi.annotation.util.DataType; 25 | import org.wso2.siddhi.core.config.SiddhiAppContext; 26 | import org.wso2.siddhi.core.event.ComplexEventChunk; 27 | import org.wso2.siddhi.core.event.stream.StreamEvent; 28 | import org.wso2.siddhi.core.event.stream.StreamEventCloner; 29 | import org.wso2.siddhi.core.event.stream.populater.ComplexEventPopulater; 30 | import org.wso2.siddhi.core.executor.ConstantExpressionExecutor; 31 | import org.wso2.siddhi.core.executor.ExpressionExecutor; 32 | import org.wso2.siddhi.core.query.processor.Processor; 33 | import org.wso2.siddhi.core.query.processor.stream.StreamProcessor; 34 | import org.wso2.siddhi.core.util.config.ConfigReader; 35 | import org.wso2.siddhi.query.api.definition.AbstractDefinition; 36 | import org.wso2.siddhi.query.api.definition.Attribute; 37 | import org.wso2.siddhi.query.api.exception.SiddhiAppValidationException; 38 | 39 | import java.util.ArrayList; 40 | import java.util.List; 41 | import java.util.Map; 42 | import java.util.concurrent.ConcurrentHashMap; 43 | 44 | /** 45 | * Siddhi Resource Identifier Stream Processor Extension to register the resources with name, and serve registered 46 | * resource count for given name. 47 | */ 48 | @Extension( 49 | name = "resourceIdentifier", 50 | namespace = "env", 51 | description = "The resource identifier stream processor is an extension to register a resource name with a" + 52 | " reference in a static map and serve a static resources count for a specific resource name.", 53 | parameters = { 54 | @Parameter(name = "resource.group.id", 55 | description = "The name of the resource group.", 56 | type = {DataType.STRING}) 57 | }, 58 | examples = { 59 | @Example( 60 | syntax = 61 | "@info(name='product_color_code_rule') \n" + 62 | "from SweetProductDefectsDetector#env:resourceIdentifier(\"rule-group-1\")\n" + 63 | "select productId, ifThenElse(colorCode == '#FF0000', true, false) as " + 64 | "isValid\n" + 65 | "insert into DefectDetectionResult;\n" + 66 | "\n" + 67 | "@info(name='product_dimensions_rule') \n" + 68 | "from SweetProductDefectsDetector#env:resourceIdentifier(\"rule-group-1\")\n" + 69 | "select productId, ifThenElse(height == 5 && width ==10, true, false) as " + 70 | "isValid\n" + 71 | "insert into DefectDetectionResult;\n" + 72 | "@info(name='defect_analyzer') \n" + 73 | "from DefectDetectionResult#window.env:resourceBatch(\"rule-group-1\", " + 74 | "productId, 60000)\n" + 75 | "select productId, and(not isValid) as isDefected\n" + 76 | "insert into SweetProductDefectAlert;", 77 | description = "'product_color_code_rule' and 'product_dimensions_rule' are two rule-based " + 78 | "queries that process the same events from the 'SweetProductDefectsDetector' stream." + 79 | " They both insert their process results as the output into the " + 80 | "'DefectDetectionResult' output stream.\n" + 81 | "\n" + 82 | "Multiple queries like this can be added in the Siddhi Application and the number of" + 83 | " output events inserted into the 'DefectDetectionResult' stream depends on the " + 84 | "number of available queries. If you need to further aggregate results for a " + 85 | "particular correlation ID ('productId' in this scenario) from the " + 86 | "'DefectDetectionResult' stream, follow-up queries need to wait for events with same" + 87 | " value for the 'productId' attribute from all the available queries. For this, " + 88 | "follow-up queries need to identify the number of events that can be expected from " + 89 | "these rule-based queries with a specific value for 'productID'. To address this " + 90 | "requirement, a resource identifier named 'rule-group-1' is assigned to both the " + 91 | "rule queries. The 'defect_analyzer' query includes the 'env:resourceBatch' window" + 92 | " to derive the count for the registered resource named 'rule-group-1' count from the" + 93 | " output of both the queries within a specific time period. All of these factors " + 94 | "determine the event waiting condition for events from the 'DefectDetectionResult'" + 95 | " stream." 96 | ) 97 | } 98 | ) 99 | public class ResourceIdentifierStreamProcessor extends StreamProcessor { 100 | private static Map> resourceIdentifyStreamProcessorMap = 101 | new ConcurrentHashMap<>(); 102 | private String resourceName; 103 | 104 | @Override 105 | protected void process(ComplexEventChunk complexEventChunk, Processor processor, 106 | StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) { 107 | nextProcessor.process(complexEventChunk); 108 | } 109 | 110 | @Override 111 | protected List init(AbstractDefinition abstractDefinition, ExpressionExecutor[] expressionExecutors, 112 | ConfigReader configReader, SiddhiAppContext siddhiAppContext) { 113 | int inputExecutorLength = attributeExpressionExecutors.length; 114 | if (inputExecutorLength == 1) { 115 | if (attributeExpressionExecutors[0] instanceof ConstantExpressionExecutor) { 116 | if (attributeExpressionExecutors[0].getReturnType() == Attribute.Type.STRING) { 117 | resourceName = (String) ((ConstantExpressionExecutor) attributeExpressionExecutors[0]).getValue(); 118 | } else { 119 | throw new SiddhiAppValidationException("Resource Identify Stream Processor first parameter " + 120 | "attribute should be string type but found " + 121 | attributeExpressionExecutors[0].getReturnType()); 122 | } 123 | } else { 124 | throw new SiddhiAppValidationException("Resource Identify Stream Processor should have " + 125 | "constant parameter attributes but found a dynamic attribute " + 126 | attributeExpressionExecutors[0].getClass().getCanonicalName()); 127 | } 128 | } else { 129 | throw new SiddhiAppValidationException("Resource Identify Stream Processor should only have one " + 130 | "parameter ( resource.name), but found " + attributeExpressionExecutors.length + 131 | "input attributes"); 132 | } 133 | return new ArrayList(); 134 | } 135 | 136 | @Override 137 | public void start() { 138 | if (resourceName != null) { 139 | List resourceIdentifierStreamProcessorList = 140 | resourceIdentifyStreamProcessorMap.get(resourceName); 141 | if (resourceIdentifierStreamProcessorList != null) { 142 | resourceIdentifierStreamProcessorList.add(this); 143 | } else { 144 | List list = new ArrayList<>(); 145 | list.add(this); 146 | resourceIdentifyStreamProcessorMap.put(resourceName, list); 147 | } 148 | } 149 | } 150 | 151 | @Override 152 | public void stop() { 153 | if (resourceName != null) { 154 | List resourceIdentifierStreamProcessorList = 155 | resourceIdentifyStreamProcessorMap.get(resourceName); 156 | if (resourceIdentifierStreamProcessorList != null) { 157 | resourceIdentifierStreamProcessorList.remove(this); 158 | if (resourceIdentifierStreamProcessorList.size() == 0) { 159 | resourceIdentifyStreamProcessorMap.remove(resourceName); 160 | } 161 | } 162 | } 163 | } 164 | 165 | @Override 166 | public Map currentState() { 167 | return null; 168 | } 169 | 170 | @Override 171 | public void restoreState(Map map) { 172 | 173 | } 174 | 175 | public static int getResourceCount(String resourceName) { 176 | List resourceIdentifierStreamProcessorList = 177 | resourceIdentifyStreamProcessorMap.get(resourceName); 178 | if (resourceIdentifierStreamProcessorList != null) { 179 | return resourceIdentifierStreamProcessorList.size(); 180 | } else { 181 | return 0; 182 | } 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /component/src/test/java/org/wso2/extension/siddhi/execution/env/ResourceIdentifierStreamProcessorTestCase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package org.wso2.extension.siddhi.execution.env; 20 | 21 | import org.apache.log4j.Logger; 22 | import org.awaitility.Awaitility; 23 | import org.awaitility.Duration; 24 | import org.testng.AssertJUnit; 25 | import org.testng.annotations.BeforeMethod; 26 | import org.testng.annotations.Test; 27 | import org.wso2.siddhi.core.SiddhiAppRuntime; 28 | import org.wso2.siddhi.core.SiddhiManager; 29 | import org.wso2.siddhi.core.event.Event; 30 | import org.wso2.siddhi.core.query.output.callback.QueryCallback; 31 | import org.wso2.siddhi.core.stream.input.InputHandler; 32 | import org.wso2.siddhi.core.util.EventPrinter; 33 | 34 | import java.util.concurrent.atomic.AtomicInteger; 35 | 36 | /** 37 | * Test case for ResourceIdentifierStreamProcessor extension. 38 | */ 39 | public class ResourceIdentifierStreamProcessorTestCase { 40 | private static Logger logger = Logger.getLogger(ResourceIdentifierStreamProcessorTestCase.class); 41 | private static AtomicInteger actualEventCount; 42 | 43 | @BeforeMethod 44 | public void beforeTest() { 45 | actualEventCount = new AtomicInteger(0); 46 | } 47 | 48 | @Test 49 | public void testDefaultBehaviour() throws Exception { 50 | logger.info("ResourceIdentifierStreamProcessorDefaultBehaviour TestCase"); 51 | 52 | SiddhiManager siddhiManager = new SiddhiManager(); 53 | 54 | String stream = "define stream inputStream (key string);\n"; 55 | 56 | String query = ("@info(name = 'query1')\n" + 57 | "from inputStream#env:resourceIdentifier(\"Y\")\n" 58 | + "select *\n" 59 | + "insert into outputStream;"); 60 | String query2 = ("@info(name = 'query2')\n" + 61 | "from inputStream#env:resourceIdentifier(\"Y\")\n" 62 | + "select *\n" 63 | + "insert into outputStream;"); 64 | 65 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query + query2); 66 | siddhiAppRuntime.addCallback("query2", new QueryCallback() { 67 | @Override 68 | public void receive(long timeStamp, Event[] inEvents, 69 | Event[] removeEvents) { 70 | EventPrinter.print(timeStamp, inEvents, removeEvents); 71 | AssertJUnit.assertEquals(2, ResourceIdentifierStreamProcessor. 72 | getResourceCount("Y")); 73 | actualEventCount.incrementAndGet(); 74 | } 75 | }); 76 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("inputStream"); 77 | siddhiAppRuntime.start(); 78 | inputHandler.send(new String[]{"stringProperty"}); 79 | waitTillVariableCountMatches(1, Duration.ONE_MINUTE); 80 | siddhiAppRuntime.shutdown(); 81 | } 82 | 83 | @Test(dependsOnMethods = "testDefaultBehaviour") 84 | public void testResourceGenerateWithTwoSiddhiRuntime() throws Exception { 85 | logger.info("ResourceIdentifierStreamProcessorResourceGenerateWithTwoSiddhiRuntime TestCase"); 86 | 87 | SiddhiManager siddhiManager = new SiddhiManager(); 88 | 89 | String stream = "define stream inputStream (key string);\n"; 90 | 91 | String query = ("@info(name = 'query1')\n" + 92 | "from inputStream#env:resourceIdentifier(\"Y\")\n" 93 | + "select *\n" 94 | + "insert into outputStream;"); 95 | String query2 = ("@info(name = 'query2')\n" + 96 | "from inputStream#env:resourceIdentifier(\"Y\")\n" 97 | + "select *\n" 98 | + "insert into outputStream;"); 99 | 100 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 101 | SiddhiAppRuntime siddhiAppRuntime2 = siddhiManager.createSiddhiAppRuntime(stream + query2); 102 | siddhiAppRuntime2.addCallback("query2", new QueryCallback() { 103 | @Override 104 | public void receive(long timeStamp, Event[] inEvents, 105 | Event[] removeEvents) { 106 | EventPrinter.print(timeStamp, inEvents, removeEvents); 107 | AssertJUnit.assertEquals(2, ResourceIdentifierStreamProcessor. 108 | getResourceCount("Y")); 109 | actualEventCount.incrementAndGet(); 110 | } 111 | }); 112 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("inputStream"); 113 | InputHandler inputHandler2 = siddhiAppRuntime2.getInputHandler("inputStream"); 114 | siddhiAppRuntime.start(); 115 | siddhiAppRuntime2.start(); 116 | inputHandler.send(new String[]{"stringProperty"}); 117 | inputHandler2.send(new String[]{"stringProperty"}); 118 | waitTillVariableCountMatches(1, Duration.ONE_MINUTE); 119 | siddhiAppRuntime.shutdown(); 120 | siddhiAppRuntime2.shutdown(); 121 | } 122 | 123 | 124 | @Test(dependsOnMethods = "testResourceGenerateWithTwoSiddhiRuntime") 125 | public void testRemoveResource() throws Exception { 126 | logger.info("ResourceIdentifierStreamProcessorRemoveResource TestCase"); 127 | 128 | SiddhiManager siddhiManager = new SiddhiManager(); 129 | 130 | String stream = "define stream inputStream (key string);\n"; 131 | 132 | String query = ("@info(name = 'query1')\n" + 133 | "from inputStream#env:resourceIdentifier(\"Y\")\n" 134 | + "select *\n" 135 | + "insert into outputStream;"); 136 | String query2 = ("@info(name = 'query2')\n" + 137 | "from inputStream#env:resourceIdentifier(\"Y\")\n" 138 | + "select *\n" 139 | + "insert into outputStream;"); 140 | 141 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 142 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 143 | @Override 144 | public void receive(long timeStamp, Event[] inEvents, 145 | Event[] removeEvents) { 146 | EventPrinter.print(timeStamp, inEvents, removeEvents); 147 | AssertJUnit.assertEquals(1, ResourceIdentifierStreamProcessor. 148 | getResourceCount("Y")); 149 | actualEventCount.incrementAndGet(); 150 | } 151 | }); 152 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("inputStream"); 153 | siddhiAppRuntime.start(); 154 | inputHandler.send(new String[]{"stringProperty1"}); 155 | waitTillVariableCountMatches(1, Duration.ONE_MINUTE); 156 | siddhiAppRuntime.shutdown(); 157 | Thread.sleep(1000); 158 | SiddhiAppRuntime siddhiAppRuntime2 = siddhiManager.createSiddhiAppRuntime(stream + query2); 159 | siddhiAppRuntime2.start(); 160 | InputHandler inputHandler2 = siddhiAppRuntime2.getInputHandler("inputStream"); 161 | siddhiAppRuntime2.addCallback("query2", new QueryCallback() { 162 | @Override 163 | public void receive(long timeStamp, Event[] inEvents, 164 | Event[] removeEvents) { 165 | EventPrinter.print(timeStamp, inEvents, removeEvents); 166 | AssertJUnit.assertEquals(1, ResourceIdentifierStreamProcessor. 167 | getResourceCount("Y")); 168 | actualEventCount.incrementAndGet(); 169 | } 170 | }); 171 | inputHandler2.send(new String[]{"stringProperty2"}); 172 | waitTillVariableCountMatches(2, Duration.ONE_MINUTE); 173 | siddhiAppRuntime2.shutdown(); 174 | } 175 | 176 | @Test(dependsOnMethods = "testRemoveResource") 177 | public void testTwoResources() throws Exception { 178 | logger.info("ResourceIdentifierStreamProcessorTwoResources TestCase"); 179 | 180 | SiddhiManager siddhiManager = new SiddhiManager(); 181 | 182 | String stream = "define stream inputStream (key string);\n"; 183 | 184 | String query = ("@info(name = 'query1')\n" + 185 | "from inputStream#env:resourceIdentifier(\"Y\")\n" 186 | + "select *\n" 187 | + "insert into outputStream;"); 188 | String query2 = ("@info(name = 'query2')\n" + 189 | "from inputStream#env:resourceIdentifier(\"Z\")\n" 190 | + "select *\n" 191 | + "insert into outputStream;"); 192 | 193 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 194 | SiddhiAppRuntime siddhiAppRuntime2 = siddhiManager.createSiddhiAppRuntime(stream + query2); 195 | siddhiAppRuntime2.addCallback("query2", new QueryCallback() { 196 | @Override 197 | public void receive(long timeStamp, Event[] inEvents, 198 | Event[] removeEvents) { 199 | EventPrinter.print(timeStamp, inEvents, removeEvents); 200 | AssertJUnit.assertEquals(1, ResourceIdentifierStreamProcessor. 201 | getResourceCount("Y")); 202 | AssertJUnit.assertEquals(1, ResourceIdentifierStreamProcessor. 203 | getResourceCount("Z")); 204 | actualEventCount.incrementAndGet(); 205 | } 206 | }); 207 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("inputStream"); 208 | InputHandler inputHandler2 = siddhiAppRuntime2.getInputHandler("inputStream"); 209 | siddhiAppRuntime.start(); 210 | siddhiAppRuntime2.start(); 211 | inputHandler.send(new String[]{"stringProperty"}); 212 | inputHandler2.send(new String[]{"stringProperty"}); 213 | waitTillVariableCountMatches(1, Duration.ONE_MINUTE); 214 | siddhiAppRuntime.shutdown(); 215 | siddhiAppRuntime2.shutdown(); 216 | } 217 | 218 | private static void waitTillVariableCountMatches(long expected, Duration duration) { 219 | Awaitility.await().atMost(duration).until(() -> actualEventCount.get() == expected); 220 | } 221 | } 222 | -------------------------------------------------------------------------------- /docs/api/1.0.3.md: -------------------------------------------------------------------------------- 1 | # API Docs - v1.0.3 2 | 3 | ## Env 4 | 5 | ### getEnvironmentProperty *(Function)* 6 | 7 |

This function returns Java environment property corresponding to the key provided

8 | 9 | Syntax 10 | ``` 11 | env:getEnvironmentProperty( key, default.value) 12 | ``` 13 | 14 | QUERY PARAMETERS 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
keyThis specifies Key of the property to be read.STRINGNoNo
default.valueThis specifies the default Value to be returned if the property value is not available.nullSTRINGYesNo
41 | 42 | Examples 43 | EXAMPLE 1 44 | ``` 45 | define stream keyStream (key string); 46 | from keyStream env:getEnvironmentProperty(key) as FunctionOutput 47 | insert into outputStream; 48 | ``` 49 |

This query returns Java environment property corresponding to the key from keyStream as FunctionOutput to the outputStream

50 | 51 | ### getSystemProperty *(Function)* 52 | 53 |

This function returns the system property pointed by the system property key

54 | 55 | Syntax 56 | ``` 57 | env:getSystemProperty( key, default.value) 58 | ``` 59 | 60 | QUERY PARAMETERS 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
keyThis specifies Key of the property to be read.STRINGNoNo
default.valueThis specifies the default Value to be returned if the property value is not available.nullSTRINGYesNo
87 | 88 | Examples 89 | EXAMPLE 1 90 | ``` 91 | define stream keyStream (key string); 92 | from keyStream env:getSystemProperty(key) as FunctionOutput 93 | insert into outputStream; 94 | ``` 95 |

This query returns system property corresponding to the key from keyStream as FunctionOutput to the outputStream

96 | 97 | ### getUserAgentProperty *(Function)* 98 | 99 |

This function returns the value corresponding to a given property name in a given user agent

100 | 101 | Syntax 102 | ``` 103 | env:getUserAgentProperty( user.agent, property.name) 104 | ``` 105 | 106 | QUERY PARAMETERS 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
user.agentThis specifies the user agent from which property will be extracted.STRINGNoNo
property.nameThis specifies property name which should be extracted. Supported property names are 'browser', 'os' and 'device'.STRINGNoNo
133 | 134 | System Parameters 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 |
NameDescriptionDefault ValuePossible Parameters
regexFilePathLocation of the yaml file which contains the regex to process the user agent. Default regexes included in the ua_parser libraryN/A
149 | 150 | Examples 151 | EXAMPLE 1 152 | ``` 153 | define stream UserAgentStream (userAgent string); 154 | from UserAgentStream 155 | select env:getUserAgentProperty(userAgent, "browser") as functionOutput 156 | insert into OutputStream; 157 | ``` 158 |

This query returns browser name of the userAgent from UserAgentStream as functionOutput to the OutputStream

159 | 160 | ### getYAMLProperty *(Function)* 161 | 162 |

This function returns the YAML property requested or the default values specified if such avariable is not available in the deployment.yaml

163 | 164 | Syntax 165 | ``` 166 | env:getYAMLProperty( key, data.type, default.value) 167 | ``` 168 | 169 | QUERY PARAMETERS 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
keyThis specifies Key of the property to be read.STRINGNoNo
data.typeA string constant parameter expressing the data type of the propertyusing one of the following string values: int, long, float, double, string, bool.stringSTRINGNoNo
default.valueThis specifies the default Value to be returned if the property value is not available.nullINT
LONG
DOUBLE
FLOAT
STRING
BOOL
YesNo
204 | 205 | Examples 206 | EXAMPLE 1 207 | ``` 208 | define stream keyStream (key string); 209 | from keyStream env:getYAMLProperty(key) as FunctionOutput 210 | insert into outputStream; 211 | ``` 212 |

This query returns corresponding YAML property for the corresponding key from keyStream as FunctionOutput to the outputStream

213 | 214 | -------------------------------------------------------------------------------- /docs/license.md: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 WSO2 Inc. () All Rights Reserved. 2 | 3 | WSO2 Inc. licenses this file to you under the Apache License, 4 | Version 2.0 (the "License"); you may not use this file except 5 | in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | 9 | 10 | Unless required by applicable law or agreed to in writing, 11 | software distributed under the License is distributed on an 12 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | KIND, either express or implied. See the License for the 14 | specific language governing permissions and limitations 15 | under the License. 16 | 17 | ``` 18 | ------------------------------------------------------------------------- 19 | Apache License 20 | Version 2.0, January 2004 21 | http://www.apache.org/licenses/ 22 | 23 | 24 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 25 | 26 | 1. Definitions. 27 | 28 | "License" shall mean the terms and conditions for use, reproduction, 29 | and distribution as defined by Sections 1 through 9 of this document. 30 | 31 | "Licensor" shall mean the copyright owner or entity authorized by 32 | the copyright owner that is granting the License. 33 | 34 | "Legal Entity" shall mean the union of the acting entity and all 35 | other entities that control, are controlled by, or are under common 36 | control with that entity. For the purposes of this definition, 37 | "control" means (i) the power, direct or indirect, to cause the 38 | direction or management of such entity, whether by contract or 39 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 40 | outstanding shares, or (iii) beneficial ownership of such entity. 41 | 42 | "You" (or "Your") shall mean an individual or Legal Entity 43 | exercising permissions granted by this License. 44 | 45 | "Source" form shall mean the preferred form for making modifications, 46 | including but not limited to software source code, documentation 47 | source, and configuration files. 48 | 49 | "Object" form shall mean any form resulting from mechanical 50 | transformation or translation of a Source form, including but 51 | not limited to compiled object code, generated documentation, 52 | and conversions to other media types. 53 | 54 | "Work" shall mean the work of authorship, whether in Source or 55 | Object form, made available under the License, as indicated by a 56 | copyright notice that is included in or attached to the work 57 | (an example is provided in the Appendix below). 58 | 59 | "Derivative Works" shall mean any work, whether in Source or Object 60 | form, that is based on (or derived from) the Work and for which the 61 | editorial revisions, annotations, elaborations, or other modifications 62 | represent, as a whole, an original work of authorship. For the purposes 63 | of this License, Derivative Works shall not include works that remain 64 | separable from, or merely link (or bind by name) to the interfaces of, 65 | the Work and Derivative Works thereof. 66 | 67 | "Contribution" shall mean any work of authorship, including 68 | the original version of the Work and any modifications or additions 69 | to that Work or Derivative Works thereof, that is intentionally 70 | submitted to Licensor for inclusion in the Work by the copyright owner 71 | or by an individual or Legal Entity authorized to submit on behalf of 72 | the copyright owner. For the purposes of this definition, "submitted" 73 | means any form of electronic, verbal, or written communication sent 74 | to the Licensor or its representatives, including but not limited to 75 | communication on electronic mailing lists, source code control systems, 76 | and issue tracking systems that are managed by, or on behalf of, the 77 | Licensor for the purpose of discussing and improving the Work, but 78 | excluding communication that is conspicuously marked or otherwise 79 | designated in writing by the copyright owner as "Not a Contribution." 80 | 81 | "Contributor" shall mean Licensor and any individual or Legal Entity 82 | on behalf of whom a Contribution has been received by Licensor and 83 | subsequently incorporated within the Work. 84 | 85 | 2. Grant of Copyright License. Subject to the terms and conditions of 86 | this License, each Contributor hereby grants to You a perpetual, 87 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 88 | copyright license to reproduce, prepare Derivative Works of, 89 | publicly display, publicly perform, sublicense, and distribute the 90 | Work and such Derivative Works in Source or Object form. 91 | 92 | 3. Grant of Patent License. Subject to the terms and conditions of 93 | this License, each Contributor hereby grants to You a perpetual, 94 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 95 | (except as stated in this section) patent license to make, have made, 96 | use, offer to sell, sell, import, and otherwise transfer the Work, 97 | where such license applies only to those patent claims licensable 98 | by such Contributor that are necessarily infringed by their 99 | Contribution(s) alone or by combination of their Contribution(s) 100 | with the Work to which such Contribution(s) was submitted. If You 101 | institute patent litigation against any entity (including a 102 | cross-claim or counterclaim in a lawsuit) alleging that the Work 103 | or a Contribution incorporated within the Work constitutes direct 104 | or contributory patent infringement, then any patent licenses 105 | granted to You under this License for that Work shall terminate 106 | as of the date such litigation is filed. 107 | 108 | 4. Redistribution. You may reproduce and distribute copies of the 109 | Work or Derivative Works thereof in any medium, with or without 110 | modifications, and in Source or Object form, provided that You 111 | meet the following conditions: 112 | 113 | (a) You must give any other recipients of the Work or 114 | Derivative Works a copy of this License; and 115 | 116 | (b) You must cause any modified files to carry prominent notices 117 | stating that You changed the files; and 118 | 119 | (c) You must retain, in the Source form of any Derivative Works 120 | that You distribute, all copyright, patent, trademark, and 121 | attribution notices from the Source form of the Work, 122 | excluding those notices that do not pertain to any part of 123 | the Derivative Works; and 124 | 125 | (d) If the Work includes a "NOTICE" text file as part of its 126 | distribution, then any Derivative Works that You distribute must 127 | include a readable copy of the attribution notices contained 128 | within such NOTICE file, excluding those notices that do not 129 | pertain to any part of the Derivative Works, in at least one 130 | of the following places: within a NOTICE text file distributed 131 | as part of the Derivative Works; within the Source form or 132 | documentation, if provided along with the Derivative Works; or, 133 | within a display generated by the Derivative Works, if and 134 | wherever such third-party notices normally appear. The contents 135 | of the NOTICE file are for informational purposes only and 136 | do not modify the License. You may add Your own attribution 137 | notices within Derivative Works that You distribute, alongside 138 | or as an addendum to the NOTICE text from the Work, provided 139 | that such additional attribution notices cannot be construed 140 | as modifying the License. 141 | 142 | You may add Your own copyright statement to Your modifications and 143 | may provide additional or different license terms and conditions 144 | for use, reproduction, or distribution of Your modifications, or 145 | for any such Derivative Works as a whole, provided Your use, 146 | reproduction, and distribution of the Work otherwise complies with 147 | the conditions stated in this License. 148 | 149 | 5. Submission of Contributions. Unless You explicitly state otherwise, 150 | any Contribution intentionally submitted for inclusion in the Work 151 | by You to the Licensor shall be under the terms and conditions of 152 | this License, without any additional terms or conditions. 153 | Notwithstanding the above, nothing herein shall supersede or modify 154 | the terms of any separate license agreement you may have executed 155 | with Licensor regarding such Contributions. 156 | 157 | 6. Trademarks. This License does not grant permission to use the trade 158 | names, trademarks, service marks, or product names of the Licensor, 159 | except as required for reasonable and customary use in describing the 160 | origin of the Work and reproducing the content of the NOTICE file. 161 | 162 | 7. Disclaimer of Warranty. Unless required by applicable law or 163 | agreed to in writing, Licensor provides the Work (and each 164 | Contributor provides its Contributions) on an "AS IS" BASIS, 165 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 166 | implied, including, without limitation, any warranties or conditions 167 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 168 | PARTICULAR PURPOSE. You are solely responsible for determining the 169 | appropriateness of using or redistributing the Work and assume any 170 | risks associated with Your exercise of permissions under this License. 171 | 172 | 8. Limitation of Liability. In no event and under no legal theory, 173 | whether in tort (including negligence), contract, or otherwise, 174 | unless required by applicable law (such as deliberate and grossly 175 | negligent acts) or agreed to in writing, shall any Contributor be 176 | liable to You for damages, including any direct, indirect, special, 177 | incidental, or consequential damages of any character arising as a 178 | result of this License or out of the use or inability to use the 179 | Work (including but not limited to damages for loss of goodwill, 180 | work stoppage, computer failure or malfunction, or any and all 181 | other commercial damages or losses), even if such Contributor 182 | has been advised of the possibility of such damages. 183 | 184 | 9. Accepting Warranty or Additional Liability. While redistributing 185 | the Work or Derivative Works thereof, You may choose to offer, 186 | and charge a fee for, acceptance of support, warranty, indemnity, 187 | or other liability obligations and/or rights consistent with this 188 | License. However, in accepting such obligations, You may act only 189 | on Your own behalf and on Your sole responsibility, not on behalf 190 | of any other Contributor, and only if You agree to indemnify, 191 | defend, and hold each Contributor harmless for any liability 192 | incurred by, or claims asserted against, such Contributor by reason 193 | of your accepting any such warranty or additional liability. 194 | 195 | END OF TERMS AND CONDITIONS 196 | ``` 197 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /component/src/main/java/org/wso2/extension/siddhi/execution/env/GetYAMLPropertyFunction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package org.wso2.extension.siddhi.execution.env; 20 | 21 | import org.wso2.siddhi.annotation.Example; 22 | import org.wso2.siddhi.annotation.Extension; 23 | import org.wso2.siddhi.annotation.Parameter; 24 | import org.wso2.siddhi.annotation.ReturnAttribute; 25 | import org.wso2.siddhi.annotation.util.DataType; 26 | import org.wso2.siddhi.core.config.SiddhiAppContext; 27 | import org.wso2.siddhi.core.exception.SiddhiAppRuntimeException; 28 | import org.wso2.siddhi.core.executor.ConstantExpressionExecutor; 29 | import org.wso2.siddhi.core.executor.ExpressionExecutor; 30 | import org.wso2.siddhi.core.executor.function.FunctionExecutor; 31 | import org.wso2.siddhi.core.util.config.ConfigReader; 32 | import org.wso2.siddhi.query.api.definition.Attribute; 33 | import org.wso2.siddhi.query.api.exception.SiddhiAppValidationException; 34 | 35 | import java.util.Map; 36 | 37 | /** 38 | * Siddhi Function getYAMLProperty to read property values from deployment.yaml. 39 | */ 40 | 41 | @Extension( 42 | name = "getYAMLProperty", 43 | namespace = "env", 44 | description = "This function returns the YAML property requested or the default values specified if such a" + 45 | "variable is not specified in the 'deployment.yaml'.", 46 | parameters = { 47 | @Parameter(name = "key", 48 | description = "This specifies key of the property to be read.", 49 | type = {DataType.STRING}, 50 | optional = false), 51 | @Parameter(name = "data.type", 52 | description = "A string constant parameter expressing the data type of the property" + 53 | "using one of the following string values:\n int, long, float, double, string, bool.", 54 | type = {DataType.STRING}, 55 | optional = false, 56 | defaultValue = "string"), 57 | @Parameter(name = "default.value", 58 | description = "This specifies the default value to be returned " + 59 | "if the property value is not available.", 60 | type = {DataType.INT, DataType.LONG, DataType.DOUBLE, DataType.FLOAT, 61 | DataType.STRING, DataType.BOOL}, 62 | optional = true, 63 | defaultValue = "null") 64 | }, 65 | returnAttributes = @ReturnAttribute( 66 | description = "The default return type is 'string', but it can also be any of the following:\n " + 67 | "'int', 'long', 'float', 'double', 'string',' bool'.", 68 | type = {org.wso2.siddhi.annotation.util.DataType.INT, org.wso2.siddhi.annotation.util.DataType.LONG, 69 | org.wso2.siddhi.annotation.util.DataType.DOUBLE, org.wso2.siddhi.annotation.util.DataType.FLOAT, 70 | org.wso2.siddhi.annotation.util.DataType.STRING, org.wso2.siddhi.annotation.util.DataType.BOOL 71 | }), 72 | examples = { 73 | @Example( 74 | syntax = "define stream KeyStream (key string);\n" + 75 | "from KeyStream env:getYAMLProperty(key) as FunctionOutput \n" + 76 | "insert into outputStream;", 77 | description = "This query returns the corresponding YAML property for the corresponding key " + 78 | "from the 'KeyStream' stream as 'FunctionOutput', and inserts it into the to the" + 79 | " 'OutputStream' stream." 80 | ) 81 | } 82 | ) 83 | 84 | public class GetYAMLPropertyFunction extends FunctionExecutor { 85 | 86 | private ConfigReader configReader; 87 | private Attribute.Type returnType = Attribute.Type.STRING; 88 | private boolean hasDefaultValue = false; 89 | 90 | /** 91 | * The initialization method for TheFun, this method will be called before the other methods. 92 | * 93 | * @param attributeExpressionExecutors the executors of each function parameter. 94 | * @param siddhiAppContext the context of the execution plan. 95 | */ 96 | protected void init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader reader, 97 | SiddhiAppContext siddhiAppContext) { 98 | int attributeExpressionExecutorsLength = attributeExpressionExecutors.length; 99 | if ((attributeExpressionExecutorsLength > 0) && (attributeExpressionExecutorsLength < 4)) { 100 | Attribute.Type typeofKeyAttribute = attributeExpressionExecutors[0].getReturnType(); 101 | checkKeyAttribute(typeofKeyAttribute); 102 | if (attributeExpressionExecutorsLength > 1) { 103 | if (!(attributeExpressionExecutors[1] instanceof ConstantExpressionExecutor)) { 104 | throw new SiddhiAppValidationException("The second argument has to be a string constant " + 105 | "specifying one of the supported data types (int, long, float, double, string, bool)"); 106 | } else { 107 | String type = attributeExpressionExecutors[1].execute(null).toString(); 108 | returnType = getReturnType(type); 109 | } 110 | } 111 | if (attributeExpressionExecutors.length > 2) { 112 | Attribute.Type typeofDefaultValueAttribute = attributeExpressionExecutors[2].getReturnType(); 113 | if (typeofDefaultValueAttribute != returnType) { 114 | throw new SiddhiAppValidationException("Type of parameter default.Value " + 115 | "needs to match parameter data.type"); 116 | } 117 | } 118 | } else { 119 | throw new SiddhiAppValidationException("Invalid no of arguments passed to " + 120 | "env:getYAMLProperty(Key, data.type, default.value) function, " + 121 | "required 1,2 or 3, but found " + attributeExpressionExecutorsLength); 122 | } 123 | 124 | this.configReader = reader; 125 | hasDefaultValue = (attributeExpressionExecutorsLength > 2); 126 | } 127 | 128 | private Attribute.Type getReturnType(String type) { 129 | Attribute.Type theReturnType; 130 | if ("int".equalsIgnoreCase(type)) { 131 | theReturnType = Attribute.Type.INT; 132 | } else if ("long".equalsIgnoreCase(type)) { 133 | theReturnType = Attribute.Type.LONG; 134 | } else if ("float".equalsIgnoreCase(type)) { 135 | theReturnType = Attribute.Type.FLOAT; 136 | } else if ("double".equalsIgnoreCase(type)) { 137 | theReturnType = Attribute.Type.DOUBLE; 138 | } else if ("bool".equalsIgnoreCase(type)) { 139 | theReturnType = Attribute.Type.BOOL; 140 | } else if ("string".equalsIgnoreCase(type)) { 141 | theReturnType = Attribute.Type.STRING; 142 | } else { 143 | throw new SiddhiAppValidationException("Type must be one of int, long, float, double, bool, " + 144 | "string"); 145 | } 146 | return theReturnType; 147 | } 148 | 149 | private void checkKeyAttribute(Attribute.Type typeofKeyAttribute) { 150 | if (typeofKeyAttribute != Attribute.Type.STRING) { 151 | throw new SiddhiAppValidationException("Invalid parameter type found " + 152 | "for the argument Key of getYAMLProperty() function, " + 153 | "required " + Attribute.Type.STRING + 154 | ", but found " + typeofKeyAttribute.toString()); 155 | } 156 | } 157 | 158 | /** 159 | * The main execution method which will be called upon event arrival 160 | * when there are more than one function parameter. 161 | * 162 | * @param data the runtime values of function parameters. 163 | * @return the function result. 164 | */ 165 | 166 | @Override 167 | protected Object execute(Object[] data) { 168 | String key = (String) data[0]; 169 | String value = configReader.readConfig(key, null); 170 | if (value != null) { 171 | try { 172 | switch (returnType) { 173 | case INT: 174 | return Integer.parseInt(value); 175 | case LONG: 176 | return Long.parseLong(value); 177 | case FLOAT: 178 | return Float.parseFloat(value); 179 | case DOUBLE: 180 | return Double.parseDouble(value); 181 | case BOOL: 182 | return Boolean.parseBoolean(value); 183 | default: // case STRING: 184 | break; 185 | } 186 | return value; 187 | } catch (NumberFormatException e) { 188 | throw new SiddhiAppRuntimeException 189 | ("The type of property value and parameter dataType does not match"); 190 | } 191 | } else { 192 | return ((hasDefaultValue) ? data[2] : null); 193 | } 194 | } 195 | 196 | /** 197 | * The main execution method which will be called upon event arrival 198 | * when there are zero or one function parameter. 199 | * 200 | * @param data null if the function parameter count is zero or 201 | * runtime data value of the function parameter. 202 | * @return the function result. 203 | */ 204 | @Override 205 | protected Object execute(Object data) { 206 | if (data != null) { 207 | if (data instanceof String) { 208 | String key = (String) data; 209 | return configReader.readConfig(key, null); 210 | } 211 | } else { 212 | throw new SiddhiAppRuntimeException("Input to the getYAMLProperty function cannot be null"); 213 | } 214 | return null; 215 | } 216 | 217 | /** 218 | * This will be called only once and this can be used to acquire 219 | * required resources for the processing element. 220 | * This will be called after initializing the system and before 221 | * starting to process the events. 222 | */ 223 | 224 | @Override 225 | public Attribute.Type getReturnType() { 226 | return returnType; 227 | } 228 | 229 | /** 230 | * Used to collect the serializable state of the processing element, that need to be 231 | * persisted for the reconstructing the element to the same state on a different point of time. 232 | * 233 | * @return stateful objects of the processing element as an array. 234 | */ 235 | @Override 236 | public Map currentState() { 237 | return null; 238 | } 239 | 240 | /** 241 | * Used to restore serialized state of the processing element, for reconstructing 242 | * the element to the same state as if was on a previous point of time. 243 | * 244 | * @param state the stateful objects of the element as an array on 245 | * the same order provided by currentState(). 246 | */ 247 | @Override 248 | public void restoreState(Map state) { 249 | //Implement restore state logic. 250 | } 251 | 252 | } 253 | -------------------------------------------------------------------------------- /docs/api/1.0.4.md: -------------------------------------------------------------------------------- 1 | # API Docs - v1.0.4 2 | 3 | ## Env 4 | 5 | ### getEnvironmentProperty *(Function)* 6 | 7 |

This function returns Java environment property corresponding to the key provided

8 | 9 | Syntax 10 | ``` 11 | env:getEnvironmentProperty( key, default.value) 12 | ``` 13 | 14 | QUERY PARAMETERS 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
keyThis specifies Key of the property to be read.STRINGNoNo
default.valueThis specifies the default Value to be returned if the property value is not available.nullSTRINGYesNo
41 | 42 | Examples 43 | EXAMPLE 1 44 | ``` 45 | define stream keyStream (key string); 46 | from keyStream env:getEnvironmentProperty(key) as FunctionOutput 47 | insert into outputStream; 48 | ``` 49 |

This query returns Java environment property corresponding to the key from keyStream as FunctionOutput to the outputStream

50 | 51 | ### getOriginIPFromXForwarded *(Function)* 52 | 53 |

This function returns the public origin IP from the given X-Forwarded header

54 | 55 | Syntax 56 | ``` 57 | env:getOriginIPFromXForwarded( xforwardedheader) 58 | ``` 59 | 60 | QUERY PARAMETERS 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
xforwardedheaderX-Forwarded-For header of the requestSTRINGNoNo
79 | 80 | Examples 81 | EXAMPLE 1 82 | ``` 83 | define stream InputStream (xForwardedHeader string); 84 | from InputStream select env:getOriginIPFromXForwarded(xForwardedHeader) as originIP 85 | insert into OutputStream; 86 | ``` 87 |

This query returns the public origin IP from the given X-Forwarded header

88 | 89 | ### getSystemProperty *(Function)* 90 | 91 |

This function returns the system property pointed by the system property key

92 | 93 | Syntax 94 | ``` 95 | env:getSystemProperty( key, default.value) 96 | ``` 97 | 98 | QUERY PARAMETERS 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
keyThis specifies Key of the property to be read.STRINGNoNo
default.valueThis specifies the default Value to be returned if the property value is not available.nullSTRINGYesNo
125 | 126 | Examples 127 | EXAMPLE 1 128 | ``` 129 | define stream keyStream (key string); 130 | from keyStream env:getSystemProperty(key) as FunctionOutput 131 | insert into outputStream; 132 | ``` 133 |

This query returns system property corresponding to the key from keyStream as FunctionOutput to the outputStream

134 | 135 | ### getUserAgentProperty *(Function)* 136 | 137 |

This function returns the value corresponding to a given property name in a given user agent

138 | 139 | Syntax 140 | ``` 141 | env:getUserAgentProperty( user.agent, property.name) 142 | ``` 143 | 144 | QUERY PARAMETERS 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
user.agentThis specifies the user agent from which property will be extracted.STRINGNoNo
property.nameThis specifies property name which should be extracted. Supported property names are 'browser', 'os' and 'device'.STRINGNoNo
171 | 172 | System Parameters 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 |
NameDescriptionDefault ValuePossible Parameters
regexFilePathLocation of the yaml file which contains the regex to process the user agent. Default regexes included in the ua_parser libraryN/A
187 | 188 | Examples 189 | EXAMPLE 1 190 | ``` 191 | define stream UserAgentStream (userAgent string); 192 | from UserAgentStream 193 | select env:getUserAgentProperty(userAgent, "browser") as functionOutput 194 | insert into OutputStream; 195 | ``` 196 |

This query returns browser name of the userAgent from UserAgentStream as functionOutput to the OutputStream

197 | 198 | ### getYAMLProperty *(Function)* 199 | 200 |

This function returns the YAML property requested or the default values specified if such avariable is not available in the deployment.yaml

201 | 202 | Syntax 203 | ``` 204 | env:getYAMLProperty( key, data.type, default.value) 205 | ``` 206 | 207 | QUERY PARAMETERS 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 |
NameDescriptionDefault ValuePossible Data TypesOptionalDynamic
keyThis specifies Key of the property to be read.STRINGNoNo
data.typeA string constant parameter expressing the data type of the propertyusing one of the following string values: int, long, float, double, string, bool.stringSTRINGNoNo
default.valueThis specifies the default Value to be returned if the property value is not available.nullINT
LONG
DOUBLE
FLOAT
STRING
BOOL
YesNo
242 | 243 | Examples 244 | EXAMPLE 1 245 | ``` 246 | define stream keyStream (key string); 247 | from keyStream env:getYAMLProperty(key) as FunctionOutput 248 | insert into outputStream; 249 | ``` 250 |

This query returns corresponding YAML property for the corresponding key from keyStream as FunctionOutput to the outputStream

251 | 252 | --------------------------------------------------------------------------------