├── 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 └── license.md ├── .gitignore ├── component ├── src │ ├── test │ │ ├── resources │ │ │ ├── log4j.properties │ │ │ └── testng.xml │ │ └── java │ │ │ └── org │ │ │ └── wso2 │ │ │ └── extension │ │ │ └── siddhi │ │ │ └── execution │ │ │ └── json │ │ │ ├── ToJSONFunctionTestCase.java │ │ │ ├── ToStringFunctionTestCase.java │ │ │ ├── GetIntJSONFunctionTestCase.java │ │ │ ├── GetObjectJSONFunctionTestCase.java │ │ │ ├── GetBoolJSONFunctionTestCase.java │ │ │ ├── GetLongJSONFunctionTestCase.java │ │ │ ├── GetFloatJSONFunctionTestCase.java │ │ │ ├── GetDoubleJSONFunctionTestCase.java │ │ │ ├── GetStringJSONFunctionTestCase.java │ │ │ └── JsonTokenizerStreamProcessorFunctionTestCase.java │ └── main │ │ ├── resources │ │ └── log4j.properties │ │ └── java │ │ └── org │ │ └── wso2 │ │ └── extension │ │ └── siddhi │ │ └── execution │ │ └── json │ │ └── function │ │ ├── ToJSONStringFunctionExtension.java │ │ ├── ToJSONObjectFunctionExtension.java │ │ ├── GetObjectJSONFunctionExtension.java │ │ ├── GetStringJSONFunctionExtension.java │ │ ├── IsExistsFunctionExtension.java │ │ ├── GetLongJSONFunctionExtension.java │ │ ├── GetIntJSONFunctionExtension.java │ │ ├── GetFloatJSONFunctionExtension.java │ │ ├── GetDoubleJSONFunctionExtension.java │ │ └── GetBoolJSONFunctionExtension.java └── pom.xml ├── issue_template.md ├── mkdocs.yml ├── pull_request_template.md ├── pom.xml └── README.md /docs/images/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/this/siddhi-execution-json/master/docs/images/favicon.ico -------------------------------------------------------------------------------- /docs/images/siddhi-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/this/siddhi-execution-json/master/docs/images/siddhi-logo.png -------------------------------------------------------------------------------- /docs/images/siddhi-logo-w.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/this/siddhi-execution-json/master/docs/images/siddhi-logo-w.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything in this directory 2 | target 3 | .classpath 4 | .settings 5 | .project 6 | *.class 7 | 8 | # Ignore Package Files 9 | *.war 10 | *.ear 11 | 12 | # Ignore Intellij-IDEA files 13 | *.iml 14 | *.ipr 15 | *.iws 16 | *.classpath 17 | *.settings 18 | *.project 19 | *.idea 20 | .DS_Store 21 | 22 | # Ignore logs 23 | *.log 24 | 25 | # Ignore target directories 26 | target/ 27 | *.*~ 28 | -------------------------------------------------------------------------------- /component/src/test/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # For the general syntax of property based configuration files see the 2 | # documenation of org.apache.log4j.PropertyConfigurator. 3 | # The root category uses the appender called A1. Since no priority is 4 | # specified, the root category assumes the default priority for root 5 | # which is DEBUG in log4j. The root category is the only category that 6 | # has a default priority. All other categories need not be assigned a 7 | # priority in which case they inherit their priority from the 8 | # hierarchy. 9 | #log4j.rootLogger=DEBUG, stdout 10 | log4j.rootLogger=INFO, stdout 11 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 12 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 13 | log4j.appender.stdout.layout.ConversionPattern=%m%n 14 | #log4j.appender.stdout.layout.ConversionPattern=[%t] %-5p %c %x - %m%n 15 | -------------------------------------------------------------------------------- /component/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # For the general syntax of property based configuration files see the 2 | # documenation of org.apache.log4j.PropertyConfigurator. 3 | 4 | # The root category uses the appender called A1. Since no priority is 5 | # specified, the root category assumes the default priority for root 6 | # which is DEBUG in log4j. The root category is the only category that 7 | # has a default priority. All other categories need not be assigned a 8 | # priority in which case they inherit their priority from the 9 | # hierarchy. 10 | 11 | #log4j.rootLogger=DEBUG, stdout 12 | log4j.rootLogger=INFO, stdout 13 | 14 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 15 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 16 | log4j.appender.stdout.layout.ConversionPattern=%m%n 17 | #log4j.appender.stdout.layout.ConversionPattern=[%t] %-5p %c %x - %m%n 18 | -------------------------------------------------------------------------------- /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 | var headerContent = document.querySelectorAll('.md-header-nav__topic')[1].textContent.trim(); 21 | 22 | header.innerHTML = '' + extentionTitle + '' + headerContent; 23 | 24 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: Siddhi Execution JSON 2 | site_description: Siddhi Execution JSON Extension 3 | site_author: WSO2 4 | site_url: https://wso2-extensions.github.io/siddhi-execution-json/ 5 | extra_css: 6 | - stylesheets/extra.css 7 | extra_javascript: 8 | - javascripts/extra.js 9 | repo_name: Siddhi-Execution-JSON 10 | repo_url: https://github.com/wso2-extensions/siddhi-execution-json 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.11: api/1.0.11.md 36 | - 1.0.10: api/1.0.10.md 37 | - 1.0.9: api/1.0.9.md 38 | - 1.0.8: api/1.0.8.md 39 | - 1.0.7: api/1.0.7.md 40 | - 1.0.6: api/1.0.6.md 41 | - 1.0.5: api/1.0.5.md 42 | - 1.0.4: api/1.0.4.md 43 | - 1.0.3: api/1.0.3.md 44 | - latest: api/latest.md 45 | - License: license.md 46 | -------------------------------------------------------------------------------- /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 | } 54 | -------------------------------------------------------------------------------- /component/src/test/resources/testng.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /component/src/test/java/org/wso2/extension/siddhi/execution/json/ToJSONFunctionTestCase.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.json; 20 | 21 | import net.minidev.json.JSONObject; 22 | import net.minidev.json.parser.JSONParser; 23 | import net.minidev.json.parser.ParseException; 24 | import org.apache.log4j.Logger; 25 | import org.testng.AssertJUnit; 26 | import org.testng.annotations.BeforeMethod; 27 | import org.testng.annotations.Test; 28 | import org.wso2.siddhi.core.SiddhiAppRuntime; 29 | import org.wso2.siddhi.core.SiddhiManager; 30 | import org.wso2.siddhi.core.event.Event; 31 | import org.wso2.siddhi.core.query.output.callback.QueryCallback; 32 | import org.wso2.siddhi.core.stream.input.InputHandler; 33 | import org.wso2.siddhi.core.util.EventPrinter; 34 | 35 | import java.util.concurrent.atomic.AtomicInteger; 36 | 37 | public class ToJSONFunctionTestCase { 38 | private static final Logger log = Logger.getLogger(ToJSONFunctionTestCase.class); 39 | private AtomicInteger count = new AtomicInteger(0); 40 | private static final String JSON_INPUT = "{name:\"John\", age:25, citizen:false, " + 41 | "bar:[{barName:\"barName\"},{barName:\"barName2\"}]}"; 42 | 43 | @BeforeMethod 44 | public void init() { 45 | count.set(0); 46 | } 47 | 48 | @Test 49 | public void testToJSONObjectFunction() throws InterruptedException, ParseException { 50 | log.info("ToJSONFunctionTestCase - testToJSONObjectFunction"); 51 | SiddhiManager siddhiManager = new SiddhiManager(); 52 | String stream = "define stream InputStream(json string);\n"; 53 | String query = ("@info(name = 'query1')\n" + 54 | "from InputStream\n" + 55 | "select json:toObject(json) as json\n" + 56 | "insert into OutputStream;"); 57 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 58 | JSONParser jsonParser = new JSONParser(); 59 | JSONObject jsonObject = (JSONObject) jsonParser.parse(JSON_INPUT); 60 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 61 | @Override 62 | public void receive(long timeStamp, Event[] inEvents, 63 | Event[] removeEvents) { 64 | EventPrinter.print(timeStamp, inEvents, removeEvents); 65 | for (Event event : inEvents) { 66 | count.incrementAndGet(); 67 | switch (count.get()) { 68 | case 1: 69 | AssertJUnit.assertEquals(jsonObject, event.getData(0)); 70 | break; 71 | } 72 | } 73 | } 74 | }); 75 | 76 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 77 | siddhiAppRuntime.start(); 78 | inputHandler.send(new Object[]{JSON_INPUT}); 79 | siddhiAppRuntime.shutdown(); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /component/src/test/java/org/wso2/extension/siddhi/execution/json/ToStringFunctionTestCase.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.json; 20 | 21 | import net.minidev.json.JSONObject; 22 | import net.minidev.json.parser.JSONParser; 23 | import net.minidev.json.parser.ParseException; 24 | import org.apache.log4j.Logger; 25 | import org.testng.AssertJUnit; 26 | import org.testng.annotations.BeforeMethod; 27 | import org.testng.annotations.Test; 28 | import org.wso2.siddhi.core.SiddhiAppRuntime; 29 | import org.wso2.siddhi.core.SiddhiManager; 30 | import org.wso2.siddhi.core.event.Event; 31 | import org.wso2.siddhi.core.query.output.callback.QueryCallback; 32 | import org.wso2.siddhi.core.stream.input.InputHandler; 33 | import org.wso2.siddhi.core.util.EventPrinter; 34 | 35 | import java.util.concurrent.atomic.AtomicInteger; 36 | 37 | public class ToStringFunctionTestCase { 38 | private static final Logger log = Logger.getLogger(ToStringFunctionTestCase.class); 39 | private AtomicInteger count = new AtomicInteger(0); 40 | private static final String JSON_INPUT = "{name:\"John\", age:25, citizen:false, " + 41 | "bar:[{barName:\"barName\"},{barName:\"barName2\"}]}"; 42 | 43 | @BeforeMethod 44 | public void init() { 45 | count.set(0); 46 | } 47 | 48 | @Test 49 | public void testToStringFunction() throws InterruptedException, ParseException { 50 | log.info("ToStringFunctionTestCase - testToStringFunction"); 51 | SiddhiManager siddhiManager = new SiddhiManager(); 52 | String stream = "define stream InputStream(json object);\n"; 53 | String query = ("@info(name = 'query1')\n" + 54 | "from InputStream\n" + 55 | "select json:toString(json) as json\n" + 56 | "insert into OutputStream;"); 57 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 58 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 59 | @Override 60 | public void receive(long timeStamp, Event[] inEvents, 61 | Event[] removeEvents) { 62 | EventPrinter.print(timeStamp, inEvents, removeEvents); 63 | for (Event event : inEvents) { 64 | count.incrementAndGet(); 65 | switch (count.get()) { 66 | case 1: 67 | AssertJUnit.assertEquals("{\"citizen\":false,\"bar\":[{\"barName\":\"barName\"}," + 68 | "{\"barName\":\"barName2\"}],\"name\":\"John\",\"age\":25}", event.getData(0)); 69 | break; 70 | } 71 | } 72 | } 73 | }); 74 | 75 | JSONParser jsonParser = new JSONParser(); 76 | JSONObject jsonObject = (JSONObject) jsonParser.parse(JSON_INPUT); 77 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 78 | siddhiAppRuntime.start(); 79 | inputHandler.send(new Object[]{jsonObject}); 80 | siddhiAppRuntime.shutdown(); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /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 | 3 | 4 | org.wso2 5 | wso2 6 | 5 7 | 8 | org.wso2.extension.siddhi.execution.json 9 | siddhi-execution-json-parent 10 | 1.0.12-SNAPSHOT 11 | Siddhi Execution Extension - Json Parent Pom 12 | 4.0.0 13 | pom 14 | 15 | 16 | 17 | default 18 | 19 | true 20 | 21 | 22 | component 23 | 24 | 25 | 26 | 27 | 4.2.17 28 | 1.2.17.wso2v1 29 | 2.2.0 30 | 6.11 31 | 0.7.8 32 | 33 | 34 | scm:git:https://github.com/wso2-extensions/siddhi-execution-json.git 35 | https://github.com/wso2-extensions/siddhi-execution-json.git 36 | scm:git:https://github.com/wso2-extensions/siddhi-execution-json.git 37 | 38 | HEAD 39 | 40 | 41 | 42 | 43 | org.wso2.siddhi 44 | siddhi-core 45 | ${siddhi.version} 46 | 47 | 48 | org.wso2.siddhi 49 | siddhi-query-api 50 | ${siddhi.version} 51 | 52 | 53 | com.jayway.jsonpath 54 | json-path 55 | ${com.jayway.jsonpath.version} 56 | 57 | 58 | org.apache.log4j.wso2 59 | log4j 60 | ${log4j.version} 61 | 62 | 63 | javax.mail 64 | mail 65 | 66 | 67 | javax.jms 68 | jms 69 | 70 | 71 | com.sun.jdmk 72 | jmxtools 73 | 74 | 75 | com.sun.jmx 76 | jmxri 77 | 78 | 79 | 80 | 81 | org.testng 82 | testng 83 | ${testng.version} 84 | test 85 | 86 | 87 | org.jacoco 88 | org.jacoco.agent 89 | runtime 90 | ${jacoco.maven.version} 91 | 92 | 93 | 94 | 95 | 96 | 97 | org.apache.maven.plugins 98 | maven-release-plugin 99 | 100 | clean install -Pdocumentation-deploy 101 | true 102 | 103 | 104 | 105 | 106 | 107 | -------------------------------------------------------------------------------- /component/src/test/java/org/wso2/extension/siddhi/execution/json/GetIntJSONFunctionTestCase.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.json; 20 | 21 | import net.minidev.json.JSONObject; 22 | import net.minidev.json.parser.JSONParser; 23 | import net.minidev.json.parser.ParseException; 24 | import org.apache.log4j.Logger; 25 | import org.testng.AssertJUnit; 26 | import org.testng.annotations.BeforeMethod; 27 | import org.testng.annotations.Test; 28 | import org.wso2.siddhi.core.SiddhiAppRuntime; 29 | import org.wso2.siddhi.core.SiddhiManager; 30 | import org.wso2.siddhi.core.event.Event; 31 | import org.wso2.siddhi.core.query.output.callback.QueryCallback; 32 | import org.wso2.siddhi.core.stream.input.InputHandler; 33 | import org.wso2.siddhi.core.util.EventPrinter; 34 | 35 | import java.util.concurrent.atomic.AtomicInteger; 36 | 37 | public class GetIntJSONFunctionTestCase { 38 | private static final Logger log = Logger.getLogger(GetIntJSONFunctionTestCase.class); 39 | private AtomicInteger count = new AtomicInteger(0); 40 | private static final String JSON_INPUT = "{name:\"John\", age:25, citizen:false}"; 41 | 42 | @BeforeMethod 43 | public void init() { 44 | count.set(0); 45 | } 46 | 47 | @Test 48 | public void testGetIntFromJSON() throws InterruptedException { 49 | log.info("GetIntJSONFunctionTestCase - testGetIntFromJSON"); 50 | SiddhiManager siddhiManager = new SiddhiManager(); 51 | String stream = "define stream InputStream(json string,path string);\n"; 52 | String query = ("@info(name = 'query1')\n" + 53 | "from InputStream\n" + 54 | "select json:getInt(json,path) as married\n" + 55 | "insert into OutputStream;"); 56 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 57 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 58 | @Override 59 | public void receive(long timeStamp, Event[] inEvents, 60 | Event[] removeEvents) { 61 | EventPrinter.print(timeStamp, inEvents, removeEvents); 62 | for (Event event : inEvents) { 63 | count.incrementAndGet(); 64 | switch (count.get()) { 65 | case 1: 66 | AssertJUnit.assertEquals(25, event.getData(0)); 67 | break; 68 | case 2: 69 | AssertJUnit.assertEquals(null, event.getData(0)); 70 | break; 71 | case 3: 72 | AssertJUnit.assertEquals(null, event.getData(0)); 73 | break; 74 | case 4: 75 | AssertJUnit.assertEquals(null, event.getData(0)); 76 | break; 77 | } 78 | } 79 | } 80 | }); 81 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 82 | siddhiAppRuntime.start(); 83 | inputHandler.send(new Object[]{JSON_INPUT, "$.age"}); 84 | inputHandler.send(new Object[]{JSON_INPUT, "$.citizen"}); 85 | inputHandler.send(new Object[]{JSON_INPUT, "$.name"}); 86 | inputHandler.send(new Object[]{JSON_INPUT, "$.married"}); 87 | siddhiAppRuntime.shutdown(); 88 | } 89 | 90 | @Test 91 | public void testGetIntFromJSONWithObjectInput() throws InterruptedException, ParseException { 92 | log.info("GetIntJSONFunctionTestCase - testGetIntFromJSONWithObjectInput"); 93 | SiddhiManager siddhiManager = new SiddhiManager(); 94 | String stream = "define stream InputStream(json object,path string);\n"; 95 | String query = ("@info(name = 'query1')\n" + 96 | "from InputStream\n" + 97 | "select json:getInt(json,path) as married\n" + 98 | "insert into OutputStream;"); 99 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 100 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 101 | @Override 102 | public void receive(long timeStamp, Event[] inEvents, 103 | Event[] removeEvents) { 104 | EventPrinter.print(timeStamp, inEvents, removeEvents); 105 | for (Event event : inEvents) { 106 | count.incrementAndGet(); 107 | switch (count.get()) { 108 | case 1: 109 | AssertJUnit.assertEquals(25, event.getData(0)); 110 | break; 111 | case 2: 112 | AssertJUnit.assertEquals(null, event.getData(0)); 113 | break; 114 | case 3: 115 | AssertJUnit.assertEquals(null, event.getData(0)); 116 | break; 117 | case 4: 118 | AssertJUnit.assertEquals(null, event.getData(0)); 119 | break; 120 | } 121 | } 122 | } 123 | }); 124 | JSONParser jsonParser = new JSONParser(); 125 | JSONObject jsonObject = (JSONObject) jsonParser.parse(JSON_INPUT); 126 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 127 | siddhiAppRuntime.start(); 128 | inputHandler.send(new Object[]{jsonObject, "$.age"}); 129 | inputHandler.send(new Object[]{jsonObject, "$.citizen"}); 130 | inputHandler.send(new Object[]{jsonObject, "$.name"}); 131 | inputHandler.send(new Object[]{jsonObject, "$.married"}); 132 | siddhiAppRuntime.shutdown(); 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /component/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | org.wso2.extension.siddhi.execution.json 5 | siddhi-execution-json-parent 6 | 1.0.12-SNAPSHOT 7 | 8 | 4.0.0 9 | siddhi-execution-json 10 | bundle 11 | Siddhi Execution Extension - JSON 12 | 13 | 14 | 15 | org.wso2.siddhi 16 | siddhi-core 17 | 18 | 19 | org.apache.log4j.wso2 20 | log4j 21 | 22 | 23 | com.jayway.jsonpath 24 | json-path 25 | 26 | 27 | org.testng 28 | testng 29 | test 30 | 31 | 32 | 33 | 34 | 35 | 36 | org.apache.maven.plugins 37 | maven-compiler-plugin 38 | 39 | 1.8 40 | 1.8 41 | 42 | 43 | 44 | org.apache.maven.plugins 45 | maven-surefire-plugin 46 | 47 | false 48 | 49 | src/test/resources/testng.xml 50 | 51 | ${surefireArgLine} -ea -Xmx512m 52 | 53 | 54 | 55 | org.jacoco 56 | jacoco-maven-plugin 57 | ${jacoco.maven.version} 58 | 59 | 60 | jacoco-initialize 61 | 62 | prepare-agent 63 | 64 | 65 | ${basedir}/target/coverage-reports/jacoco.exec 66 | surefireArgLine 67 | 68 | 69 | 70 | jacoco-site 71 | post-integration-test 72 | 73 | report 74 | 75 | 76 | ${basedir}/target/coverage-reports/jacoco.exec 77 | ${basedir}/target/coverage-reports/ 78 | 79 | 80 | 81 | 82 | 83 | org.apache.felix 84 | maven-bundle-plugin 85 | true 86 | 87 | 88 | ${project.artifactId} 89 | ${project.artifactId} 90 | 91 | org.wso2.extension.siddhi.execution.json, 92 | org.wso2.extension.siddhi.execution.json.* 93 | 94 | 95 | com.jayway.jsonpath.*, 96 | net.minidev.* 97 | 98 | 99 | *;resolution:=optional 100 | 101 | * 102 | 103 | META-INF=target/classes/META-INF 104 | 105 | 106 | 107 | 108 | 109 | org.wso2.siddhi 110 | siddhi-doc-gen 111 | ${siddhi.version} 112 | 113 | 114 | compile 115 | 116 | generate-md-docs 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | documentation-deploy 126 | 127 | 128 | 129 | org.wso2.siddhi 130 | siddhi-doc-gen 131 | ${siddhi.version} 132 | 133 | 134 | compile 135 | 136 | deploy-mkdocs-github-pages 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | -------------------------------------------------------------------------------- /component/src/test/java/org/wso2/extension/siddhi/execution/json/GetObjectJSONFunctionTestCase.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.json; 20 | 21 | import net.minidev.json.JSONObject; 22 | import net.minidev.json.parser.JSONParser; 23 | import net.minidev.json.parser.ParseException; 24 | import org.apache.log4j.Logger; 25 | import org.testng.AssertJUnit; 26 | import org.testng.annotations.BeforeMethod; 27 | import org.testng.annotations.Test; 28 | import org.wso2.siddhi.core.SiddhiAppRuntime; 29 | import org.wso2.siddhi.core.SiddhiManager; 30 | import org.wso2.siddhi.core.event.Event; 31 | import org.wso2.siddhi.core.query.output.callback.QueryCallback; 32 | import org.wso2.siddhi.core.stream.input.InputHandler; 33 | import org.wso2.siddhi.core.util.EventPrinter; 34 | 35 | import java.util.concurrent.atomic.AtomicInteger; 36 | 37 | public class GetObjectJSONFunctionTestCase { 38 | private static final Logger log = Logger.getLogger(GetObjectJSONFunctionTestCase.class); 39 | private AtomicInteger count = new AtomicInteger(0); 40 | private static final String JSON_INPUT = "{name:\"John\", age:25, citizen:false}"; 41 | 42 | @BeforeMethod 43 | public void init() { 44 | count.set(0); 45 | } 46 | 47 | @Test 48 | public void testGetObjectFromJSON() throws InterruptedException { 49 | log.info("GetObjectJSONFunctionTestCase - testGetObjectFromJSON"); 50 | SiddhiManager siddhiManager = new SiddhiManager(); 51 | String stream = "define stream InputStream(json string,path string);\n"; 52 | String query = ("@info(name = 'query1')\n" + 53 | "from InputStream\n" + 54 | "select json:getObject(json,path) as married\n" + 55 | "insert into OutputStream;"); 56 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 57 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 58 | @Override 59 | public void receive(long timeStamp, Event[] inEvents, 60 | Event[] removeEvents) { 61 | EventPrinter.print(timeStamp, inEvents, removeEvents); 62 | for (Event event : inEvents) { 63 | count.incrementAndGet(); 64 | switch (count.get()) { 65 | case 1: 66 | AssertJUnit.assertEquals(25, event.getData(0)); 67 | break; 68 | case 2: 69 | AssertJUnit.assertEquals(false, event.getData(0)); 70 | break; 71 | case 3: 72 | AssertJUnit.assertEquals("John", event.getData(0)); 73 | break; 74 | case 4: 75 | AssertJUnit.assertEquals(null, event.getData(0)); 76 | break; 77 | } 78 | } 79 | } 80 | }); 81 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 82 | siddhiAppRuntime.start(); 83 | inputHandler.send(new Object[]{JSON_INPUT, "$.age"}); 84 | inputHandler.send(new Object[]{JSON_INPUT, "$.citizen"}); 85 | inputHandler.send(new Object[]{JSON_INPUT, "$.name"}); 86 | inputHandler.send(new Object[]{JSON_INPUT, "$.married"}); 87 | siddhiAppRuntime.shutdown(); 88 | } 89 | 90 | @Test 91 | public void testGetObjectFromJSON2() throws InterruptedException, ParseException { 92 | log.info("GetObjectJSONFunctionTestCase - testGetObjectFromJSON"); 93 | SiddhiManager siddhiManager = new SiddhiManager(); 94 | String stream = "define stream InputStream(json object,path string);\n"; 95 | String query = ("@info(name = 'query1')\n" + 96 | "from InputStream\n" + 97 | "select json:getObject(json,path) as married\n" + 98 | "insert into OutputStream;"); 99 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 100 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 101 | @Override 102 | public void receive(long timeStamp, Event[] inEvents, 103 | Event[] removeEvents) { 104 | EventPrinter.print(timeStamp, inEvents, removeEvents); 105 | for (Event event : inEvents) { 106 | count.incrementAndGet(); 107 | switch (count.get()) { 108 | case 1: 109 | AssertJUnit.assertEquals(25, event.getData(0)); 110 | break; 111 | case 2: 112 | AssertJUnit.assertEquals(false, event.getData(0)); 113 | break; 114 | case 3: 115 | AssertJUnit.assertEquals("John", event.getData(0)); 116 | break; 117 | case 4: 118 | AssertJUnit.assertEquals(null, event.getData(0)); 119 | break; 120 | } 121 | } 122 | } 123 | }); 124 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 125 | JSONParser jsonParser = new JSONParser(); 126 | JSONObject jsonObject = (JSONObject) jsonParser.parse(JSON_INPUT); 127 | siddhiAppRuntime.start(); 128 | inputHandler.send(new Object[]{jsonObject, "$.age"}); 129 | inputHandler.send(new Object[]{jsonObject, "$.citizen"}); 130 | inputHandler.send(new Object[]{jsonObject, "$.name"}); 131 | inputHandler.send(new Object[]{jsonObject, "$.married"}); 132 | siddhiAppRuntime.shutdown(); 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /component/src/test/java/org/wso2/extension/siddhi/execution/json/GetBoolJSONFunctionTestCase.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.json; 20 | 21 | import net.minidev.json.JSONObject; 22 | import net.minidev.json.parser.JSONParser; 23 | import net.minidev.json.parser.ParseException; 24 | import org.apache.log4j.Logger; 25 | import org.testng.AssertJUnit; 26 | import org.testng.annotations.BeforeMethod; 27 | import org.testng.annotations.Test; 28 | import org.wso2.siddhi.core.SiddhiAppRuntime; 29 | import org.wso2.siddhi.core.SiddhiManager; 30 | import org.wso2.siddhi.core.event.Event; 31 | import org.wso2.siddhi.core.query.output.callback.QueryCallback; 32 | import org.wso2.siddhi.core.stream.input.InputHandler; 33 | import org.wso2.siddhi.core.util.EventPrinter; 34 | 35 | import java.util.concurrent.atomic.AtomicInteger; 36 | 37 | public class GetBoolJSONFunctionTestCase { 38 | private static final Logger log = Logger.getLogger(JsonTokenizerStreamProcessorFunctionTestCase.class); 39 | private AtomicInteger count = new AtomicInteger(0); 40 | private static final String JSON_INPUT = "{name:\"John\", married:true, citizen:false}"; 41 | 42 | @BeforeMethod 43 | public void init() { 44 | count.set(0); 45 | } 46 | 47 | @Test 48 | public void testGetBoolFromJSON() throws InterruptedException { 49 | log.info("GetBoolJSONFunctionExtension - testGetBoolFromJSON"); 50 | SiddhiManager siddhiManager = new SiddhiManager(); 51 | String stream = "define stream InputStream(json string,path string);\n"; 52 | String query = ("@info(name = 'query1')\n" + 53 | "from InputStream\n" + 54 | "select json:getBool(json,path) as married\n" + 55 | "insert into OutputStream;"); 56 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 57 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 58 | @Override 59 | public void receive(long timeStamp, Event[] inEvents, 60 | Event[] removeEvents) { 61 | EventPrinter.print(timeStamp, inEvents, removeEvents); 62 | for (Event event : inEvents) { 63 | count.incrementAndGet(); 64 | switch (count.get()) { 65 | case 1: 66 | AssertJUnit.assertEquals(true, event.getData(0)); 67 | break; 68 | case 2: 69 | AssertJUnit.assertEquals(false, event.getData(0)); 70 | break; 71 | case 3: 72 | AssertJUnit.assertEquals(false, event.getData(0)); 73 | break; 74 | case 4: 75 | AssertJUnit.assertEquals(false, event.getData(0)); 76 | break; 77 | } 78 | } 79 | } 80 | }); 81 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 82 | siddhiAppRuntime.start(); 83 | inputHandler.send(new Object[]{JSON_INPUT, "$.married"}); 84 | inputHandler.send(new Object[]{JSON_INPUT, "$.citizen"}); 85 | inputHandler.send(new Object[]{JSON_INPUT, "$.name"}); 86 | inputHandler.send(new Object[]{JSON_INPUT, "$.xyz"}); 87 | siddhiAppRuntime.shutdown(); 88 | } 89 | 90 | @Test 91 | public void testGetBoolFromJSON2() throws InterruptedException, ParseException { 92 | log.info("GetBoolJSONFunctionExtension - testGetBoolFromJSON"); 93 | SiddhiManager siddhiManager = new SiddhiManager(); 94 | String stream = "define stream InputStream(json object,path string);\n"; 95 | String query = ("@info(name = 'query1')\n" + 96 | "from InputStream\n" + 97 | "select json:getBool(json,path) as married\n" + 98 | "insert into OutputStream;"); 99 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 100 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 101 | @Override 102 | public void receive(long timeStamp, Event[] inEvents, 103 | Event[] removeEvents) { 104 | EventPrinter.print(timeStamp, inEvents, removeEvents); 105 | for (Event event : inEvents) { 106 | count.incrementAndGet(); 107 | switch (count.get()) { 108 | case 1: 109 | AssertJUnit.assertEquals(true, event.getData(0)); 110 | break; 111 | case 2: 112 | AssertJUnit.assertEquals(false, event.getData(0)); 113 | break; 114 | case 3: 115 | AssertJUnit.assertEquals(false, event.getData(0)); 116 | break; 117 | case 4: 118 | AssertJUnit.assertEquals(false, event.getData(0)); 119 | break; 120 | } 121 | } 122 | } 123 | }); 124 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 125 | JSONParser jsonParser = new JSONParser(); 126 | JSONObject jsonObject = (JSONObject) jsonParser.parse(JSON_INPUT); 127 | siddhiAppRuntime.start(); 128 | inputHandler.send(new Object[]{jsonObject, "$.married"}); 129 | inputHandler.send(new Object[]{jsonObject, "$.citizen"}); 130 | inputHandler.send(new Object[]{jsonObject, "$.name"}); 131 | inputHandler.send(new Object[]{jsonObject, "$.xyz"}); 132 | siddhiAppRuntime.shutdown(); 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /component/src/test/java/org/wso2/extension/siddhi/execution/json/GetLongJSONFunctionTestCase.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.json; 20 | 21 | import net.minidev.json.JSONObject; 22 | import net.minidev.json.parser.JSONParser; 23 | import net.minidev.json.parser.ParseException; 24 | import org.apache.log4j.Logger; 25 | import org.testng.AssertJUnit; 26 | import org.testng.annotations.BeforeMethod; 27 | import org.testng.annotations.Test; 28 | import org.wso2.siddhi.core.SiddhiAppRuntime; 29 | import org.wso2.siddhi.core.SiddhiManager; 30 | import org.wso2.siddhi.core.event.Event; 31 | import org.wso2.siddhi.core.query.output.callback.QueryCallback; 32 | import org.wso2.siddhi.core.stream.input.InputHandler; 33 | import org.wso2.siddhi.core.util.EventPrinter; 34 | 35 | import java.util.concurrent.atomic.AtomicInteger; 36 | 37 | public class GetLongJSONFunctionTestCase { 38 | private static final Logger log = Logger.getLogger(GetLongJSONFunctionTestCase.class); 39 | private AtomicInteger count = new AtomicInteger(0); 40 | private static final String JSON_INPUT = "{name:\"John\", age:25, citizen:false}"; 41 | 42 | @BeforeMethod 43 | public void init() { 44 | count.set(0); 45 | } 46 | 47 | @Test 48 | public void testGetLongFromJSON() throws InterruptedException { 49 | log.info("GetLongJSONFunctionTestCase - testGetLongFromJSON"); 50 | SiddhiManager siddhiManager = new SiddhiManager(); 51 | String stream = "define stream InputStream(json string,path string);\n"; 52 | String query = ("@info(name = 'query1')\n" + 53 | "from InputStream\n" + 54 | "select json:getLong(json,path) as married\n" + 55 | "insert into OutputStream;"); 56 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 57 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 58 | @Override 59 | public void receive(long timeStamp, Event[] inEvents, 60 | Event[] removeEvents) { 61 | EventPrinter.print(timeStamp, inEvents, removeEvents); 62 | for (Event event : inEvents) { 63 | count.incrementAndGet(); 64 | switch (count.get()) { 65 | case 1: 66 | AssertJUnit.assertEquals(new Long(25), event.getData(0)); 67 | break; 68 | case 2: 69 | AssertJUnit.assertEquals(null, event.getData(0)); 70 | break; 71 | case 3: 72 | AssertJUnit.assertEquals(null, event.getData(0)); 73 | break; 74 | case 4: 75 | AssertJUnit.assertEquals(null, event.getData(0)); 76 | break; 77 | } 78 | } 79 | } 80 | }); 81 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 82 | siddhiAppRuntime.start(); 83 | inputHandler.send(new Object[]{JSON_INPUT, "$.age"}); 84 | inputHandler.send(new Object[]{JSON_INPUT, "$.citizen"}); 85 | inputHandler.send(new Object[]{JSON_INPUT, "$.name"}); 86 | inputHandler.send(new Object[]{JSON_INPUT, "$.married"}); 87 | siddhiAppRuntime.shutdown(); 88 | } 89 | 90 | @Test 91 | public void testGetLongFromJSONWithObjectInput() throws InterruptedException, ParseException { 92 | log.info("GetLongJSONFunctionTestCase - testGetLongFromJSONWithObjectInput"); 93 | SiddhiManager siddhiManager = new SiddhiManager(); 94 | String stream = "define stream InputStream(json object,path string);\n"; 95 | String query = ("@info(name = 'query1')\n" + 96 | "from InputStream\n" + 97 | "select json:getLong(json,path) as married\n" + 98 | "insert into OutputStream;"); 99 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 100 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 101 | @Override 102 | public void receive(long timeStamp, Event[] inEvents, 103 | Event[] removeEvents) { 104 | EventPrinter.print(timeStamp, inEvents, removeEvents); 105 | for (Event event : inEvents) { 106 | count.incrementAndGet(); 107 | switch (count.get()) { 108 | case 1: 109 | AssertJUnit.assertEquals(new Long(25), event.getData(0)); 110 | break; 111 | case 2: 112 | AssertJUnit.assertEquals(null, event.getData(0)); 113 | break; 114 | case 3: 115 | AssertJUnit.assertEquals(null, event.getData(0)); 116 | break; 117 | case 4: 118 | AssertJUnit.assertEquals(null, event.getData(0)); 119 | break; 120 | } 121 | } 122 | } 123 | }); 124 | JSONParser jsonParser = new JSONParser(); 125 | JSONObject jsonObject = (JSONObject) jsonParser.parse(JSON_INPUT); 126 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 127 | siddhiAppRuntime.start(); 128 | inputHandler.send(new Object[]{jsonObject, "$.age"}); 129 | inputHandler.send(new Object[]{jsonObject, "$.citizen"}); 130 | inputHandler.send(new Object[]{jsonObject, "$.name"}); 131 | inputHandler.send(new Object[]{jsonObject, "$.married"}); 132 | siddhiAppRuntime.shutdown(); 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /component/src/test/java/org/wso2/extension/siddhi/execution/json/GetFloatJSONFunctionTestCase.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.json; 20 | 21 | import net.minidev.json.JSONObject; 22 | import net.minidev.json.parser.JSONParser; 23 | import net.minidev.json.parser.ParseException; 24 | import org.apache.log4j.Logger; 25 | import org.testng.AssertJUnit; 26 | import org.testng.annotations.BeforeMethod; 27 | import org.testng.annotations.Test; 28 | import org.wso2.siddhi.core.SiddhiAppRuntime; 29 | import org.wso2.siddhi.core.SiddhiManager; 30 | import org.wso2.siddhi.core.event.Event; 31 | import org.wso2.siddhi.core.query.output.callback.QueryCallback; 32 | import org.wso2.siddhi.core.stream.input.InputHandler; 33 | import org.wso2.siddhi.core.util.EventPrinter; 34 | 35 | import java.util.concurrent.atomic.AtomicInteger; 36 | 37 | public class GetFloatJSONFunctionTestCase { 38 | private static final Logger log = Logger.getLogger(GetFloatJSONFunctionTestCase.class); 39 | private AtomicInteger count = new AtomicInteger(0); 40 | private static final String JSON_INPUT = "{name:\"John\", age:25, citizen:false}"; 41 | 42 | @BeforeMethod 43 | public void init() { 44 | count.set(0); 45 | } 46 | 47 | @Test 48 | public void testGetFloatFromJSON() throws InterruptedException { 49 | log.info("GetFloatJSONFunctionTestCase - testGetFloatFromJSON"); 50 | SiddhiManager siddhiManager = new SiddhiManager(); 51 | String stream = "define stream InputStream(json string,path string);\n"; 52 | String query = ("@info(name = 'query1')\n" + 53 | "from InputStream\n" + 54 | "select json:getFloat(json,path) as married\n" + 55 | "insert into OutputStream;"); 56 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 57 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 58 | @Override 59 | public void receive(long timeStamp, Event[] inEvents, 60 | Event[] removeEvents) { 61 | EventPrinter.print(timeStamp, inEvents, removeEvents); 62 | for (Event event : inEvents) { 63 | count.incrementAndGet(); 64 | switch (count.get()) { 65 | case 1: 66 | AssertJUnit.assertEquals(new Float(25.0), event.getData(0)); 67 | break; 68 | case 2: 69 | AssertJUnit.assertEquals(null, event.getData(0)); 70 | break; 71 | case 3: 72 | AssertJUnit.assertEquals(null, event.getData(0)); 73 | break; 74 | case 4: 75 | AssertJUnit.assertEquals(null, event.getData(0)); 76 | break; 77 | } 78 | } 79 | } 80 | }); 81 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 82 | siddhiAppRuntime.start(); 83 | inputHandler.send(new Object[]{JSON_INPUT, "$.age"}); 84 | inputHandler.send(new Object[]{JSON_INPUT, "$.citizen"}); 85 | inputHandler.send(new Object[]{JSON_INPUT, "$.name"}); 86 | inputHandler.send(new Object[]{JSON_INPUT, "$.married"}); 87 | siddhiAppRuntime.shutdown(); 88 | } 89 | 90 | @Test 91 | public void testGetFloatFromJSONWithObjectInput() throws InterruptedException, ParseException { 92 | log.info("GetFloatJSONFunctionTestCase - testGetFloatFromJSONWithObjectInput"); 93 | SiddhiManager siddhiManager = new SiddhiManager(); 94 | String stream = "define stream InputStream(json object,path string);\n"; 95 | String query = ("@info(name = 'query1')\n" + 96 | "from InputStream\n" + 97 | "select json:getFloat(json,path) as married\n" + 98 | "insert into OutputStream;"); 99 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 100 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 101 | @Override 102 | public void receive(long timeStamp, Event[] inEvents, 103 | Event[] removeEvents) { 104 | EventPrinter.print(timeStamp, inEvents, removeEvents); 105 | for (Event event : inEvents) { 106 | count.incrementAndGet(); 107 | switch (count.get()) { 108 | case 1: 109 | AssertJUnit.assertEquals(new Float(25.0), event.getData(0)); 110 | break; 111 | case 2: 112 | AssertJUnit.assertEquals(null, event.getData(0)); 113 | break; 114 | case 3: 115 | AssertJUnit.assertEquals(null, event.getData(0)); 116 | break; 117 | case 4: 118 | AssertJUnit.assertEquals(null, event.getData(0)); 119 | break; 120 | } 121 | } 122 | } 123 | }); 124 | JSONParser jsonParser = new JSONParser(); 125 | JSONObject jsonObject = (JSONObject) jsonParser.parse(JSON_INPUT); 126 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 127 | siddhiAppRuntime.start(); 128 | inputHandler.send(new Object[]{jsonObject, "$.age"}); 129 | inputHandler.send(new Object[]{jsonObject, "$.citizen"}); 130 | inputHandler.send(new Object[]{jsonObject, "$.name"}); 131 | inputHandler.send(new Object[]{jsonObject, "$.married"}); 132 | siddhiAppRuntime.shutdown(); 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /component/src/test/java/org/wso2/extension/siddhi/execution/json/GetDoubleJSONFunctionTestCase.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.json; 20 | 21 | import net.minidev.json.JSONObject; 22 | import net.minidev.json.parser.JSONParser; 23 | import net.minidev.json.parser.ParseException; 24 | import org.apache.log4j.Logger; 25 | import org.testng.AssertJUnit; 26 | import org.testng.annotations.BeforeMethod; 27 | import org.testng.annotations.Test; 28 | import org.wso2.siddhi.core.SiddhiAppRuntime; 29 | import org.wso2.siddhi.core.SiddhiManager; 30 | import org.wso2.siddhi.core.event.Event; 31 | import org.wso2.siddhi.core.query.output.callback.QueryCallback; 32 | import org.wso2.siddhi.core.stream.input.InputHandler; 33 | import org.wso2.siddhi.core.util.EventPrinter; 34 | 35 | import java.util.concurrent.atomic.AtomicInteger; 36 | 37 | public class GetDoubleJSONFunctionTestCase { 38 | private static final Logger log = Logger.getLogger(GetDoubleJSONFunctionTestCase.class); 39 | private AtomicInteger count = new AtomicInteger(0); 40 | private static final String JSON_INPUT = "{name:\"John\", age:25, citizen:false}"; 41 | 42 | @BeforeMethod 43 | public void init() { 44 | count.set(0); 45 | } 46 | 47 | @Test 48 | public void testGetDoubleFromJSON() throws InterruptedException, ParseException { 49 | log.info("GetDoubleJSONFunctionExtension - testGetDoubleFromJSON"); 50 | SiddhiManager siddhiManager = new SiddhiManager(); 51 | String stream = "define stream InputStream(json string,path string);\n"; 52 | String query = ("@info(name = 'query1')\n" + 53 | "from InputStream\n" + 54 | "select json:getDouble(json,path) as married\n" + 55 | "insert into OutputStream;"); 56 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 57 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 58 | @Override 59 | public void receive(long timeStamp, Event[] inEvents, 60 | Event[] removeEvents) { 61 | EventPrinter.print(timeStamp, inEvents, removeEvents); 62 | for (Event event : inEvents) { 63 | count.incrementAndGet(); 64 | switch (count.get()) { 65 | case 1: 66 | AssertJUnit.assertEquals(25.0, event.getData(0)); 67 | break; 68 | case 2: 69 | AssertJUnit.assertEquals(null, event.getData(0)); 70 | break; 71 | case 3: 72 | AssertJUnit.assertEquals(null, event.getData(0)); 73 | break; 74 | case 4: 75 | AssertJUnit.assertEquals(null, event.getData(0)); 76 | break; 77 | } 78 | } 79 | } 80 | }); 81 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 82 | siddhiAppRuntime.start(); 83 | inputHandler.send(new Object[]{JSON_INPUT, "$.age"}); 84 | inputHandler.send(new Object[]{JSON_INPUT, "$.citizen"}); 85 | inputHandler.send(new Object[]{JSON_INPUT, "$.name"}); 86 | inputHandler.send(new Object[]{JSON_INPUT, "$.married"}); 87 | siddhiAppRuntime.shutdown(); 88 | } 89 | 90 | @Test 91 | public void testGetDoubleFromJSONWithObjectInput() throws InterruptedException, ParseException { 92 | log.info("GetDoubleJSONFunctionExtension - testGetDoubleFromJSONWithObjectInput"); 93 | SiddhiManager siddhiManager = new SiddhiManager(); 94 | String stream = "define stream InputStream(json object,path string);\n"; 95 | String query = ("@info(name = 'query1')\n" + 96 | "from InputStream\n" + 97 | "select json:getDouble(json,path) as married\n" + 98 | "insert into OutputStream;"); 99 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 100 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 101 | @Override 102 | public void receive(long timeStamp, Event[] inEvents, 103 | Event[] removeEvents) { 104 | EventPrinter.print(timeStamp, inEvents, removeEvents); 105 | for (Event event : inEvents) { 106 | count.incrementAndGet(); 107 | switch (count.get()) { 108 | case 1: 109 | AssertJUnit.assertEquals(25.0, event.getData(0)); 110 | break; 111 | case 2: 112 | AssertJUnit.assertEquals(null, event.getData(0)); 113 | break; 114 | case 3: 115 | AssertJUnit.assertEquals(null, event.getData(0)); 116 | break; 117 | case 4: 118 | AssertJUnit.assertEquals(null, event.getData(0)); 119 | break; 120 | } 121 | } 122 | } 123 | }); 124 | 125 | JSONParser jsonParser = new JSONParser(); 126 | JSONObject jsonObject = (JSONObject) jsonParser.parse(JSON_INPUT); 127 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 128 | siddhiAppRuntime.start(); 129 | inputHandler.send(new Object[]{jsonObject, "$.age"}); 130 | inputHandler.send(new Object[]{jsonObject, "$.citizen"}); 131 | inputHandler.send(new Object[]{jsonObject, "$.name"}); 132 | inputHandler.send(new Object[]{jsonObject, "$.married"}); 133 | siddhiAppRuntime.shutdown(); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /component/src/main/java/org/wso2/extension/siddhi/execution/json/function/ToJSONStringFunctionExtension.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.json.function; 20 | 21 | import com.google.gson.Gson; 22 | import com.google.gson.GsonBuilder; 23 | import org.apache.log4j.Logger; 24 | import org.wso2.siddhi.annotation.Example; 25 | import org.wso2.siddhi.annotation.Extension; 26 | import org.wso2.siddhi.annotation.Parameter; 27 | import org.wso2.siddhi.annotation.ReturnAttribute; 28 | import org.wso2.siddhi.annotation.util.DataType; 29 | import org.wso2.siddhi.core.config.SiddhiAppContext; 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 | 36 | import java.util.Map; 37 | 38 | 39 | /** 40 | * This class provides implementation for getting json string from the given object. 41 | */ 42 | @Extension( 43 | name = "toString", 44 | namespace = "json", 45 | description = "This method returns the JSON string corresponding to a given JSON object.", 46 | parameters = { 47 | @Parameter( 48 | name = "json", 49 | description = "A valid JSON object from which the function generates a JSON string.", 50 | type = {DataType.OBJECT}), 51 | }, 52 | returnAttributes = @ReturnAttribute( 53 | description = "Returns the JSON string generated using the given JSON object.", 54 | type = {DataType.STRING}), 55 | examples = @Example( 56 | 57 | syntax = "define stream InputStream(json string);\n" + 58 | "from InputStream\n" + 59 | "select json:toString(json) as jsonString\n" + 60 | "insert into OutputStream;", 61 | description = "This returns the JSON string corresponding to a given JSON object. The results are " + 62 | "directed to the 'OutputStream' stream.") 63 | ) 64 | public class ToJSONStringFunctionExtension extends FunctionExecutor { 65 | private static final Logger log = Logger.getLogger(ToJSONStringFunctionExtension.class); 66 | private static final Gson gson = new GsonBuilder().serializeNulls().create(); 67 | 68 | /** 69 | * The initialization method for {@link FunctionExecutor}, which will be called before other methods and validate 70 | * the all configuration and getting the initial values. 71 | * 72 | * @param attributeExpressionExecutors are the executors of each attributes in the Function 73 | * @param configReader this hold the {@link FunctionExecutor} extensions configuration reader. 74 | * @param siddhiAppContext Siddhi app runtime context 75 | */ 76 | @Override 77 | protected void init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader configReader, 78 | SiddhiAppContext siddhiAppContext) { 79 | 80 | 81 | if (attributeExpressionExecutors.length != 1) { 82 | throw new SiddhiAppValidationException("Invalid no of arguments passed to json:toString() function, " 83 | + "required 1, but found " + attributeExpressionExecutors.length); 84 | } 85 | 86 | if (attributeExpressionExecutors[0] == null) { 87 | throw new SiddhiAppValidationException("Invalid input given to first argument 'json' of " + 88 | "json:toString() function. Input for 'json' argument cannot be null"); 89 | } 90 | Attribute.Type firstAttributeType = attributeExpressionExecutors[0].getReturnType(); 91 | if (!(firstAttributeType == Attribute.Type.OBJECT)) { 92 | throw new SiddhiAppValidationException("Invalid parameter type found for first argument 'json' of " + 93 | "json:toString() function, required " + Attribute.Type.OBJECT + ", but found " + firstAttributeType 94 | .toString()); 95 | } 96 | } 97 | 98 | /** 99 | * The main execution method which will be called upon event arrival 100 | * when there are more than one Function parameter 101 | * 102 | * @param data the runtime values of Function parameters 103 | * @return the Function result 104 | */ 105 | @Override 106 | protected Object execute(Object[] data) { 107 | return null; 108 | } 109 | 110 | /** 111 | * The main execution method which will be called upon event arrival 112 | * when there are zero or one Function parameter 113 | * 114 | * @param data null if the Function parameter count is zero or 115 | * runtime data value of the Function parameter 116 | * @return the Function result 117 | */ 118 | @Override 119 | protected Object execute(Object data) { 120 | return gson.toJson(data); 121 | } 122 | 123 | /** 124 | * return a Class object that represents the formal return type of the method represented by this Method object. 125 | * 126 | * @return the return type for the method this object represents 127 | */ 128 | @Override 129 | public Attribute.Type getReturnType() { 130 | return Attribute.Type.STRING; 131 | } 132 | 133 | /** 134 | * Used to collect the serializable state of the processing element, that need to be 135 | * persisted for reconstructing the element to the same state on a different point of time 136 | * 137 | * @return stateful objects of the processing element as an map 138 | */ 139 | @Override 140 | public Map currentState() { 141 | return null; 142 | } 143 | 144 | /** 145 | * Used to restore serialized state of the processing element, for reconstructing 146 | * the element to the same state as if was on a previous point of time. 147 | * 148 | * @param state the stateful objects of the processing element as a map. 149 | * This is the same map that is created upon calling currentState() method. 150 | */ 151 | @Override 152 | public void restoreState(Map state) { 153 | 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /component/src/test/java/org/wso2/extension/siddhi/execution/json/GetStringJSONFunctionTestCase.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.json; 20 | 21 | import net.minidev.json.JSONObject; 22 | import net.minidev.json.parser.JSONParser; 23 | import net.minidev.json.parser.ParseException; 24 | import org.apache.log4j.Logger; 25 | import org.testng.AssertJUnit; 26 | import org.testng.annotations.BeforeMethod; 27 | import org.testng.annotations.Test; 28 | import org.wso2.siddhi.core.SiddhiAppRuntime; 29 | import org.wso2.siddhi.core.SiddhiManager; 30 | import org.wso2.siddhi.core.event.Event; 31 | import org.wso2.siddhi.core.query.output.callback.QueryCallback; 32 | import org.wso2.siddhi.core.stream.input.InputHandler; 33 | import org.wso2.siddhi.core.util.EventPrinter; 34 | 35 | import java.util.concurrent.atomic.AtomicInteger; 36 | 37 | public class GetStringJSONFunctionTestCase { 38 | private static final Logger log = Logger.getLogger(GetStringJSONFunctionTestCase.class); 39 | private AtomicInteger count = new AtomicInteger(0); 40 | private static final String JSON_INPUT = "{name:\"John\", age:25, citizen:false, " + 41 | "bar:[{barName:\"barName\"},{barName:\"barName2\"}]}"; 42 | 43 | @BeforeMethod 44 | public void init() { 45 | count.set(0); 46 | } 47 | 48 | @Test 49 | public void testGetStringFromJSON() throws InterruptedException { 50 | log.info("GetStringJSONFunctionTestCase - testGetStringFromJSON"); 51 | SiddhiManager siddhiManager = new SiddhiManager(); 52 | String stream = "define stream InputStream(json string,path string);\n"; 53 | String query = ("@info(name = 'query1')\n" + 54 | "from InputStream\n" + 55 | "select json:getString(json,path) as married\n" + 56 | "insert into OutputStream;"); 57 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 58 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 59 | @Override 60 | public void receive(long timeStamp, Event[] inEvents, 61 | Event[] removeEvents) { 62 | EventPrinter.print(timeStamp, inEvents, removeEvents); 63 | for (Event event : inEvents) { 64 | count.incrementAndGet(); 65 | switch (count.get()) { 66 | case 1: 67 | AssertJUnit.assertEquals("25", event.getData(0)); 68 | break; 69 | case 2: 70 | AssertJUnit.assertEquals("false", event.getData(0)); 71 | break; 72 | case 3: 73 | AssertJUnit.assertEquals("John", event.getData(0)); 74 | break; 75 | case 4: 76 | AssertJUnit.assertEquals("[{\"barName\":\"barName\"},{\"barName\":\"barName2\"}]", event 77 | .getData(0)); 78 | break; 79 | case 5: 80 | AssertJUnit.assertEquals(null, event.getData(0)); 81 | break; 82 | } 83 | } 84 | } 85 | }); 86 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 87 | siddhiAppRuntime.start(); 88 | inputHandler.send(new Object[]{JSON_INPUT, "$.age"}); 89 | inputHandler.send(new Object[]{JSON_INPUT, "$.citizen"}); 90 | inputHandler.send(new Object[]{JSON_INPUT, "$.name"}); 91 | inputHandler.send(new Object[]{JSON_INPUT, "$.bar"}); 92 | inputHandler.send(new Object[]{JSON_INPUT, "$.married"}); 93 | siddhiAppRuntime.shutdown(); 94 | } 95 | 96 | @Test 97 | public void testGetStringFromJSON2() throws InterruptedException, ParseException { 98 | log.info("GetStringJSONFunctionTestCase - testGetStringFromJSON"); 99 | SiddhiManager siddhiManager = new SiddhiManager(); 100 | String stream = "define stream InputStream(json object,path string);\n"; 101 | String query = ("@info(name = 'query1')\n" + 102 | "from InputStream\n" + 103 | "select json:getString(json,path) as married\n" + 104 | "insert into OutputStream;"); 105 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 106 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 107 | @Override 108 | public void receive(long timeStamp, Event[] inEvents, 109 | Event[] removeEvents) { 110 | EventPrinter.print(timeStamp, inEvents, removeEvents); 111 | for (Event event : inEvents) { 112 | count.incrementAndGet(); 113 | switch (count.get()) { 114 | case 1: 115 | AssertJUnit.assertEquals("25", event.getData(0)); 116 | break; 117 | case 2: 118 | AssertJUnit.assertEquals("false", event.getData(0)); 119 | break; 120 | case 3: 121 | AssertJUnit.assertEquals("John", event.getData(0)); 122 | break; 123 | case 4: 124 | AssertJUnit.assertEquals("[{\"barName\":\"barName\"},{\"barName\":\"barName2\"}]", event 125 | .getData(0)); 126 | break; 127 | case 5: 128 | AssertJUnit.assertEquals(null, event.getData(0)); 129 | break; 130 | } 131 | } 132 | } 133 | }); 134 | JSONParser jsonParser = new JSONParser(); 135 | JSONObject jsonObject = (JSONObject) jsonParser.parse(JSON_INPUT); 136 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 137 | siddhiAppRuntime.start(); 138 | inputHandler.send(new Object[]{jsonObject, "$.age"}); 139 | inputHandler.send(new Object[]{jsonObject, "$.citizen"}); 140 | inputHandler.send(new Object[]{jsonObject, "$.name"}); 141 | inputHandler.send(new Object[]{jsonObject, "$.bar"}); 142 | inputHandler.send(new Object[]{jsonObject, "$.married"}); 143 | siddhiAppRuntime.shutdown(); 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /component/src/main/java/org/wso2/extension/siddhi/execution/json/function/ToJSONObjectFunctionExtension.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.json.function; 20 | 21 | import net.minidev.json.parser.JSONParser; 22 | import net.minidev.json.parser.ParseException; 23 | import org.apache.log4j.Logger; 24 | import org.wso2.siddhi.annotation.Example; 25 | import org.wso2.siddhi.annotation.Extension; 26 | import org.wso2.siddhi.annotation.Parameter; 27 | import org.wso2.siddhi.annotation.ReturnAttribute; 28 | import org.wso2.siddhi.annotation.util.DataType; 29 | import org.wso2.siddhi.core.config.SiddhiAppContext; 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 | 36 | import java.util.Map; 37 | 38 | 39 | /** 40 | * This class provides implementation for getting json object from the given json string. 41 | */ 42 | @Extension( 43 | name = "toObject", 44 | namespace = "json", 45 | description = "This method returns the JSON object related to a given JSON string.", 46 | parameters = { 47 | @Parameter( 48 | name = "json", 49 | description = "A valid JSON string from which the function generates " + 50 | "the JSON object.", 51 | type = {DataType.STRING}), 52 | }, 53 | returnAttributes = @ReturnAttribute( 54 | description = "Returns the JSON object generated using the given JSON string.", 55 | type = {DataType.OBJECT}), 56 | examples = @Example( 57 | 58 | syntax = "define stream InputStream(json string);\n" + 59 | "from InputStream\n" + 60 | "select json:toJson(json) as jsonObject\n" + 61 | "insert into OutputStream;", 62 | description = "This returns the JSON object corresponding to the given JSON string.The results are" + 63 | "directed to the 'OutputStream' stream.") 64 | ) 65 | public class ToJSONObjectFunctionExtension extends FunctionExecutor { 66 | private static final Logger log = Logger.getLogger(ToJSONObjectFunctionExtension.class); 67 | private static final JSONParser jsonParser = new JSONParser(); 68 | 69 | /** 70 | * The initialization method for {@link FunctionExecutor}, which will be called before other methods and validate 71 | * the all configuration and getting the initial values. 72 | * 73 | * @param attributeExpressionExecutors are the executors of each attributes in the Function 74 | * @param configReader this hold the {@link FunctionExecutor} extensions configuration reader. 75 | * @param siddhiAppContext Siddhi app runtime context 76 | */ 77 | @Override 78 | protected void init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader configReader, 79 | SiddhiAppContext siddhiAppContext) { 80 | 81 | 82 | if (attributeExpressionExecutors.length != 1) { 83 | throw new SiddhiAppValidationException("Invalid no of arguments passed to json:toJson() function, " 84 | + "required 1, but found " + attributeExpressionExecutors.length); 85 | } 86 | 87 | if (attributeExpressionExecutors[0] == null) { 88 | throw new SiddhiAppValidationException("Invalid input given to first argument 'json' of " + 89 | "json:toJson() function. Input for 'json' argument cannot be null"); 90 | } 91 | Attribute.Type firstAttributeType = attributeExpressionExecutors[0].getReturnType(); 92 | if (!(firstAttributeType == Attribute.Type.STRING)) { 93 | throw new SiddhiAppValidationException("Invalid parameter type found for first argument 'json' of " + 94 | "json:toJson() function, required " + Attribute.Type.STRING + ", but found " + firstAttributeType 95 | .toString()); 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 | return null; 109 | } 110 | 111 | /** 112 | * The main execution method which will be called upon event arrival 113 | * when there are zero or one Function parameter 114 | * 115 | * @param data null if the Function parameter count is zero or 116 | * runtime data value of the Function parameter 117 | * @return the Function result 118 | */ 119 | @Override 120 | protected Object execute(Object data) { 121 | Object returnValue = null; 122 | try { 123 | returnValue = jsonParser.parse(data.toString()); 124 | } catch (ParseException e) { 125 | log.error("Cannot parse the given string into JSON. Hence returning null"); 126 | } 127 | return returnValue; 128 | } 129 | 130 | /** 131 | * return a Class object that represents the formal return type of the method represented by this Method object. 132 | * 133 | * @return the return type for the method this object represents 134 | */ 135 | @Override 136 | public Attribute.Type getReturnType() { 137 | return Attribute.Type.OBJECT; 138 | } 139 | 140 | /** 141 | * Used to collect the serializable state of the processing element, that need to be 142 | * persisted for reconstructing the element to the same state on a different point of time 143 | * 144 | * @return stateful objects of the processing element as an map 145 | */ 146 | @Override 147 | public Map currentState() { 148 | return null; 149 | } 150 | 151 | /** 152 | * Used to restore serialized state of the processing element, for reconstructing 153 | * the element to the same state as if was on a previous point of time. 154 | * 155 | * @param state the stateful objects of the processing element as a map. 156 | * This is the same map that is created upon calling currentState() method. 157 | */ 158 | @Override 159 | public void restoreState(Map state) { 160 | 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Siddhi Execution Json Extension 2 | ====================================== 3 | 4 | The **siddhi-execution-json extension** is an extension to Siddhi that provides a rich set of capabilities to retrieve data from JSONs and inserting/modifying elements in JSONs using Siddhi streams. 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.11. 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.json 32 | siddhi-execution-json 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-json/badge/icon)](https://wso2.org/jenkins/view/All%20Builds/job/siddhi/job/siddhi-execution-json/) | 44 | 45 | --- 46 | 47 | 48 | ## Features 49 | 50 | * getBool *(Function)*

This method returns a 'boolean' value, either 'true' or 'false', based on the valuespecified against the JSON element present in the given path.In case there is no valid boolean value found in the given path, the method still returns 'false'.

51 | * getDouble *(Function)*

This method returns the double value of the JSON element present in the given path. If there is no valid double value in the given path, the method returns 'null'.

52 | * getFloat *(Function)*

This method returns the float value of the JSON element present in the given path.If there is no valid float value in the given path, the method returns 'null'.

53 | * getInt *(Function)*

This method returns the integer value of the JSON element present in the given path. If there is no valid integer value in the given path, the method returns 'null'.

54 | * getLong *(Function)*

This returns the long value of the JSON element present in the given path. Ifthere is no valid long value in the given path, the method returns 'null'.

55 | * getObject *(Function)*

This returns the object of the JSON element present in the given path.

56 | * getString *(Function)*

This returns the string value of the JSON element present in the given path.

57 | * isExists *(Function)*

This method checks whether there is a JSON element present in the given path or not.If there is a valid JSON element in the given path, it returns 'true'. If there is no valid JSON element, it returns 'false'

58 | * setElement *(Function)*

This method allows to insert elements into a given JSON present in a specific path. If there is no valid path given, it returns the original JSON. Otherwise, it returns the new JSON.

59 | * toObject *(Function)*

This method returns the JSON object related to a given JSON string.

60 | * toString *(Function)*

This method returns the JSON string corresponding to a given JSON object.

61 | * tokenize *(Stream Processor)*

This tokenizes the given json according the path provided

62 | * tokenizeAsObject *(Stream Processor)*

This tokenizes the given JSON based on the path provided and returns the response as an object.

63 | 64 | ## How to Contribute 65 | 66 | * Please report issues at GitHub Issue Tracker. 67 | 68 | * Send your contributions as pull requests to master branch. 69 | 70 | ## Contact us 71 | 72 | * Post your questions with the "Siddhi" tag in Stackoverflow. 73 | 74 | * Siddhi developers can be contacted via the mailing lists: 75 | 76 | Developers List : [dev@wso2.org](mailto:dev@wso2.org) 77 | 78 | Architecture List : [architecture@wso2.org](mailto:architecture@wso2.org) 79 | 80 | ## Support 81 | 82 | * 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. 83 | 84 | * For more details and to take advantage of this unique opportunity contact us via http://wso2.com/support/. 85 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | Siddhi Execution Json Extension 2 | ====================================== 3 | 4 | The **siddhi-execution-json extension** is an extension to Siddhi that provides a rich set of capabilities to retrieve data from JSONs and inserting/modifying elements in JSONs using Siddhi streams. 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.11. 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.json 32 | siddhi-execution-json 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-json/badge/icon)](https://wso2.org/jenkins/view/All%20Builds/job/siddhi/job/siddhi-execution-json/) | 44 | 45 | --- 46 | 47 | 48 | ## Features 49 | 50 | * getBool *(Function)*

This method returns a 'boolean' value, either 'true' or 'false', based on the valuespecified against the JSON element present in the given path.In case there is no valid boolean value found in the given path, the method still returns 'false'.

51 | * getDouble *(Function)*

This method returns the double value of the JSON element present in the given path. If there is no valid double value in the given path, the method returns 'null'.

52 | * getFloat *(Function)*

This method returns the float value of the JSON element present in the given path.If there is no valid float value in the given path, the method returns 'null'.

53 | * getInt *(Function)*

This method returns the integer value of the JSON element present in the given path. If there is no valid integer value in the given path, the method returns 'null'.

54 | * getLong *(Function)*

This returns the long value of the JSON element present in the given path. Ifthere is no valid long value in the given path, the method returns 'null'.

55 | * getObject *(Function)*

This returns the object of the JSON element present in the given path.

56 | * getString *(Function)*

This returns the string value of the JSON element present in the given path.

57 | * isExists *(Function)*

This method checks whether there is a JSON element present in the given path or not.If there is a valid JSON element in the given path, it returns 'true'. If there is no valid JSON element, it returns 'false'

58 | * setElement *(Function)*

This method allows to insert elements into a given JSON present in a specific path. If there is no valid path given, it returns the original JSON. Otherwise, it returns the new JSON.

59 | * toObject *(Function)*

This method returns the JSON object related to a given JSON string.

60 | * toString *(Function)*

This method returns the JSON string corresponding to a given JSON object.

61 | * tokenize *(Stream Processor)*

This tokenizes the given json according the path provided

62 | * tokenizeAsObject *(Stream Processor)*

This tokenizes the given JSON based on the path provided and returns the response as an object.

63 | 64 | ## How to Contribute 65 | 66 | * Please report issues at GitHub Issue Tracker. 67 | 68 | * Send your contributions as pull requests to master branch. 69 | 70 | ## Contact us 71 | 72 | * Post your questions with the "Siddhi" tag in Stackoverflow. 73 | 74 | * Siddhi developers can be contacted via the mailing lists: 75 | 76 | Developers List : [dev@wso2.org](mailto:dev@wso2.org) 77 | 78 | Architecture List : [architecture@wso2.org](mailto:architecture@wso2.org) 79 | 80 | ## Support 81 | 82 | * 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. 83 | 84 | * For more details and to take advantage of this unique opportunity contact us via http://wso2.com/support/. 85 | -------------------------------------------------------------------------------- /component/src/main/java/org/wso2/extension/siddhi/execution/json/function/GetObjectJSONFunctionExtension.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.json.function; 20 | 21 | import com.google.gson.Gson; 22 | import com.google.gson.GsonBuilder; 23 | import com.jayway.jsonpath.InvalidJsonException; 24 | import com.jayway.jsonpath.JsonPath; 25 | import com.jayway.jsonpath.PathNotFoundException; 26 | import org.apache.log4j.Logger; 27 | import org.wso2.siddhi.annotation.Example; 28 | import org.wso2.siddhi.annotation.Extension; 29 | import org.wso2.siddhi.annotation.Parameter; 30 | import org.wso2.siddhi.annotation.ReturnAttribute; 31 | import org.wso2.siddhi.annotation.util.DataType; 32 | import org.wso2.siddhi.core.config.SiddhiAppContext; 33 | import org.wso2.siddhi.core.exception.SiddhiAppRuntimeException; 34 | import org.wso2.siddhi.core.executor.ExpressionExecutor; 35 | import org.wso2.siddhi.core.executor.function.FunctionExecutor; 36 | import org.wso2.siddhi.core.util.config.ConfigReader; 37 | import org.wso2.siddhi.query.api.definition.Attribute; 38 | import org.wso2.siddhi.query.api.exception.SiddhiAppValidationException; 39 | 40 | import java.util.List; 41 | import java.util.Map; 42 | 43 | 44 | /** 45 | * This class provides implementation for getting Object from the given json based on the 'path' provided. 46 | */ 47 | @Extension( 48 | name = "getObject", 49 | namespace = "json", 50 | description = "This returns the object of the JSON element present in the given path.", 51 | parameters = { 52 | @Parameter( 53 | name = "json", 54 | description = "The JSON input that holds the value in the given path.", 55 | type = {DataType.STRING, DataType.OBJECT}), 56 | @Parameter( 57 | name = "path", 58 | description = "The path of the input JSON from which the 'getObject' function fetches the" + 59 | "object.", 60 | type = {DataType.STRING}) 61 | }, 62 | returnAttributes = @ReturnAttribute( 63 | description = "Returns the object of the input JSON from the input stream.", 64 | type = {DataType.OBJECT}), 65 | examples = @Example( 66 | syntax = "define stream InputStream(json string);\n" + 67 | "from InputStream\n" + 68 | "select json:getObject(json,\"$.name\") as name\n" + 69 | "insert into OutputStream;", 70 | description = "This returns the object of the JSON input in the given path. The results are " + 71 | "directed to the 'OutputStream' stream.") 72 | ) 73 | public class GetObjectJSONFunctionExtension extends FunctionExecutor { 74 | private static final Logger log = Logger.getLogger(GetObjectJSONFunctionExtension.class); 75 | private static final Gson gson = new GsonBuilder().serializeNulls().create(); 76 | 77 | /** 78 | * The initialization method for {@link FunctionExecutor}, which will be called before other methods and validate 79 | * the all configuration and getting the initial values. 80 | * 81 | * @param attributeExpressionExecutors are the executors of each attributes in the Function 82 | * @param configReader this hold the {@link FunctionExecutor} extensions configuration reader. 83 | * @param siddhiAppContext Siddhi app runtime context 84 | */ 85 | @Override 86 | protected void init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader configReader, 87 | SiddhiAppContext siddhiAppContext) { 88 | if (attributeExpressionExecutors.length == 2) { 89 | if (attributeExpressionExecutors[0] == null) { 90 | throw new SiddhiAppValidationException("Invalid input given to first argument 'json' of " + 91 | "json:getObject() function. Input for 'json' argument cannot be null"); 92 | } 93 | Attribute.Type firstAttributeType = attributeExpressionExecutors[0].getReturnType(); 94 | if (!(firstAttributeType == Attribute.Type.STRING || firstAttributeType == Attribute.Type.OBJECT)) { 95 | throw new SiddhiAppValidationException("Invalid parameter type found for first argument 'json' of " + 96 | "json:getObject() function, required " + Attribute.Type.STRING + " or " + Attribute.Type 97 | .OBJECT + ", but found " + firstAttributeType.toString()); 98 | } 99 | 100 | if (attributeExpressionExecutors[1] == null) { 101 | throw new SiddhiAppValidationException("Invalid input given to second argument 'path' of " + 102 | "json:getObject() function. Input 'path' argument cannot be null"); 103 | } 104 | Attribute.Type secondAttributeType = attributeExpressionExecutors[1].getReturnType(); 105 | if (secondAttributeType != Attribute.Type.STRING) { 106 | throw new SiddhiAppValidationException("Invalid parameter type found for second argument 'path' of " + 107 | "json:getObject() function, required " + Attribute.Type.STRING + ", but found " + 108 | secondAttributeType.toString()); 109 | } 110 | } else { 111 | throw new SiddhiAppValidationException("Invalid no of arguments passed to json:getObject() function, " 112 | + "required 2, but found " + attributeExpressionExecutors.length); 113 | } 114 | 115 | } 116 | 117 | /** 118 | * The main execution method which will be called upon event arrival 119 | * when there are more than one Function parameter 120 | * 121 | * @param data the runtime values of Function parameters 122 | * @return the Function result 123 | */ 124 | @Override 125 | protected Object execute(Object[] data) { 126 | String jsonInput; 127 | if (data[0] instanceof String) { 128 | jsonInput = (String) data[0]; 129 | } else { 130 | jsonInput = gson.toJson(data[0]); 131 | } 132 | String path = data[1].toString(); 133 | Object returnValue = null; 134 | try { 135 | returnValue = JsonPath.read(jsonInput, path); 136 | } catch (PathNotFoundException e) { 137 | log.warn("Cannot find json element for the path '" + path + "'. Hence returning the default value 'null'"); 138 | } catch (InvalidJsonException e) { 139 | throw new SiddhiAppRuntimeException("The input JSON is not a valid JSON. Input JSON - " + jsonInput, e); 140 | } 141 | if (returnValue instanceof List) { 142 | if (((List) returnValue).size() == 1) { 143 | returnValue = ((List) returnValue).get(0); 144 | } 145 | } 146 | return returnValue; 147 | } 148 | 149 | /** 150 | * The main execution method which will be called upon event arrival 151 | * when there are zero or one Function parameter 152 | * 153 | * @param data null if the Function parameter count is zero or 154 | * runtime data value of the Function parameter 155 | * @return the Function result 156 | */ 157 | @Override 158 | protected Object execute(Object data) { 159 | return null; 160 | } 161 | 162 | /** 163 | * return a Class object that represents the formal return type of the method represented by this Method object. 164 | * 165 | * @return the return type for the method this object represents 166 | */ 167 | @Override 168 | public Attribute.Type getReturnType() { 169 | return Attribute.Type.OBJECT; 170 | } 171 | 172 | /** 173 | * Used to collect the serializable state of the processing element, that need to be 174 | * persisted for reconstructing the element to the same state on a different point of time 175 | * 176 | * @return stateful objects of the processing element as an map 177 | */ 178 | @Override 179 | public Map currentState() { 180 | return null; 181 | } 182 | 183 | /** 184 | * Used to restore serialized state of the processing element, for reconstructing 185 | * the element to the same state as if was on a previous point of time. 186 | * 187 | * @param state the stateful objects of the processing element as a map. 188 | * This is the same map that is created upon calling currentState() method. 189 | */ 190 | @Override 191 | public void restoreState(Map state) { 192 | 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /component/src/main/java/org/wso2/extension/siddhi/execution/json/function/GetStringJSONFunctionExtension.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.json.function; 20 | 21 | import com.google.gson.Gson; 22 | import com.google.gson.GsonBuilder; 23 | import com.jayway.jsonpath.InvalidJsonException; 24 | import com.jayway.jsonpath.JsonPath; 25 | import com.jayway.jsonpath.PathNotFoundException; 26 | import org.apache.log4j.Logger; 27 | import org.wso2.siddhi.annotation.Example; 28 | import org.wso2.siddhi.annotation.Extension; 29 | import org.wso2.siddhi.annotation.Parameter; 30 | import org.wso2.siddhi.annotation.ReturnAttribute; 31 | import org.wso2.siddhi.annotation.util.DataType; 32 | import org.wso2.siddhi.core.config.SiddhiAppContext; 33 | import org.wso2.siddhi.core.exception.SiddhiAppRuntimeException; 34 | import org.wso2.siddhi.core.executor.ExpressionExecutor; 35 | import org.wso2.siddhi.core.executor.function.FunctionExecutor; 36 | import org.wso2.siddhi.core.util.config.ConfigReader; 37 | import org.wso2.siddhi.query.api.definition.Attribute; 38 | import org.wso2.siddhi.query.api.exception.SiddhiAppValidationException; 39 | 40 | import java.util.Map; 41 | 42 | 43 | /** 44 | * This class provides implementation for getting String values from the given json based on the 'path' provided. 45 | */ 46 | @Extension( 47 | name = "getString", 48 | namespace = "json", 49 | description = "This returns the string value of the JSON element present in the given path.", 50 | parameters = { 51 | @Parameter( 52 | name = "json", 53 | description = "The JSON input that holds the value in the given path.", 54 | type = {DataType.STRING, DataType.OBJECT}), 55 | @Parameter( 56 | name = "path", 57 | description = "The path of the JSON input from which the 'getString' function fetches " + 58 | " the string value.", 59 | type = {DataType.STRING}) 60 | }, 61 | returnAttributes = @ReturnAttribute( 62 | description = "Returns the string value of the input JSON from the input stream.", 63 | type = {DataType.STRING}), 64 | examples = @Example( 65 | syntax = "define stream InputStream(json string);\n" + 66 | "from InputStream\n" + 67 | "select json:getString(json,\"$.name\") as name\n" + 68 | "insert into OutputStream;", 69 | description = "This returns the string value of the JSON input in the given path. The results are " + 70 | "directed to the 'OutputStream' stream.") 71 | ) 72 | public class GetStringJSONFunctionExtension extends FunctionExecutor { 73 | private static final Logger log = Logger.getLogger(GetStringJSONFunctionExtension.class); 74 | private static final Gson gson = new GsonBuilder().serializeNulls().create(); 75 | 76 | /** 77 | * The initialization method for {@link FunctionExecutor}, which will be called before other methods and validate 78 | * the all configuration and getting the initial values. 79 | * 80 | * @param attributeExpressionExecutors are the executors of each attributes in the Function 81 | * @param configReader this hold the {@link FunctionExecutor} extensions configuration reader. 82 | * @param siddhiAppContext Siddhi app runtime context 83 | */ 84 | @Override 85 | protected void init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader configReader, 86 | SiddhiAppContext siddhiAppContext) { 87 | if (attributeExpressionExecutors.length == 2) { 88 | if (attributeExpressionExecutors[0] == null) { 89 | throw new SiddhiAppValidationException("Invalid input given to first argument 'json' of " + 90 | "json:getString() function. Input for 'json' argument cannot be null"); 91 | } 92 | Attribute.Type firstAttributeType = attributeExpressionExecutors[0].getReturnType(); 93 | if (!(firstAttributeType == Attribute.Type.STRING || firstAttributeType == Attribute.Type.OBJECT)) { 94 | throw new SiddhiAppValidationException("Invalid parameter type found for first argument 'json' of " + 95 | "json:getString() function, required " + Attribute.Type.STRING + " or " + Attribute.Type 96 | .OBJECT + ", but found " + firstAttributeType.toString()); 97 | } 98 | 99 | if (attributeExpressionExecutors[1] == null) { 100 | throw new SiddhiAppValidationException("Invalid input given to second argument 'path' of " + 101 | "json:getString() function. Input 'path' argument cannot be null"); 102 | } 103 | Attribute.Type secondAttributeType = attributeExpressionExecutors[1].getReturnType(); 104 | if (secondAttributeType != Attribute.Type.STRING) { 105 | throw new SiddhiAppValidationException("Invalid parameter type found for second argument 'path' of " + 106 | "json:getString() function, required " + Attribute.Type.STRING + ", but found " + 107 | secondAttributeType.toString()); 108 | } 109 | } else { 110 | throw new SiddhiAppValidationException("Invalid no of arguments passed to json:getString() function, " 111 | + "required 2, but found " + attributeExpressionExecutors.length); 112 | } 113 | 114 | } 115 | 116 | /** 117 | * The main execution method which will be called upon event arrival 118 | * when there are more than one Function parameter 119 | * 120 | * @param data the runtime values of Function parameters 121 | * @return the Function result 122 | */ 123 | @Override 124 | protected Object execute(Object[] data) { 125 | String jsonInput; 126 | if (data[0] instanceof String) { 127 | jsonInput = (String) data[0]; 128 | 129 | } else { 130 | jsonInput = gson.toJson(data[0]); 131 | } 132 | String path = data[1].toString(); 133 | Object returnValue = null; 134 | try { 135 | returnValue = JsonPath.read(jsonInput, path); 136 | } catch (PathNotFoundException e) { 137 | log.warn("Cannot find json element for the path '" + path + "'. Hence returning the default value 'null'"); 138 | } catch (InvalidJsonException e) { 139 | throw new SiddhiAppRuntimeException("The input JSON is not a valid JSON. Input JSON - " + jsonInput, e); 140 | } 141 | if (returnValue == null) { 142 | return null; 143 | } else if (!(returnValue instanceof String)) { 144 | returnValue = gson.toJson(returnValue); 145 | } 146 | return returnValue; 147 | } 148 | 149 | /** 150 | * The main execution method which will be called upon event arrival 151 | * when there are zero or one Function parameter 152 | * 153 | * @param data null if the Function parameter count is zero or 154 | * runtime data value of the Function parameter 155 | * @return the Function result 156 | */ 157 | @Override 158 | protected Object execute(Object data) { 159 | return null; 160 | } 161 | 162 | /** 163 | * return a Class object that represents the formal return type of the method represented by this Method object. 164 | * 165 | * @return the return type for the method this object represents 166 | */ 167 | @Override 168 | public Attribute.Type getReturnType() { 169 | return Attribute.Type.STRING; 170 | } 171 | 172 | /** 173 | * Used to collect the serializable state of the processing element, that need to be 174 | * persisted for reconstructing the element to the same state on a different point of time 175 | * 176 | * @return stateful objects of the processing element as an map 177 | */ 178 | @Override 179 | public Map currentState() { 180 | return null; 181 | } 182 | 183 | /** 184 | * Used to restore serialized state of the processing element, for reconstructing 185 | * the element to the same state as if was on a previous point of time. 186 | * 187 | * @param state the stateful objects of the processing element as a map. 188 | * This is the same map that is created upon calling currentState() method. 189 | */ 190 | @Override 191 | public void restoreState(Map state) { 192 | 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /component/src/main/java/org/wso2/extension/siddhi/execution/json/function/IsExistsFunctionExtension.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.json.function; 20 | 21 | import com.google.gson.Gson; 22 | import com.google.gson.GsonBuilder; 23 | import com.jayway.jsonpath.InvalidJsonException; 24 | import com.jayway.jsonpath.JsonPath; 25 | import com.jayway.jsonpath.PathNotFoundException; 26 | import org.apache.log4j.Logger; 27 | import org.wso2.siddhi.annotation.Example; 28 | import org.wso2.siddhi.annotation.Extension; 29 | import org.wso2.siddhi.annotation.Parameter; 30 | import org.wso2.siddhi.annotation.ReturnAttribute; 31 | import org.wso2.siddhi.annotation.util.DataType; 32 | import org.wso2.siddhi.core.config.SiddhiAppContext; 33 | import org.wso2.siddhi.core.exception.SiddhiAppRuntimeException; 34 | import org.wso2.siddhi.core.executor.ExpressionExecutor; 35 | import org.wso2.siddhi.core.executor.function.FunctionExecutor; 36 | import org.wso2.siddhi.core.util.config.ConfigReader; 37 | import org.wso2.siddhi.query.api.definition.Attribute; 38 | import org.wso2.siddhi.query.api.exception.SiddhiAppValidationException; 39 | 40 | import java.util.Map; 41 | 42 | 43 | /** 44 | * This class provides implementation for checking whether there is any json element in the given path or not. 45 | */ 46 | @Extension( 47 | name = "isExists", 48 | namespace = "json", 49 | description = "This method checks whether there is a JSON element present in the given path or not." + 50 | "If there is a valid JSON element in the given path, it returns 'true'. If there is no valid JSON " + 51 | "element, it returns 'false'", 52 | parameters = { 53 | @Parameter( 54 | name = "json", 55 | description = "The JSON input in a given path, on which the function performs the search for" + 56 | "JSON elements.", 57 | type = {DataType.STRING, DataType.OBJECT}), 58 | @Parameter( 59 | name = "path", 60 | description = "The path that contains the input JSON on which the function " + 61 | "performs the search.", 62 | type = {DataType.STRING}) 63 | }, 64 | returnAttributes = @ReturnAttribute( 65 | description = "If there is a valid JSON element in the given path, it returns 'true'. If there is " + 66 | "no valid JSON element, it returns 'false'.", 67 | type = {DataType.BOOL}), 68 | examples = @Example( 69 | 70 | syntax = "define stream InputStream(json string);\n" + 71 | "from InputStream\n" + 72 | "select json:isExists(json,\"$.name\") as name\n" + 73 | "insert into OutputStream;", 74 | description = "This returns either true or false based on the existence of a JSON element in a " + 75 | "given path. The results are directed to the 'OutputStream' stream.") 76 | ) 77 | public class IsExistsFunctionExtension extends FunctionExecutor { 78 | private static final Logger log = Logger.getLogger(IsExistsFunctionExtension.class); 79 | private static final Gson gson = new GsonBuilder().serializeNulls().create(); 80 | 81 | /** 82 | * The initialization method for {@link FunctionExecutor}, which will be called before other methods and validate 83 | * the all configuration and getting the initial values. 84 | * 85 | * @param attributeExpressionExecutors are the executors of each attributes in the Function 86 | * @param configReader this hold the {@link FunctionExecutor} extensions configuration reader. 87 | * @param siddhiAppContext Siddhi app runtime context 88 | */ 89 | @Override 90 | protected void init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader configReader, 91 | SiddhiAppContext siddhiAppContext) { 92 | if (attributeExpressionExecutors.length == 2) { 93 | if (attributeExpressionExecutors[0] == null) { 94 | throw new SiddhiAppValidationException("Invalid input given to first argument 'json' of " + 95 | "json:isExists() function. Input for 'json' argument cannot be null"); 96 | } 97 | Attribute.Type inputJsonAttributeType = attributeExpressionExecutors[0].getReturnType(); 98 | if (!(inputJsonAttributeType == Attribute.Type.STRING || inputJsonAttributeType == Attribute.Type.OBJECT)) { 99 | throw new SiddhiAppValidationException("Invalid parameter type found for first argument 'json' of " + 100 | "json:isExists() function, required " + Attribute.Type.STRING + " or " + Attribute.Type 101 | .OBJECT + ", but found " + inputJsonAttributeType.toString()); 102 | } 103 | if (attributeExpressionExecutors[1] == null) { 104 | throw new SiddhiAppValidationException("Invalid input given to second argument 'path' of " + 105 | "json:isExists() function. Input 'path' argument cannot be null"); 106 | } 107 | Attribute.Type pathAttributeType = attributeExpressionExecutors[1].getReturnType(); 108 | if (pathAttributeType != Attribute.Type.STRING) { 109 | throw new SiddhiAppValidationException("Invalid parameter type found for second argument 'path' of " + 110 | "json:isExists() function, required " + Attribute.Type.STRING + ", but found " + 111 | pathAttributeType.toString()); 112 | } 113 | } else { 114 | throw new SiddhiAppValidationException("Invalid no of arguments passed to json:insertIntoJson() function, " 115 | + "required 2, but found " + attributeExpressionExecutors.length); 116 | } 117 | 118 | } 119 | 120 | /** 121 | * The main execution method which will be called upon event arrival 122 | * when there are more than one Function parameter 123 | * 124 | * @param data the runtime values of Function parameters 125 | * @return the Function result 126 | */ 127 | @Override 128 | protected Object execute(Object[] data) { 129 | String jsonInput; 130 | if (data[0] instanceof String) { 131 | jsonInput = (String) data[0]; 132 | } else { 133 | jsonInput = gson.toJson(data[0]); 134 | } 135 | String path = data[1].toString(); 136 | boolean isExists; 137 | try { 138 | JsonPath.read(jsonInput, path); 139 | isExists = true; 140 | } catch (PathNotFoundException e) { 141 | isExists = false; 142 | } catch (InvalidJsonException e) { 143 | throw new SiddhiAppRuntimeException("The input JSON is not a valid JSON. Input JSON - " + jsonInput, e); 144 | } 145 | return isExists; 146 | } 147 | 148 | /** 149 | * The main execution method which will be called upon event arrival 150 | * when there are zero or one Function parameter 151 | * 152 | * @param data null if the Function parameter count is zero or 153 | * runtime data value of the Function parameter 154 | * @return the Function result 155 | */ 156 | @Override 157 | protected Object execute(Object data) { 158 | return null; 159 | } 160 | 161 | /** 162 | * return a Class object that represents the formal return type of the method represented by this Method object. 163 | * 164 | * @return the return type for the method this object represents 165 | */ 166 | @Override 167 | public Attribute.Type getReturnType() { 168 | return Attribute.Type.BOOL; 169 | } 170 | 171 | /** 172 | * Used to collect the serializable state of the processing element, that need to be 173 | * persisted for reconstructing the element to the same state on a different point of time 174 | * 175 | * @return stateful objects of the processing element as an map 176 | */ 177 | @Override 178 | public Map currentState() { 179 | return null; 180 | } 181 | 182 | /** 183 | * Used to restore serialized state of the processing element, for reconstructing 184 | * the element to the same state as if was/ on a previous point of time. 185 | * 186 | * @param state the stateful objects of the processing element as a map. 187 | * This is the same map that is created upon calling currentState() method. 188 | */ 189 | @Override 190 | public void restoreState(Map state) { 191 | 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /component/src/main/java/org/wso2/extension/siddhi/execution/json/function/GetLongJSONFunctionExtension.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.json.function; 20 | 21 | import com.google.gson.Gson; 22 | import com.google.gson.GsonBuilder; 23 | import com.jayway.jsonpath.InvalidJsonException; 24 | import com.jayway.jsonpath.JsonPath; 25 | import com.jayway.jsonpath.PathNotFoundException; 26 | import org.apache.log4j.Logger; 27 | import org.wso2.siddhi.annotation.Example; 28 | import org.wso2.siddhi.annotation.Extension; 29 | import org.wso2.siddhi.annotation.Parameter; 30 | import org.wso2.siddhi.annotation.ReturnAttribute; 31 | import org.wso2.siddhi.annotation.util.DataType; 32 | import org.wso2.siddhi.core.config.SiddhiAppContext; 33 | import org.wso2.siddhi.core.exception.SiddhiAppRuntimeException; 34 | import org.wso2.siddhi.core.executor.ExpressionExecutor; 35 | import org.wso2.siddhi.core.executor.function.FunctionExecutor; 36 | import org.wso2.siddhi.core.util.config.ConfigReader; 37 | import org.wso2.siddhi.query.api.definition.Attribute; 38 | import org.wso2.siddhi.query.api.exception.SiddhiAppValidationException; 39 | 40 | import java.util.List; 41 | import java.util.Map; 42 | 43 | 44 | /** 45 | * This class provides implementation for getting Long values from the given json based on the 'path' provided. 46 | */ 47 | @Extension( 48 | name = "getLong", 49 | namespace = "json", 50 | description = "This returns the long value of the JSON element present in the given path. If" + 51 | "there is no valid long value in the given path, the method returns 'null'.", 52 | parameters = { 53 | @Parameter( 54 | name = "json", 55 | description = "The JSON input that holds the value in the given path.", 56 | type = {DataType.STRING, DataType.OBJECT}), 57 | @Parameter( 58 | name = "path", 59 | description = "The path of the JSON element from which the 'getLong' function" + 60 | "fetches the long value.", 61 | type = {DataType.STRING}) 62 | }, 63 | returnAttributes = @ReturnAttribute( 64 | description = "Returns the long value of input JSON from the input stream.", 65 | type = {DataType.LONG}), 66 | examples = @Example( 67 | syntax = "define stream InputStream(json string);\n" + 68 | "from InputStream\n" + 69 | "select json:getLong(json,\"$.name\") as name\n" + 70 | "insert into OutputStream;", 71 | description = "This returns the long value of the JSON input in the given path. The results are" + 72 | "directed to 'OutputStream' stream.") 73 | 74 | ) 75 | public class GetLongJSONFunctionExtension extends FunctionExecutor { 76 | private static final Logger log = Logger.getLogger(GetLongJSONFunctionExtension.class); 77 | private static final Gson gson = new GsonBuilder().serializeNulls().create(); 78 | 79 | /** 80 | * The initialization method for {@link FunctionExecutor}, which will be called before other methods and validate 81 | * the all configuration and getting the initial values. 82 | * 83 | * @param attributeExpressionExecutors are the executors of each attributes in the Function 84 | * @param configReader this hold the {@link FunctionExecutor} extensions configuration reader. 85 | * @param siddhiAppContext Siddhi app runtime context 86 | */ 87 | @Override 88 | protected void init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader configReader, 89 | SiddhiAppContext siddhiAppContext) { 90 | if (attributeExpressionExecutors.length == 2) { 91 | if (attributeExpressionExecutors[0] == null) { 92 | throw new SiddhiAppValidationException("Invalid input given to first argument 'json' of " + 93 | "json:getLong() function. Input for 'json' argument cannot be null"); 94 | } 95 | Attribute.Type firstAttributeType = attributeExpressionExecutors[0].getReturnType(); 96 | if (!(firstAttributeType == Attribute.Type.STRING || firstAttributeType == Attribute.Type.OBJECT)) { 97 | throw new SiddhiAppValidationException("Invalid parameter type found for first argument 'json' of " + 98 | "json:getLong() function, required " + Attribute.Type.STRING + " or " + Attribute.Type 99 | .OBJECT + ", but found " + firstAttributeType.toString()); 100 | } 101 | 102 | if (attributeExpressionExecutors[1] == null) { 103 | throw new SiddhiAppValidationException("Invalid input given to second argument 'path' of " + 104 | "json:getLong() function. Input 'path' argument cannot be null"); 105 | } 106 | Attribute.Type secondAttributeType = attributeExpressionExecutors[1].getReturnType(); 107 | if (secondAttributeType != Attribute.Type.STRING) { 108 | throw new SiddhiAppValidationException("Invalid parameter type found for second argument 'path' of " + 109 | "json:getLong() function, required " + Attribute.Type.STRING + ", but found " + 110 | secondAttributeType.toString()); 111 | } 112 | } else { 113 | throw new SiddhiAppValidationException("Invalid no of arguments passed to json:getLong() function, " 114 | + "required 2, but found " + attributeExpressionExecutors.length); 115 | } 116 | 117 | } 118 | 119 | /** 120 | * The main execution method which will be called upon event arrival 121 | * when there are more than one Function parameter 122 | * 123 | * @param data the runtime values of Function parameters 124 | * @return the Function result 125 | */ 126 | @Override 127 | protected Object execute(Object[] data) { 128 | String jsonInput; 129 | if (data[0] instanceof String) { 130 | jsonInput = (String) data[0]; 131 | } else { 132 | jsonInput = gson.toJson(data[0]); 133 | } 134 | String path = data[1].toString(); 135 | Object filteredJsonElement = null; 136 | Long returnValue; 137 | try { 138 | filteredJsonElement = JsonPath.read(jsonInput, path); 139 | } catch (PathNotFoundException e) { 140 | log.error("Cannot find json element for the path '" + path + "'. Hence returning the default value 'null'"); 141 | } catch (InvalidJsonException e) { 142 | throw new SiddhiAppRuntimeException("The input JSON is not a valid JSON. Input JSON - " + jsonInput, e); 143 | } 144 | if (filteredJsonElement instanceof List) { 145 | if (((List) filteredJsonElement).size() != 1) { 146 | filteredJsonElement = null; 147 | log.error("Multiple matches or No matches for the given path '" + path + "' in input json. Please use" + 148 | " valid path which provide exact one match in the given json"); 149 | } else { 150 | filteredJsonElement = ((List) filteredJsonElement).get(0); 151 | } 152 | } 153 | if (filteredJsonElement == null) { 154 | return null; 155 | } 156 | try { 157 | returnValue = Long.parseLong(filteredJsonElement.toString()); 158 | } catch (NumberFormatException e) { 159 | returnValue = null; 160 | log.error("The value that is retrieved using the given path '" + path + "', is not a valid long value. " + 161 | "Hence returning the default value 'null'"); 162 | } 163 | return returnValue; 164 | } 165 | 166 | /** 167 | * The main execution method which will be called upon event arrival 168 | * when there are zero or one Function parameter 169 | * 170 | * @param data null if the Function parameter count is zero or 171 | * runtime data value of the Function parameter 172 | * @return the Function result 173 | */ 174 | @Override 175 | protected Object execute(Object data) { 176 | return null; 177 | } 178 | 179 | /** 180 | * return a Class object that represents the formal return type of the method represented by this Method object. 181 | * 182 | * @return the return type for the method this object represents 183 | */ 184 | @Override 185 | public Attribute.Type getReturnType() { 186 | return Attribute.Type.LONG; 187 | } 188 | 189 | /** 190 | * Used to collect the serializable state of the processing element, that need to be 191 | * persisted for reconstructing the element to the same state on a different point of time 192 | * 193 | * @return stateful objects of the processing element as an map 194 | */ 195 | @Override 196 | public Map currentState() { 197 | return null; 198 | } 199 | 200 | /** 201 | * Used to restore serialized state of the processing element, for reconstructing 202 | * the element to the same state as if was on a previous point of time. 203 | * 204 | * @param state the stateful objects of the processing element as a map. 205 | * This is the same map that is created upon calling currentState() method. 206 | */ 207 | @Override 208 | public void restoreState(Map state) { 209 | 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /component/src/main/java/org/wso2/extension/siddhi/execution/json/function/GetIntJSONFunctionExtension.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.json.function; 20 | 21 | import com.google.gson.Gson; 22 | import com.google.gson.GsonBuilder; 23 | import com.jayway.jsonpath.InvalidJsonException; 24 | import com.jayway.jsonpath.JsonPath; 25 | import com.jayway.jsonpath.PathNotFoundException; 26 | import org.apache.log4j.Logger; 27 | import org.wso2.siddhi.annotation.Example; 28 | import org.wso2.siddhi.annotation.Extension; 29 | import org.wso2.siddhi.annotation.Parameter; 30 | import org.wso2.siddhi.annotation.ReturnAttribute; 31 | import org.wso2.siddhi.annotation.util.DataType; 32 | import org.wso2.siddhi.core.config.SiddhiAppContext; 33 | import org.wso2.siddhi.core.exception.SiddhiAppRuntimeException; 34 | import org.wso2.siddhi.core.executor.ExpressionExecutor; 35 | import org.wso2.siddhi.core.executor.function.FunctionExecutor; 36 | import org.wso2.siddhi.core.util.config.ConfigReader; 37 | import org.wso2.siddhi.query.api.definition.Attribute; 38 | import org.wso2.siddhi.query.api.exception.SiddhiAppValidationException; 39 | 40 | import java.util.List; 41 | import java.util.Map; 42 | 43 | 44 | /** 45 | * This class provides implementation for getting Integer values from the given json based on the 'path' provided. 46 | */ 47 | @Extension( 48 | name = "getInt", 49 | namespace = "json", 50 | description = "This method returns the integer value of the JSON element present in the given path. If " + 51 | "there is no valid integer value in the given path, the method returns 'null'.", 52 | parameters = { 53 | @Parameter( 54 | name = "json", 55 | description = "The JSON input that holds the value in the given path.", 56 | type = {DataType.STRING, DataType.OBJECT}), 57 | @Parameter( 58 | name = "path", 59 | description = "The path of the input JSON from which the 'getInt' function fetches the" + 60 | "integer value.", 61 | type = {DataType.STRING}) 62 | }, 63 | returnAttributes = @ReturnAttribute( 64 | description = "Returns the integer value of the input JSON from the input stream.", 65 | type = {DataType.INT}), 66 | examples = @Example( 67 | 68 | syntax = "define stream InputStream(json string);\n" + 69 | "from InputStream\n" + 70 | "select json:getInt(json,\"$.name\") as name\n" + 71 | "insert into OutputStream;", 72 | description = "This returns the integer value of the JSON input in the given path. The results" + 73 | "are directed to the 'OutputStream' stream.") 74 | ) 75 | public class GetIntJSONFunctionExtension extends FunctionExecutor { 76 | private static final Logger log = Logger.getLogger(GetIntJSONFunctionExtension.class); 77 | private static final Gson gson = new GsonBuilder().serializeNulls().create(); 78 | 79 | /** 80 | * The initialization method for {@link FunctionExecutor}, which will be called before other methods and validate 81 | * the all configuration and getting the initial values. 82 | * 83 | * @param attributeExpressionExecutors are the executors of each attributes in the Function 84 | * @param configReader this hold the {@link FunctionExecutor} extensions configuration reader. 85 | * @param siddhiAppContext Siddhi app runtime context 86 | */ 87 | @Override 88 | protected void init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader configReader, 89 | SiddhiAppContext siddhiAppContext) { 90 | if (attributeExpressionExecutors.length == 2) { 91 | if (attributeExpressionExecutors[0] == null) { 92 | throw new SiddhiAppValidationException("Invalid input given to first argument 'json' of " + 93 | "json:getInt() function. Input for 'json' argument cannot be null"); 94 | } 95 | Attribute.Type firstAttributeType = attributeExpressionExecutors[0].getReturnType(); 96 | if (!(firstAttributeType == Attribute.Type.STRING || firstAttributeType == Attribute.Type.OBJECT)) { 97 | throw new SiddhiAppValidationException("Invalid parameter type found for first argument 'json' of " + 98 | "json:getInt() function, required " + Attribute.Type.STRING + " or " + Attribute.Type 99 | .OBJECT + ", but found " + firstAttributeType.toString()); 100 | } 101 | 102 | if (attributeExpressionExecutors[1] == null) { 103 | throw new SiddhiAppValidationException("Invalid input given to second argument 'path' of " + 104 | "json:getInt() function. Input 'path' argument cannot be null"); 105 | } 106 | Attribute.Type secondAttributeType = attributeExpressionExecutors[1].getReturnType(); 107 | if (secondAttributeType != Attribute.Type.STRING) { 108 | throw new SiddhiAppValidationException("Invalid parameter type found for second argument 'path' of " + 109 | "json:getInt() function, required " + Attribute.Type.STRING + ", but found " + 110 | secondAttributeType.toString()); 111 | } 112 | } else { 113 | throw new SiddhiAppValidationException("Invalid no of arguments passed to json:getInt() function, " 114 | + "required 2, but found " + attributeExpressionExecutors.length); 115 | } 116 | 117 | } 118 | 119 | /** 120 | * The main execution method which will be called upon event arrival 121 | * when there are more than one Function parameter 122 | * 123 | * @param data the runtime values of Function parameters 124 | * @return the Function result 125 | */ 126 | @Override 127 | protected Object execute(Object[] data) { 128 | String jsonInput; 129 | if (data[0] instanceof String) { 130 | jsonInput = (String) data[0]; 131 | } else { 132 | jsonInput = gson.toJson(data[0]); 133 | } 134 | String path = data[1].toString(); 135 | Object filteredJsonElement = null; 136 | Integer returnValue; 137 | try { 138 | filteredJsonElement = JsonPath.read(jsonInput, path); 139 | } catch (PathNotFoundException e) { 140 | log.error("Cannot find json element for the path '" + path + "'. Hence returning the default value 'null'"); 141 | } catch (InvalidJsonException e) { 142 | throw new SiddhiAppRuntimeException("The input JSON is not a valid JSON. Input JSON - " + jsonInput, e); 143 | } 144 | if (filteredJsonElement instanceof List) { 145 | if (((List) filteredJsonElement).size() != 1) { 146 | filteredJsonElement = null; 147 | log.error("Multiple matches or No matches for the given path '" + path + "' in input json. Please use" + 148 | " valid path which provide exact one match in the given json"); 149 | } else { 150 | filteredJsonElement = ((List) filteredJsonElement).get(0); 151 | } 152 | } 153 | if (filteredJsonElement == null) { 154 | return null; 155 | } 156 | try { 157 | returnValue = Integer.parseInt(filteredJsonElement.toString()); 158 | } catch (NumberFormatException e) { 159 | returnValue = null; 160 | log.error("The value that is retrieved using the given path '" + path + "', is not a valid integer value." + 161 | " Hence returning the default value 'null'"); 162 | } 163 | return returnValue; 164 | } 165 | 166 | /** 167 | * The main execution method which will be called upon event arrival 168 | * when there are zero or one Function parameter 169 | * 170 | * @param data null if the Function parameter count is zero or 171 | * runtime data value of the Function parameter 172 | * @return the Function result 173 | */ 174 | @Override 175 | protected Object execute(Object data) { 176 | return null; 177 | } 178 | 179 | /** 180 | * return a Class object that represents the formal return type of the method represented by this Method object. 181 | * 182 | * @return the return type for the method this object represents 183 | */ 184 | @Override 185 | public Attribute.Type getReturnType() { 186 | return Attribute.Type.INT; 187 | } 188 | 189 | /** 190 | * Used to collect the serializable state of the processing element, that need to be 191 | * persisted for reconstructing the element to the same state on a different point of time 192 | * 193 | * @return stateful objects of the processing element as an map 194 | */ 195 | @Override 196 | public Map currentState() { 197 | return null; 198 | } 199 | 200 | /** 201 | * Used to restore serialized state of the processing element, for reconstructing 202 | * the element to the same state as if was on a previous point of time. 203 | * 204 | * @param state the stateful objects of the processing element as a map. 205 | * This is the same map that is created upon calling currentState() method. 206 | */ 207 | @Override 208 | public void restoreState(Map state) { 209 | 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /component/src/main/java/org/wso2/extension/siddhi/execution/json/function/GetFloatJSONFunctionExtension.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.json.function; 20 | 21 | import com.google.gson.Gson; 22 | import com.google.gson.GsonBuilder; 23 | import com.jayway.jsonpath.InvalidJsonException; 24 | import com.jayway.jsonpath.JsonPath; 25 | import com.jayway.jsonpath.PathNotFoundException; 26 | import org.apache.log4j.Logger; 27 | import org.wso2.siddhi.annotation.Example; 28 | import org.wso2.siddhi.annotation.Extension; 29 | import org.wso2.siddhi.annotation.Parameter; 30 | import org.wso2.siddhi.annotation.ReturnAttribute; 31 | import org.wso2.siddhi.annotation.util.DataType; 32 | import org.wso2.siddhi.core.config.SiddhiAppContext; 33 | import org.wso2.siddhi.core.exception.SiddhiAppRuntimeException; 34 | import org.wso2.siddhi.core.executor.ExpressionExecutor; 35 | import org.wso2.siddhi.core.executor.function.FunctionExecutor; 36 | import org.wso2.siddhi.core.util.config.ConfigReader; 37 | import org.wso2.siddhi.query.api.definition.Attribute; 38 | import org.wso2.siddhi.query.api.exception.SiddhiAppValidationException; 39 | 40 | import java.util.List; 41 | import java.util.Map; 42 | 43 | 44 | /** 45 | * This class provides implementation for getting Float values from the given json based on the 'path' provided. 46 | */ 47 | @Extension( 48 | name = "getFloat", 49 | namespace = "json", 50 | description = "This method returns the float value of the JSON element present in the given path." + 51 | "If there is no valid float value in the given path, the method returns 'null'.", 52 | parameters = { 53 | @Parameter( 54 | name = "json", 55 | description = "The JSON input that holds the value in the given path.", 56 | type = {DataType.STRING, DataType.OBJECT}), 57 | @Parameter( 58 | name = "path", 59 | description = "The path of the input JSON from which the 'getFloat' function fetches the" + 60 | "value.", 61 | type = {DataType.STRING}) 62 | }, 63 | returnAttributes = @ReturnAttribute( 64 | description = "Returns the float value of the input JSON from the input stream.", 65 | type = {DataType.FLOAT}), 66 | examples = @Example( 67 | 68 | syntax = "define stream InputStream(json string);\n" + 69 | "from InputStream\n" + 70 | "select json:getFloat(json,\"$.name\") as name\n" + 71 | "insert into OutputStream;", 72 | description = "This returns the float value of the JSON input in the given path. The results are" + 73 | "directed to the 'OutputStream' stream.") 74 | ) 75 | public class GetFloatJSONFunctionExtension extends FunctionExecutor { 76 | private static final Logger log = Logger.getLogger(GetFloatJSONFunctionExtension.class); 77 | private static final Gson gson = new GsonBuilder().serializeNulls().create(); 78 | 79 | /** 80 | * The initialization method for {@link FunctionExecutor}, which will be called before other methods and validate 81 | * the all configuration and getting the initial values. 82 | * 83 | * @param attributeExpressionExecutors are the executors of each attributes in the Function 84 | * @param configReader this hold the {@link FunctionExecutor} extensions configuration reader. 85 | * @param siddhiAppContext Siddhi app runtime context 86 | */ 87 | @Override 88 | protected void init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader configReader, 89 | SiddhiAppContext siddhiAppContext) { 90 | if (attributeExpressionExecutors.length == 2) { 91 | if (attributeExpressionExecutors[0] == null) { 92 | throw new SiddhiAppValidationException("Invalid input given to first argument 'json' of " + 93 | "json:getFloat() function. Input for 'json' argument cannot be null"); 94 | } 95 | Attribute.Type firstAttributeType = attributeExpressionExecutors[0].getReturnType(); 96 | if (!(firstAttributeType == Attribute.Type.STRING || firstAttributeType == Attribute.Type.OBJECT)) { 97 | throw new SiddhiAppValidationException("Invalid parameter type found for first argument 'json' of " + 98 | "json:getFloat() function, required " + Attribute.Type.STRING + " or " + Attribute.Type 99 | .OBJECT + ", but found " + firstAttributeType.toString()); 100 | } 101 | 102 | if (attributeExpressionExecutors[1] == null) { 103 | throw new SiddhiAppValidationException("Invalid input given to second argument 'path' of " + 104 | "json:getFloat() function. Input 'path' argument cannot be null"); 105 | } 106 | Attribute.Type secondAttributeType = attributeExpressionExecutors[1].getReturnType(); 107 | if (secondAttributeType != Attribute.Type.STRING) { 108 | throw new SiddhiAppValidationException("Invalid parameter type found for second argument 'path' of " + 109 | "json:getFloat() function, required " + Attribute.Type.STRING + ", but found " + 110 | secondAttributeType.toString()); 111 | } 112 | } else { 113 | throw new SiddhiAppValidationException("Invalid no of arguments passed to json:getFloat() function, " 114 | + "required 2, but found " + attributeExpressionExecutors.length); 115 | } 116 | 117 | } 118 | 119 | /** 120 | * The main execution method which will be called upon event arrival 121 | * when there are more than one Function parameter 122 | * 123 | * @param data the runtime values of Function parameters 124 | * @return the Function result 125 | */ 126 | @Override 127 | protected Object execute(Object[] data) { 128 | String jsonInput; 129 | if (data[0] instanceof String) { 130 | jsonInput = (String) data[0]; 131 | } else { 132 | jsonInput = gson.toJson(data[0]); 133 | } 134 | String path = data[1].toString(); 135 | Object filteredJsonElement = null; 136 | Float returnValue; 137 | try { 138 | filteredJsonElement = JsonPath.read(jsonInput, path); 139 | } catch (PathNotFoundException e) { 140 | log.error("Cannot find json element for the path '" + path + "'. Hence returning the default value 'null'"); 141 | } catch (InvalidJsonException e) { 142 | throw new SiddhiAppRuntimeException("The input JSON is not a valid JSON. Input JSON - " + jsonInput, e); 143 | } 144 | if (filteredJsonElement instanceof List) { 145 | if (((List) filteredJsonElement).size() != 1) { 146 | filteredJsonElement = null; 147 | log.error("Multiple matches or No matches for the given path '" + path + "' in input json. Please use" + 148 | " valid path which provide exact one match in the given json"); 149 | } else { 150 | filteredJsonElement = ((List) filteredJsonElement).get(0); 151 | } 152 | } 153 | if (filteredJsonElement == null) { 154 | return null; 155 | } 156 | try { 157 | returnValue = Float.parseFloat(filteredJsonElement.toString()); 158 | } catch (NumberFormatException e) { 159 | returnValue = null; 160 | log.error("The value that is retrieved using the given path '" + path + "', is not a valid Float value. " + 161 | "Hence returning the default value 'null'"); 162 | } 163 | return returnValue; 164 | } 165 | 166 | /** 167 | * The main execution method which will be called upon event arrival 168 | * when there are zero or one Function parameter 169 | * 170 | * @param data null if the Function parameter count is zero or 171 | * runtime data value of the Function parameter 172 | * @return the Function result 173 | */ 174 | @Override 175 | protected Object execute(Object data) { 176 | return null; 177 | } 178 | 179 | /** 180 | * return a Class object that represents the formal return type of the method represented by this Method object. 181 | * 182 | * @return the return type for the method this object represents 183 | */ 184 | @Override 185 | public Attribute.Type getReturnType() { 186 | return Attribute.Type.FLOAT; 187 | } 188 | 189 | /** 190 | * Used to collect the serializable state of the processing element, that need to be 191 | * persisted for reconstructing the element to the same state on a different point of time 192 | * 193 | * @return stateful objects of the processing element as an map 194 | */ 195 | @Override 196 | public Map currentState() { 197 | return null; 198 | } 199 | 200 | /** 201 | * Used to restore serialized state of the processing element, for reconstructing 202 | * the element to the same state as if was on a previous point of time. 203 | * 204 | * @param state the stateful objects of the processing element as a map. 205 | * This is the same map that is created upon calling currentState() method. 206 | */ 207 | @Override 208 | public void restoreState(Map state) { 209 | 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /component/src/main/java/org/wso2/extension/siddhi/execution/json/function/GetDoubleJSONFunctionExtension.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.json.function; 20 | 21 | import com.google.gson.Gson; 22 | import com.google.gson.GsonBuilder; 23 | import com.jayway.jsonpath.InvalidJsonException; 24 | import com.jayway.jsonpath.JsonPath; 25 | import com.jayway.jsonpath.PathNotFoundException; 26 | import org.apache.log4j.Logger; 27 | import org.wso2.siddhi.annotation.Example; 28 | import org.wso2.siddhi.annotation.Extension; 29 | import org.wso2.siddhi.annotation.Parameter; 30 | import org.wso2.siddhi.annotation.ReturnAttribute; 31 | import org.wso2.siddhi.annotation.util.DataType; 32 | import org.wso2.siddhi.core.config.SiddhiAppContext; 33 | import org.wso2.siddhi.core.exception.SiddhiAppRuntimeException; 34 | import org.wso2.siddhi.core.executor.ExpressionExecutor; 35 | import org.wso2.siddhi.core.executor.function.FunctionExecutor; 36 | import org.wso2.siddhi.core.util.config.ConfigReader; 37 | import org.wso2.siddhi.query.api.definition.Attribute; 38 | import org.wso2.siddhi.query.api.exception.SiddhiAppValidationException; 39 | 40 | import java.util.List; 41 | import java.util.Map; 42 | 43 | 44 | /** 45 | * This class provides implementation for getting Double values from the given json based on the 'path' provided. 46 | */ 47 | @Extension( 48 | name = "getDouble", 49 | namespace = "json", 50 | description = "This method returns the double value of the JSON element present in the given path. If " + 51 | "there is no valid double value in the given path, the method returns 'null'.", 52 | parameters = { 53 | @Parameter( 54 | name = "json", 55 | description = "The JSON input that holds the value in the given path.", 56 | type = {DataType.STRING, DataType.OBJECT}), 57 | @Parameter( 58 | name = "path", 59 | description = "The path of the input JSON from which the 'getDouble' function fetches the" + 60 | "double value.", 61 | type = {DataType.STRING}) 62 | }, 63 | returnAttributes = @ReturnAttribute( 64 | description = "Returns the double value of the input JSON from the input stream.", 65 | type = {DataType.DOUBLE}), 66 | examples = @Example( 67 | syntax = "define stream InputStream(json string);\n" + 68 | "from InputStream\n" + 69 | "select json:getDouble(json,\"$.name\") as name\n" + 70 | "insert into OutputStream;", 71 | description = "This returns the double value of the given path. The results are" + 72 | "directed to the 'OutputStream' stream.") 73 | ) 74 | public class GetDoubleJSONFunctionExtension extends FunctionExecutor { 75 | private static final Logger log = Logger.getLogger(GetDoubleJSONFunctionExtension.class); 76 | private static final Gson gson = new GsonBuilder().serializeNulls().create(); 77 | 78 | /** 79 | * The initialization method for {@link FunctionExecutor}, which will be called before other methods and validate 80 | * the all configuration and getting the initial values. 81 | * 82 | * @param attributeExpressionExecutors are the executors of each attributes in the Function 83 | * @param configReader this hold the {@link FunctionExecutor} extensions configuration reader. 84 | * @param siddhiAppContext Siddhi app runtime context 85 | */ 86 | @Override 87 | protected void init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader configReader, 88 | SiddhiAppContext siddhiAppContext) { 89 | if (attributeExpressionExecutors.length == 2) { 90 | if (attributeExpressionExecutors[0] == null) { 91 | throw new SiddhiAppValidationException("Invalid input given to first argument 'json' of " + 92 | "json:getDouble() function. Input for 'json' argument cannot be null"); 93 | } 94 | Attribute.Type firstAttributeType = attributeExpressionExecutors[0].getReturnType(); 95 | if (!(firstAttributeType == Attribute.Type.STRING || firstAttributeType == Attribute.Type.OBJECT)) { 96 | throw new SiddhiAppValidationException("Invalid parameter type found for first argument 'json' of " + 97 | "json:getDouble() function, required " + Attribute.Type.STRING + " or " + Attribute.Type 98 | .OBJECT + ", but found " + firstAttributeType.toString()); 99 | } 100 | 101 | if (attributeExpressionExecutors[1] == null) { 102 | throw new SiddhiAppValidationException("Invalid input given to second argument 'path' of " + 103 | "json:getDouble() function. Input 'path' argument cannot be null"); 104 | } 105 | Attribute.Type secondAttributeType = attributeExpressionExecutors[1].getReturnType(); 106 | if (secondAttributeType != Attribute.Type.STRING) { 107 | throw new SiddhiAppValidationException("Invalid parameter type found for second argument 'path' of " + 108 | "json:getDouble() function, required " + Attribute.Type.STRING + ", but found " + 109 | firstAttributeType.toString()); 110 | } 111 | } else { 112 | throw new SiddhiAppValidationException("Invalid no of arguments passed to json:getDouble() function, " 113 | + "required 2, but found " + attributeExpressionExecutors.length); 114 | } 115 | 116 | } 117 | 118 | /** 119 | * The main execution method which will be called upon event arrival 120 | * when there are more than one Function parameter 121 | * 122 | * @param data the runtime values of Function parameters 123 | * @return the Function result 124 | */ 125 | @Override 126 | protected Object execute(Object[] data) { 127 | String jsonInput; 128 | if (data[0] instanceof String) { 129 | jsonInput = (String) data[0]; 130 | } else { 131 | jsonInput = gson.toJson(data[0]); 132 | } 133 | String path = data[1].toString(); 134 | Object filteredJsonElement = null; 135 | Double returnValue; 136 | try { 137 | filteredJsonElement = JsonPath.read(jsonInput, path); 138 | } catch (PathNotFoundException e) { 139 | log.error("Cannot find json element for the path '" + path + "'. Hence it returns the default value, " + 140 | "'null'"); 141 | } catch (InvalidJsonException e) { 142 | throw new SiddhiAppRuntimeException("The input JSON is not a valid JSON. Input JSON - " + jsonInput, e); 143 | } 144 | if (filteredJsonElement instanceof List) { 145 | if (((List) filteredJsonElement).size() != 1) { 146 | filteredJsonElement = null; 147 | log.error("Multiple matches or no matches for the given path '" + path + "' in the input json. " + 148 | "Please use" + 149 | "valid path which provides the exact match for the given json"); 150 | } else { 151 | filteredJsonElement = ((List) filteredJsonElement).get(0); 152 | } 153 | } 154 | if (filteredJsonElement == null) { 155 | return null; 156 | } 157 | try { 158 | returnValue = Double.parseDouble(filteredJsonElement.toString()); 159 | } catch (NumberFormatException e) { 160 | returnValue = null; 161 | log.error("The value that is retrieved using the given path '" + path + "', is not a valid double value. " + 162 | "Hence it returns the default value, 'null'"); 163 | } 164 | return returnValue; 165 | } 166 | 167 | /** 168 | * The main execution method which will be called upon event arrival 169 | * when there are zero or one Function parameter 170 | * 171 | * @param data null if the Function parameter count is zero or 172 | * runtime data value of the Function parameter 173 | * @return the Function result 174 | */ 175 | @Override 176 | protected Object execute(Object data) { 177 | return null; 178 | } 179 | 180 | /** 181 | * return a Class object that represents the formal return type of the method represented by this Method object. 182 | * 183 | * @return the return type for the method this object represents 184 | */ 185 | @Override 186 | public Attribute.Type getReturnType() { 187 | return Attribute.Type.DOUBLE; 188 | } 189 | 190 | /** 191 | * Used to collect the serializable state of the processing element, that need to be 192 | * persisted for reconstructing the element to the same state on a different point of time 193 | * 194 | * @return stateful objects of the processing element as an map 195 | */ 196 | @Override 197 | public Map currentState() { 198 | return null; 199 | } 200 | 201 | /** 202 | * Used to restore serialized state of the processing element, for reconstructing 203 | * the element to the same state as if was on a previous point of time. 204 | * 205 | * @param state the stateful objects of the processing element as a map. 206 | * This is the same map that is created upon calling currentState() method. 207 | */ 208 | @Override 209 | public void restoreState(Map state) { 210 | 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /component/src/main/java/org/wso2/extension/siddhi/execution/json/function/GetBoolJSONFunctionExtension.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.json.function; 20 | 21 | import com.google.gson.Gson; 22 | import com.google.gson.GsonBuilder; 23 | import com.jayway.jsonpath.InvalidJsonException; 24 | import com.jayway.jsonpath.JsonPath; 25 | import com.jayway.jsonpath.PathNotFoundException; 26 | import org.apache.log4j.Logger; 27 | import org.wso2.siddhi.annotation.Example; 28 | import org.wso2.siddhi.annotation.Extension; 29 | import org.wso2.siddhi.annotation.Parameter; 30 | import org.wso2.siddhi.annotation.ReturnAttribute; 31 | import org.wso2.siddhi.annotation.util.DataType; 32 | import org.wso2.siddhi.core.config.SiddhiAppContext; 33 | import org.wso2.siddhi.core.exception.SiddhiAppRuntimeException; 34 | import org.wso2.siddhi.core.executor.ExpressionExecutor; 35 | import org.wso2.siddhi.core.executor.function.FunctionExecutor; 36 | import org.wso2.siddhi.core.util.config.ConfigReader; 37 | import org.wso2.siddhi.query.api.definition.Attribute; 38 | import org.wso2.siddhi.query.api.exception.SiddhiAppValidationException; 39 | 40 | import java.util.List; 41 | import java.util.Map; 42 | 43 | 44 | /** 45 | * This class provides implementation for getting Boolean values from the given json based on the 'path' provided. 46 | */ 47 | @Extension( 48 | name = "getBool", 49 | namespace = "json", 50 | description = "This method returns a 'boolean' value, either 'true' or 'false', based on the value" + 51 | "specified against the JSON element present in the given path." + 52 | "In case there is no valid boolean value found in the given path, the method still returns 'false'.", 53 | parameters = { 54 | @Parameter( 55 | name = "json", 56 | description = "The JSON input that holds the boolean value in the given path.", 57 | type = {DataType.STRING, DataType.OBJECT}), 58 | @Parameter( 59 | name = "path", 60 | description = "The path of the input JSON from which the 'getBool' function fetches the" + 61 | "boolean value.", 62 | type = {DataType.STRING}) 63 | }, 64 | returnAttributes = @ReturnAttribute( 65 | description = "Returns the boolean value of the input JSON from the input stream.", 66 | type = {DataType.BOOL}), 67 | examples = @Example( 68 | syntax = "define stream InputStream(json string);\n" + 69 | "from InputStream\n" + 70 | "select json:getBool(json,\"$.name\") as name\n" + 71 | "insert into OutputStream;", 72 | description = "This returns the boolean value of the JSON input in the given path. The results are " + 73 | "directed to the 'OutputStream' stream." 74 | ) 75 | ) 76 | public class GetBoolJSONFunctionExtension extends FunctionExecutor { 77 | private static final Logger log = Logger.getLogger(GetBoolJSONFunctionExtension.class); 78 | private static final Gson gson = new GsonBuilder().serializeNulls().create(); 79 | 80 | /** 81 | * The initialization method for {@link FunctionExecutor}, which will be called before other methods and validate 82 | * the all configuration and getting the initial values. 83 | * 84 | * @param attributeExpressionExecutors are the executors of each attributes in the Function 85 | * @param configReader this hold the {@link FunctionExecutor} extensions configuration reader. 86 | * @param siddhiAppContext Siddhi app runtime context 87 | */ 88 | @Override 89 | protected void init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader configReader, 90 | SiddhiAppContext siddhiAppContext) { 91 | if (attributeExpressionExecutors.length == 2) { 92 | if (attributeExpressionExecutors[0] == null) { 93 | throw new SiddhiAppValidationException("Invalid input given to the first argument 'json' of " + 94 | "json:getBool() function. Input for 'json' argument cannot be null"); 95 | } 96 | Attribute.Type firstAttributeType = attributeExpressionExecutors[0].getReturnType(); 97 | if (!(firstAttributeType == Attribute.Type.STRING || firstAttributeType == Attribute.Type.OBJECT)) { 98 | throw new SiddhiAppValidationException("Invalid parameter type found for first argument 'json' of " + 99 | "json:getBool() function, required " + Attribute.Type.STRING + " or " + Attribute.Type 100 | .OBJECT + ", but found " + firstAttributeType.toString()); 101 | } 102 | 103 | if (attributeExpressionExecutors[1] == null) { 104 | throw new SiddhiAppValidationException("Invalid input given to second argument 'path' of " + 105 | "json:getBool() function. Input 'path' argument cannot be null"); 106 | } 107 | Attribute.Type secondAttributeType = attributeExpressionExecutors[1].getReturnType(); 108 | if (secondAttributeType != Attribute.Type.STRING) { 109 | throw new SiddhiAppValidationException("Invalid parameter type found for second argument 'path' of " + 110 | "json:getBool() function, required " + Attribute.Type.STRING + ", but found " + 111 | secondAttributeType.toString()); 112 | } 113 | } else { 114 | throw new SiddhiAppValidationException("Invalid no of arguments passed to json:getBool() function, " 115 | + "required 2, but found " + attributeExpressionExecutors.length); 116 | } 117 | 118 | } 119 | 120 | /** 121 | * The main execution method which will be called upon event arrival 122 | * when there are more than one Function parameter 123 | * 124 | * @param data the runtime values of Function parameters 125 | * @return the Function result 126 | */ 127 | @Override 128 | protected Object execute(Object[] data) { 129 | String jsonInput; 130 | if (data[0] instanceof String) { 131 | jsonInput = (String) data[0]; 132 | } else { 133 | jsonInput = gson.toJson(data[0]); 134 | } 135 | String path = data[1].toString(); 136 | Object filteredJsonElement = null; 137 | Boolean returnValue; 138 | try { 139 | filteredJsonElement = JsonPath.read(jsonInput, path); 140 | } catch (PathNotFoundException e) { 141 | log.error("Cannot find the json element for the path '" + path + "'. Hence it returns" + 142 | "the default value 'null'"); 143 | } catch (InvalidJsonException e) { 144 | throw new SiddhiAppRuntimeException("The input JSON is not a valid JSON. Input JSON - " + jsonInput, e); 145 | } 146 | if (filteredJsonElement instanceof List) { 147 | if (((List) filteredJsonElement).size() != 1) { 148 | filteredJsonElement = null; 149 | log.error("Multiple matches or No matches for the given path '" + path + "' in input json. Please use" + 150 | " valid path which provide exact one match in the given json"); 151 | } else { 152 | filteredJsonElement = ((List) filteredJsonElement).get(0); 153 | } 154 | } 155 | if (filteredJsonElement == null) { 156 | return null; 157 | } 158 | returnValue = Boolean.parseBoolean(filteredJsonElement.toString()); 159 | if (returnValue == false && !filteredJsonElement.toString().equalsIgnoreCase("false")) { 160 | returnValue = null; 161 | log.error("The value that is retrieved using the given path '" + path + "', is not a valid boolean value." + 162 | " Hence it returns the default value 'null'"); 163 | } 164 | return returnValue; 165 | } 166 | 167 | /** 168 | * The main execution method which will be called upon event arrival 169 | * when there are zero or one Function parameter 170 | * 171 | * @param data null if the Function parameter count is zero or 172 | * runtime data value of the Function parameter 173 | * @return the Function result 174 | */ 175 | @Override 176 | protected Object execute(Object data) { 177 | return null; 178 | } 179 | 180 | /** 181 | * return a Class object that represents the formal return type of the method represented by this Method object. 182 | * 183 | * @return the return type for the method this object represents 184 | */ 185 | @Override 186 | public Attribute.Type getReturnType() { 187 | return Attribute.Type.BOOL; 188 | } 189 | 190 | /** 191 | * Used to collect the serializable state of the processing element, that need to be 192 | * persisted for reconstructing the element to the same state on a different point of time 193 | * 194 | * @return stateful objects of the processing element as an map 195 | */ 196 | @Override 197 | public Map currentState() { 198 | return null; 199 | } 200 | 201 | /** 202 | * Used to restore serialized state of the processing element, for reconstructing 203 | * the element to the same state as if was on a previous point of time. 204 | * 205 | * @param state the stateful objects of the processing element as a map. 206 | * This is the same map that is created upon calling currentState() method. 207 | */ 208 | @Override 209 | public void restoreState(Map state) { 210 | 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /component/src/test/java/org/wso2/extension/siddhi/execution/json/JsonTokenizerStreamProcessorFunctionTestCase.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.json; 20 | 21 | import net.minidev.json.JSONObject; 22 | import net.minidev.json.parser.JSONParser; 23 | import net.minidev.json.parser.ParseException; 24 | import org.apache.log4j.Logger; 25 | import org.testng.AssertJUnit; 26 | import org.testng.annotations.BeforeMethod; 27 | import org.testng.annotations.Test; 28 | import org.wso2.siddhi.core.SiddhiAppRuntime; 29 | import org.wso2.siddhi.core.SiddhiManager; 30 | import org.wso2.siddhi.core.event.Event; 31 | import org.wso2.siddhi.core.query.output.callback.QueryCallback; 32 | import org.wso2.siddhi.core.stream.input.InputHandler; 33 | import org.wso2.siddhi.core.util.EventPrinter; 34 | 35 | import java.util.concurrent.atomic.AtomicInteger; 36 | 37 | public class JsonTokenizerStreamProcessorFunctionTestCase { 38 | private static final Logger log = Logger.getLogger(JsonTokenizerStreamProcessorFunctionTestCase.class); 39 | private AtomicInteger count = new AtomicInteger(0); 40 | private static final String JSON_INPUT = "{emp:[" + 41 | "{\"name\":\"John\", foo:{fooName:\"fooName\"}, bar:[{barName:\"barName\"},{barName:\"barName2\"}]}," + 42 | "{\"name\":\"Peter\", foo:{fooName:\"fooName2\"}, bar:[{barName:\"barName3\"},{barName:\"barName4\"}]}" + 43 | "]}"; 44 | 45 | @BeforeMethod 46 | public void init() { 47 | count.set(0); 48 | } 49 | 50 | @Test 51 | public void testJsonTokenizerWithStringInput() throws InterruptedException { 52 | log.info("JsonTokenizerStreamProcessorFunction - testJsonTokenizerWithStringInput"); 53 | SiddhiManager siddhiManager = new SiddhiManager(); 54 | String stream = "define stream InputStream(json string,path string);\n"; 55 | String query = ("@info(name = 'query1')\n" + 56 | "from InputStream#json:tokenize(json, path)\n" + 57 | "select jsonElement\n" + 58 | "insert into OutputStream;"); 59 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 60 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 61 | @Override 62 | public void receive(long timeStamp, Event[] inEvents, 63 | Event[] removeEvents) { 64 | EventPrinter.print(timeStamp, inEvents, removeEvents); 65 | for (Event event : inEvents) { 66 | count.incrementAndGet(); 67 | switch (count.get()) { 68 | case 1: 69 | AssertJUnit.assertEquals("John", event.getData(0)); 70 | break; 71 | case 2: 72 | AssertJUnit.assertEquals("Peter", event.getData(0)); 73 | break; 74 | case 3: 75 | AssertJUnit.assertEquals("{\"fooName\":\"fooName\"}", event.getData(0)); 76 | break; 77 | case 4: 78 | AssertJUnit.assertEquals("{\"barName\":\"barName\"}", event.getData(0)); 79 | break; 80 | case 5: 81 | AssertJUnit.assertEquals("{\"barName\":\"barName2\"}", event.getData(0)); 82 | break; 83 | case 6: 84 | AssertJUnit.assertEquals("[{\"barName\":\"barName\"},{\"barName\":\"barName2\"}]", event 85 | .getData(0)); 86 | break; 87 | case 7: 88 | AssertJUnit.assertEquals("[{\"barName\":\"barName3\"},{\"barName\":\"barName4\"}]", event 89 | .getData(0)); 90 | break; 91 | } 92 | } 93 | } 94 | }); 95 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 96 | siddhiAppRuntime.start(); 97 | inputHandler.send(new Object[]{JSON_INPUT, "$.emp[0].name"}); 98 | inputHandler.send(new Object[]{JSON_INPUT, "$.emp[1].name"}); 99 | inputHandler.send(new Object[]{JSON_INPUT, "$.emp[0].foo"}); 100 | inputHandler.send(new Object[]{JSON_INPUT, "$.emp[0].bar"}); 101 | inputHandler.send(new Object[]{JSON_INPUT, "$..bar"}); 102 | siddhiAppRuntime.shutdown(); 103 | } 104 | 105 | @Test 106 | public void testJsonTokenizerWithObjectInput() throws InterruptedException, ParseException { 107 | log.info("JsonTokenizerStreamProcessorFunction - testJsonTokenizerWithObjectInput"); 108 | SiddhiManager siddhiManager = new SiddhiManager(); 109 | String stream = "define stream InputStream(json object,path string);\n"; 110 | String query = ("@info(name = 'query1')\n" + 111 | "from InputStream#json:tokenize(json, path, false)\n" + 112 | "select jsonElement\n" + 113 | "insert into OutputStream;"); 114 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 115 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 116 | @Override 117 | public void receive(long timeStamp, Event[] inEvents, 118 | Event[] removeEvents) { 119 | EventPrinter.print(timeStamp, inEvents, removeEvents); 120 | for (Event event : inEvents) { 121 | count.incrementAndGet(); 122 | switch (count.get()) { 123 | case 1: 124 | AssertJUnit.assertEquals("John", event.getData(0)); 125 | break; 126 | case 2: 127 | AssertJUnit.assertEquals("Peter", event.getData(0)); 128 | break; 129 | case 3: 130 | AssertJUnit.assertEquals("{\"fooName\":\"fooName\"}", event.getData(0)); 131 | break; 132 | case 4: 133 | AssertJUnit.assertEquals("{\"barName\":\"barName\"}", event.getData(0)); 134 | break; 135 | case 5: 136 | AssertJUnit.assertEquals("{\"barName\":\"barName2\"}", event.getData(0)); 137 | break; 138 | case 6: 139 | AssertJUnit.assertEquals("[{\"barName\":\"barName\"},{\"barName\":\"barName2\"}]", event 140 | .getData(0)); 141 | break; 142 | case 7: 143 | AssertJUnit.assertEquals("[{\"barName\":\"barName3\"},{\"barName\":\"barName4\"}]", event 144 | .getData(0)); 145 | break; 146 | case 8: 147 | AssertJUnit.assertEquals(null, event.getData(0)); 148 | break; 149 | } 150 | } 151 | } 152 | }); 153 | JSONParser jsonParser = new JSONParser(); 154 | JSONObject jsonObject = (JSONObject) jsonParser.parse(JSON_INPUT); 155 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 156 | siddhiAppRuntime.start(); 157 | inputHandler.send(new Object[]{jsonObject, "$.emp[0].name"}); 158 | inputHandler.send(new Object[]{jsonObject, "$.emp[1].name"}); 159 | inputHandler.send(new Object[]{jsonObject, "$.emp[0].foo"}); 160 | inputHandler.send(new Object[]{jsonObject, "$.emp[0].bar"}); 161 | inputHandler.send(new Object[]{jsonObject, "$..bar"}); 162 | inputHandler.send(new Object[]{jsonObject, "$.name"}); 163 | siddhiAppRuntime.shutdown(); 164 | 165 | } 166 | 167 | @Test 168 | public void testJsonTokenizerWithFailOnMissingAttribute() throws InterruptedException { 169 | log.info("JsonTokenizerStreamProcessorFunction - testJsonTokenizerWithFailOnMissingAttribute"); 170 | SiddhiManager siddhiManager = new SiddhiManager(); 171 | String stream = "define stream InputStream(json string,path string);\n"; 172 | String query = ("@info(name = 'query1')\n" + 173 | "from InputStream#json:tokenize(json, path, false)\n" + 174 | "select jsonElement\n" + 175 | "insert into OutputStream;"); 176 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 177 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 178 | @Override 179 | public void receive(long timeStamp, Event[] inEvents, 180 | Event[] removeEvents) { 181 | EventPrinter.print(timeStamp, inEvents, removeEvents); 182 | for (Event event : inEvents) { 183 | count.incrementAndGet(); 184 | } 185 | } 186 | }); 187 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 188 | siddhiAppRuntime.start(); 189 | inputHandler.send(new Object[]{JSON_INPUT, "$.name"}); 190 | inputHandler.send(new Object[]{JSON_INPUT, "$..xyz"}); 191 | AssertJUnit.assertEquals(2, count.get()); 192 | siddhiAppRuntime.shutdown(); 193 | } 194 | 195 | @Test 196 | public void testJsonTokenizerWithoutFailOnMissingAttribute() throws InterruptedException { 197 | log.info("JsonTokenizerStreamProcessorFunction - testJsonTokenizerWithFailOnMissingAttribute"); 198 | SiddhiManager siddhiManager = new SiddhiManager(); 199 | String stream = "define stream InputStream(json string,path string);\n"; 200 | String query = ("@info(name = 'query1')\n" + 201 | "from InputStream#json:tokenize(json, path)\n" + 202 | "select jsonElement\n" + 203 | "insert into OutputStream;"); 204 | SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); 205 | siddhiAppRuntime.addCallback("query1", new QueryCallback() { 206 | @Override 207 | public void receive(long timeStamp, Event[] inEvents, 208 | Event[] removeEvents) { 209 | EventPrinter.print(timeStamp, inEvents, removeEvents); 210 | for (Event event : inEvents) { 211 | count.incrementAndGet(); 212 | } 213 | } 214 | }); 215 | InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); 216 | siddhiAppRuntime.start(); 217 | inputHandler.send(new Object[]{JSON_INPUT, "$.name"}); 218 | inputHandler.send(new Object[]{JSON_INPUT, "$..xyz"}); 219 | AssertJUnit.assertEquals(0, count.get()); 220 | siddhiAppRuntime.shutdown(); 221 | } 222 | 223 | } 224 | 225 | 226 | --------------------------------------------------------------------------------