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 | * 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 | * 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 | * /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 | [](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 |
--------------------------------------------------------------------------------