You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@apex.apache.org by shubham-pathak22 <gi...@git.apache.org> on 2016/01/06 12:06:42 UTC
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
GitHub user shubham-pathak22 opened a pull request:
https://github.com/apache/incubator-apex-malhar/pull/163
MLHR-1962 json parser enhancements
* Enhanced existing JSON Parser.
* Now user can provide json schema against which the incoming tuple would be validated.
* JSON Schema is as per http://json-schema.org/
* Operator has 3 output ports.
* **ParsedOutputPort :** emits incoming JSON as JSONObject.
* **Out port:** emits incoming JSON as POJO
* **Err port:** emits tuples that could not be parsed as a KeyValPair where key is the tuple and value is the reason.
* POJO class needs to be provided if downstream operator connects to port that emits POJO.
* Metrics are provided to give count of incomingTuples, errorTuples, pojos , and parsedObjects (JSONObject)
You can merge this pull request into a Git repository by running:
$ git pull https://github.com/shubham-pathak22/incubator-apex-malhar MLHR-1962
Alternatively you can review and apply these changes as the patch at:
https://github.com/apache/incubator-apex-malhar/pull/163.patch
To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:
This closes #163
----
commit 967c88cd257c350d58d4e726b63a868bdbd2373c
Author: shubham <sh...@github.com>
Date: 2016-01-04T07:13:01Z
json parser enhancements
----
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by chinmaykolhatkar <gi...@git.apache.org>.
Github user chinmaykolhatkar commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49314050
--- Diff: contrib/src/main/java/com/datatorrent/contrib/parser/JsonParser.java ---
@@ -0,0 +1,187 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.hadoop.classification.InterfaceStability;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jsonschema.exceptions.ProcessingException;
+import com.github.fge.jsonschema.main.JsonSchema;
+import com.github.fge.jsonschema.main.JsonSchemaFactory;
+import com.github.fge.jsonschema.report.ProcessingMessage;
+import com.github.fge.jsonschema.report.ProcessingReport;
+import com.github.fge.jsonschema.util.JsonLoader;
+
+import com.datatorrent.api.AutoMetric;
+import com.datatorrent.api.Context.OperatorContext;
+import com.datatorrent.api.DefaultOutputPort;
+import com.datatorrent.lib.parser.Parser;
+import com.datatorrent.lib.util.KeyValPair;
+import com.datatorrent.netlet.util.DTThrowable;
+
+/**
+ * Operator that parses a json string tuple against a specified json schema and
+ * emits JSONObject on one port POJO on other port and tuples that could not be
+ * parsed on error port.<br>
+ * Schema is specified in a json format as per http://json-schema.org/ <br>
+ * Example for the schema can be seen here http://json-schema.org/example1.html <br>
+ * User can choose to skip validations by not specifying the schema at all. <br>
+ * <br>
+ * <b>Properties</b> <br>
+ * <b>jsonSchema</b>:schema as a string<br>
+ * <b>clazz</b>:Pojo class <br>
+ * <b>Ports</b> <br>
+ * <b>in</b>:input tuple as a String. Each tuple represents a json string<br>
+ * <b>parsedOutput</b>:tuples that are validated against the schema are emitted
+ * as JSONObject on this port<br>
+ * <b>out</b>:tuples that are validated against the schema are emitted as pojo
+ * on this port<br>
+ * <b>err</b>:tuples that do not confine to schema are emitted on this port as
+ * KeyValPair<String,String><br>
+ * Key being the tuple and Val being the reason.
+ *
+ *
+ * @displayName JsonParser
+ * @category Parsers
+ * @tags json pojo parser
+ * @since 3.2.0
+ */
+@InterfaceStability.Evolving
+public class JsonParser extends Parser<String, KeyValPair<String, String>>
+{
+
+ /**
+ * Contents of the schema.Schema is specified as per http://json-schema.org/
+ */
+ private String jsonSchema;
+ private transient JsonSchema schema;
+ private transient ObjectMapper objMapper;
+ /**
+ * output port to emit validate records as JSONObject
+ */
+ public transient DefaultOutputPort<JSONObject> parsedOutput = new DefaultOutputPort<JSONObject>();
+ /**
+ * metric to keep count of number of tuples emitted on {@link #parsedOutput}
+ * port
+ */
+ @AutoMetric
+ long parsedOutputCount;
+
+ @Override
+ public void beginWindow(long windowId)
+ {
+ super.beginWindow(windowId);
+ parsedOutputCount = 0;
+ }
+
+ @Override
+ public void setup(OperatorContext context)
+ {
+ try {
+ if (jsonSchema != null) {
+ JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
+ JsonNode schemaNode = JsonLoader.fromString(jsonSchema);
+ schema = factory.getJsonSchema(schemaNode);
+ }
+ objMapper = new ObjectMapper();
+ } catch (ProcessingException | IOException e) {
+ DTThrowable.wrapIfChecked(e);
+ }
+ }
+
+ @Override
+ public void processTuple(String tuple)
+ {
+ try {
+ if (schema != null) {
+ ProcessingReport report = null;
+ JsonNode data = JsonLoader.fromString(tuple);
+ report = schema.validate(data);
+ if (report != null && !report.isSuccess()) {
+ Iterator<ProcessingMessage> iter = report.iterator();
+ StringBuilder s = new StringBuilder();
+ while (iter.hasNext()) {
+ ProcessingMessage pm = iter.next();
+ s.append(pm.asJson().get("instance").findValue("pointer")).append(":").append(pm.asJson().get("message"))
+ .append(",");
+ }
+ s.setLength(s.length() - 1);
+ errorTupleCount++;
+ err.emit(new KeyValPair<String, String>(tuple, s.toString()));
+ return;
+ }
+ }
+ if (parsedOutput.isConnected()) {
+ parsedOutput.emit(new JSONObject(tuple));
+ parsedOutputCount++;
+ }
+ if (out.isConnected()) {
+ out.emit(objMapper.readValue(tuple, clazz));
+ emittedObjectCount++;
+ }
+ } catch (JSONException | ProcessingException | IOException e) {
+ errorTupleCount++;
+ err.emit(new KeyValPair<String, String>(tuple, e.getMessage()));
+ logger.error("Failed to parse json tuple {}, Exception = {} ", tuple, e);
+ }
+ }
+
+ @Override
+ public Object convert(String tuple)
+ {
+ throw new UnsupportedOperationException("Not supported");
--- End diff --
Can you please return null here instead of throwing UnsupportedOperationException.
I see similar is done in XMLParser.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by shubham-pathak22 <gi...@git.apache.org>.
Github user shubham-pathak22 commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49314239
--- Diff: contrib/src/main/java/com/datatorrent/contrib/parser/JsonParser.java ---
@@ -0,0 +1,187 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.hadoop.classification.InterfaceStability;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jsonschema.exceptions.ProcessingException;
+import com.github.fge.jsonschema.main.JsonSchema;
+import com.github.fge.jsonschema.main.JsonSchemaFactory;
+import com.github.fge.jsonschema.report.ProcessingMessage;
+import com.github.fge.jsonschema.report.ProcessingReport;
+import com.github.fge.jsonschema.util.JsonLoader;
+
+import com.datatorrent.api.AutoMetric;
+import com.datatorrent.api.Context.OperatorContext;
+import com.datatorrent.api.DefaultOutputPort;
+import com.datatorrent.lib.parser.Parser;
+import com.datatorrent.lib.util.KeyValPair;
+import com.datatorrent.netlet.util.DTThrowable;
+
+/**
+ * Operator that parses a json string tuple against a specified json schema and
+ * emits JSONObject on one port POJO on other port and tuples that could not be
+ * parsed on error port.<br>
+ * Schema is specified in a json format as per http://json-schema.org/ <br>
+ * Example for the schema can be seen here http://json-schema.org/example1.html <br>
+ * User can choose to skip validations by not specifying the schema at all. <br>
+ * <br>
+ * <b>Properties</b> <br>
+ * <b>jsonSchema</b>:schema as a string<br>
+ * <b>clazz</b>:Pojo class <br>
+ * <b>Ports</b> <br>
+ * <b>in</b>:input tuple as a String. Each tuple represents a json string<br>
+ * <b>parsedOutput</b>:tuples that are validated against the schema are emitted
+ * as JSONObject on this port<br>
+ * <b>out</b>:tuples that are validated against the schema are emitted as pojo
+ * on this port<br>
+ * <b>err</b>:tuples that do not confine to schema are emitted on this port as
+ * KeyValPair<String,String><br>
+ * Key being the tuple and Val being the reason.
+ *
+ *
+ * @displayName JsonParser
+ * @category Parsers
+ * @tags json pojo parser
+ * @since 3.2.0
+ */
+@InterfaceStability.Evolving
+public class JsonParser extends Parser<String, KeyValPair<String, String>>
+{
+
+ /**
+ * Contents of the schema.Schema is specified as per http://json-schema.org/
+ */
+ private String jsonSchema;
+ private transient JsonSchema schema;
+ private transient ObjectMapper objMapper;
+ /**
+ * output port to emit validate records as JSONObject
+ */
+ public transient DefaultOutputPort<JSONObject> parsedOutput = new DefaultOutputPort<JSONObject>();
+ /**
+ * metric to keep count of number of tuples emitted on {@link #parsedOutput}
+ * port
+ */
+ @AutoMetric
+ long parsedOutputCount;
+
+ @Override
+ public void beginWindow(long windowId)
+ {
+ super.beginWindow(windowId);
+ parsedOutputCount = 0;
+ }
+
+ @Override
+ public void setup(OperatorContext context)
+ {
+ try {
+ if (jsonSchema != null) {
+ JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
+ JsonNode schemaNode = JsonLoader.fromString(jsonSchema);
+ schema = factory.getJsonSchema(schemaNode);
+ }
+ objMapper = new ObjectMapper();
+ } catch (ProcessingException | IOException e) {
+ DTThrowable.wrapIfChecked(e);
+ }
+ }
+
+ @Override
+ public void processTuple(String tuple)
+ {
+ try {
+ if (schema != null) {
--- End diff --
User may chose to not provide schema if he doesn't wish to perform any validations. In such cases, "jsonSchema" field can be null and hence the check.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by chinmaykolhatkar <gi...@git.apache.org>.
Github user chinmaykolhatkar commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49313426
--- Diff: contrib/src/test/java/com/datatorrent/contrib/parser/JsonParserTest.java ---
@@ -0,0 +1,340 @@
+/**
--- End diff --
Just a thought..
If I understand correctly, this test won't be run as all the contrib tests are skipped by default.
Can parser tests be allowed to be executed as they do not require external setup?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by chinmaykolhatkar <gi...@git.apache.org>.
Github user chinmaykolhatkar commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49312760
--- Diff: contrib/src/test/java/com/datatorrent/contrib/parser/JsonParserApplicationTest.java ---
@@ -0,0 +1,78 @@
+package com.datatorrent.contrib.parser;
+
+import java.io.IOException;
+
+import javax.validation.ConstraintViolationException;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.hadoop.conf.Configuration;
+
+import com.datatorrent.api.Context;
+import com.datatorrent.api.DAG;
+import com.datatorrent.api.DefaultOutputPort;
+import com.datatorrent.api.InputOperator;
+import com.datatorrent.api.LocalMode;
+import com.datatorrent.api.StreamingApplication;
+import com.datatorrent.common.util.BaseOperator;
+import com.datatorrent.contrib.parser.JsonParserTest.Product;
+import com.datatorrent.lib.appdata.schemas.SchemaUtils;
+import com.datatorrent.lib.io.ConsoleOutputOperator;
+
+public class JsonParserApplicationTest
+{
+
+ @Test
+ public void testApplication() throws IOException, Exception
+ {
+ try {
+ LocalMode lma = LocalMode.newInstance();
+ Configuration conf = new Configuration(false);
+ lma.prepareDAG(new JsonParserTest(), conf);
+ LocalMode.Controller lc = lma.getController();
+ lc.run(10000);// runs for 10 seconds and quits
+ } catch (ConstraintViolationException e) {
+ Assert.fail("constraint violations: " + e.getConstraintViolations());
+ }
+ }
+
+ public static class JsonParserTest implements StreamingApplication
+ {
+ @Override
+ public void populateDAG(DAG dag, Configuration conf)
+ {
+ JsonDataEmitterOperator input = dag.addOperator("data", new JsonDataEmitterOperator());
+ JsonParser parser = dag.addOperator("jsonparser", new JsonParser());
+ parser.setClazz(Product.class);
+ dag.getMeta(parser).getMeta(parser.out).getAttributes().put(Context.PortContext.TUPLE_CLASS, Product.class);
+ parser.setJsonSchema(SchemaUtils.jarResourceFileToString("json-parser-schema.json"));
+ ConsoleOutputOperator jsonObjectOp = dag.addOperator("jsonObjectOp", new ConsoleOutputOperator());
+ ConsoleOutputOperator pojoOp = dag.addOperator("pojoOp", new ConsoleOutputOperator());
+ jsonObjectOp.setDebug(true);
+ dag.addStream("input", input.output, parser.in);
+ dag.addStream("output", parser.parsedOutput, jsonObjectOp.input);
+ dag.addStream("pojo", parser.out, pojoOp.input);
+ }
+ }
+
+ public static class JsonDataEmitterOperator extends BaseOperator implements InputOperator
+ {
+
+ public static String jsonSample = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+
+ public final transient DefaultOutputPort<String> output = new DefaultOutputPort<String>();
+
+ @Override
+ public void emitTuples()
+ {
+
--- End diff --
Remove space.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by chinmaykolhatkar <gi...@git.apache.org>.
Github user chinmaykolhatkar commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r51689008
--- Diff: contrib/src/test/java/com/datatorrent/contrib/parser/JsonParserTest.java ---
@@ -0,0 +1,414 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.junit.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+
+import com.datatorrent.lib.appdata.schemas.SchemaUtils;
+import com.datatorrent.lib.testbench.CollectorTestSink;
+import com.datatorrent.lib.util.KeyValPair;
+
+public class JsonParserTest
+{
+ private static final String filename = "json-parser-schema.json";
+ CollectorTestSink<Object> error = new CollectorTestSink<Object>();
+ CollectorTestSink<Object> objectPort = new CollectorTestSink<Object>();
+ CollectorTestSink<Object> pojoPort = new CollectorTestSink<Object>();
+ JsonParser parser = new JsonParser();
+
+ @Rule
+ public Watcher watcher = new Watcher();
+
+ public class Watcher extends TestWatcher
+ {
+ @Override
+ protected void starting(Description description)
+ {
+ super.starting(description);
+ parser.err.setSink(error);
+ parser.parsedOutput.setSink(objectPort);
+ parser.out.setSink(pojoPort);
+ parser.setClazz(Product.class);
+ parser.setJsonSchema(SchemaUtils.jarResourceFileToString(filename));
+ parser.setup(null);
+ }
+
+ @Override
+ protected void finished(Description description)
+ {
+ super.finished(description);
+ error.clear();
+ objectPort.clear();
+ pojoPort.clear();
+ parser.teardown();
+ }
+ }
+
+ @Test
+ public void testValidInput() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void testEmptyInput() throws JSONException
+ {
+ parser.setSchema(null);
+ String tuple = "";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ }
+
+ @Test
+ public void testValidInputWithoutSchema() throws JSONException
+ {
+ parser.setSchema(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void testInvalidPrice() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ Assert.assertEquals("\"/price\":\"number is lower than the required minimum\"", errorKeyValPair.getValue());
+ }
+
+ @Test
+ public void testMultipleViolations() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"width\" : 8.0," + "\"height\": 9.5" + "},"
+ + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4" + "},"
+ + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ Assert.assertEquals(
+ "\"/dimensions\":\"missing required property(ies)\",\"/price\":\"number is lower than the required minimum\"",
+ errorKeyValPair.getValue());
+ }
+
+ @Test
+ public void testJsonSyntaxError() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"width\" : 8.0," + "\"height\": 9.5" + "}"
+ + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4" + "},"
+ + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ }
+
+ @Test
+ public void testValidInputPojoPortNotConnected() throws JSONException
+ {
+ parser.out.setSink(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ }
+
+ @Test
+ public void testValidInputParsedOutputPortNotConnected() throws JSONException
+ {
+ parser.parsedOutput.setSink(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void TestParserValidInputMetricVerification()
--- End diff --
Please keep the same format for method name. All the unit tests should start from test* and not Test*
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by tushargosavi <gi...@git.apache.org>.
Github user tushargosavi commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r51700413
--- Diff: contrib/src/main/java/com/datatorrent/contrib/parser/JsonParser.java ---
@@ -0,0 +1,241 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.hadoop.classification.InterfaceStability;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jsonschema.exceptions.ProcessingException;
+import com.github.fge.jsonschema.main.JsonSchema;
+import com.github.fge.jsonschema.main.JsonSchemaFactory;
+import com.github.fge.jsonschema.report.ProcessingMessage;
+import com.github.fge.jsonschema.report.ProcessingReport;
+import com.github.fge.jsonschema.util.JsonLoader;
+import com.google.common.annotations.VisibleForTesting;
+
+import com.datatorrent.api.AutoMetric;
+import com.datatorrent.api.Context.OperatorContext;
+import com.datatorrent.api.DefaultOutputPort;
+import com.datatorrent.lib.parser.Parser;
+import com.datatorrent.lib.util.KeyValPair;
+import com.datatorrent.netlet.util.DTThrowable;
+
+/**
+ * Operator that parses a json string tuple against a specified json schema and
+ * emits JSONObject on one port POJO on other port and tuples that could not be
+ * parsed on error port.<br>
+ * Schema is specified in a json format as per http://json-schema.org/ <br>
+ * Example for the schema can be seen here http://json-schema.org/example1.html <br>
+ * User can choose to skip validations by not specifying the schema at all. <br>
+ * <br>
+ * <b>Properties</b> <br>
+ * <b>jsonSchema</b>:schema as a string<br>
+ * <b>clazz</b>:Pojo class <br>
+ * <b>Ports</b> <br>
+ * <b>in</b>:input tuple as a String. Each tuple represents a json string<br>
+ * <b>parsedOutput</b>:tuples that are validated against the schema are emitted
+ * as JSONObject on this port<br>
+ * <b>out</b>:tuples that are validated against the schema are emitted as pojo
+ * on this port<br>
+ * <b>err</b>:tuples that do not confine to schema are emitted on this port as
+ * KeyValPair<String,String><br>
+ * Key being the tuple and Val being the reason.
+ *
+ *
+ * @displayName JsonParser
+ * @category Parsers
+ * @tags json pojo parser
+ * @since 3.2.0
+ */
+@InterfaceStability.Evolving
+public class JsonParser extends Parser<byte[], KeyValPair<String, String>>
+{
+
+ /**
+ * Contents of the schema.Schema is specified as per http://json-schema.org/
+ */
+ private String jsonSchema;
+ private transient JsonSchema schema;
+ private transient ObjectMapper objMapper;
+ /**
+ * output port to emit validate records as JSONObject
+ */
+ public transient DefaultOutputPort<JSONObject> parsedOutput = new DefaultOutputPort<JSONObject>();
+ /**
+ * metric to keep count of number of tuples emitted on {@link #parsedOutput}
+ * port
+ */
+ @AutoMetric
+ long parsedOutputCount;
+
+ @Override
+ public void beginWindow(long windowId)
+ {
+ super.beginWindow(windowId);
+ parsedOutputCount = 0;
+ }
+
+ @Override
+ public void setup(OperatorContext context)
+ {
+ try {
+ if (jsonSchema != null) {
+ JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
+ JsonNode schemaNode = JsonLoader.fromString(jsonSchema);
+ schema = factory.getJsonSchema(schemaNode);
+ }
+ objMapper = new ObjectMapper();
--- End diff --
By default object mapper will check if all fields specified in json are available in the class, if it does not find such mapping it will fail the parsing. you need to relax this condition by setting
```
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
```
This will allow users to specify pojo with less number of fields than what are present in json. This way user can only extract interested fields from json.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by tushargosavi <gi...@git.apache.org>.
Github user tushargosavi commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r51879732
--- Diff: contrib/src/main/java/com/datatorrent/contrib/parser/JsonParser.java ---
@@ -0,0 +1,241 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.hadoop.classification.InterfaceStability;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jsonschema.exceptions.ProcessingException;
+import com.github.fge.jsonschema.main.JsonSchema;
+import com.github.fge.jsonschema.main.JsonSchemaFactory;
+import com.github.fge.jsonschema.report.ProcessingMessage;
+import com.github.fge.jsonschema.report.ProcessingReport;
+import com.github.fge.jsonschema.util.JsonLoader;
+import com.google.common.annotations.VisibleForTesting;
+
+import com.datatorrent.api.AutoMetric;
+import com.datatorrent.api.Context.OperatorContext;
+import com.datatorrent.api.DefaultOutputPort;
+import com.datatorrent.lib.parser.Parser;
+import com.datatorrent.lib.util.KeyValPair;
+import com.datatorrent.netlet.util.DTThrowable;
+
+/**
+ * Operator that parses a json string tuple against a specified json schema and
+ * emits JSONObject on one port POJO on other port and tuples that could not be
+ * parsed on error port.<br>
+ * Schema is specified in a json format as per http://json-schema.org/ <br>
+ * Example for the schema can be seen here http://json-schema.org/example1.html <br>
+ * User can choose to skip validations by not specifying the schema at all. <br>
+ * <br>
+ * <b>Properties</b> <br>
+ * <b>jsonSchema</b>:schema as a string<br>
+ * <b>clazz</b>:Pojo class <br>
+ * <b>Ports</b> <br>
+ * <b>in</b>:input tuple as a String. Each tuple represents a json string<br>
+ * <b>parsedOutput</b>:tuples that are validated against the schema are emitted
+ * as JSONObject on this port<br>
+ * <b>out</b>:tuples that are validated against the schema are emitted as pojo
+ * on this port<br>
+ * <b>err</b>:tuples that do not confine to schema are emitted on this port as
+ * KeyValPair<String,String><br>
+ * Key being the tuple and Val being the reason.
+ *
+ *
+ * @displayName JsonParser
+ * @category Parsers
+ * @tags json pojo parser
+ * @since 3.2.0
+ */
+@InterfaceStability.Evolving
+public class JsonParser extends Parser<byte[], KeyValPair<String, String>>
+{
+
+ /**
+ * Contents of the schema.Schema is specified as per http://json-schema.org/
+ */
+ private String jsonSchema;
+ private transient JsonSchema schema;
+ private transient ObjectMapper objMapper;
+ /**
+ * output port to emit validate records as JSONObject
+ */
+ public transient DefaultOutputPort<JSONObject> parsedOutput = new DefaultOutputPort<JSONObject>();
+ /**
+ * metric to keep count of number of tuples emitted on {@link #parsedOutput}
+ * port
+ */
+ @AutoMetric
+ long parsedOutputCount;
+
+ @Override
+ public void beginWindow(long windowId)
+ {
+ super.beginWindow(windowId);
+ parsedOutputCount = 0;
+ }
+
+ @Override
+ public void setup(OperatorContext context)
+ {
+ try {
+ if (jsonSchema != null) {
+ JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
+ JsonNode schemaNode = JsonLoader.fromString(jsonSchema);
+ schema = factory.getJsonSchema(schemaNode);
+ }
+ objMapper = new ObjectMapper();
--- End diff --
let me know once you have fixed it, I will merge after that.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by gauravgopi123 <gi...@git.apache.org>.
Github user gauravgopi123 commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49624871
--- Diff: contrib/src/test/java/com/datatorrent/contrib/parser/JsonParserTest.java ---
@@ -0,0 +1,356 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.junit.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+
+import com.datatorrent.lib.appdata.schemas.SchemaUtils;
+import com.datatorrent.lib.testbench.CollectorTestSink;
+import com.datatorrent.lib.util.KeyValPair;
+
+public class JsonParserTest
+{
+ private static final String filename = "json-parser-schema.json";
+ CollectorTestSink<Object> error = new CollectorTestSink<Object>();
+ CollectorTestSink<Object> objectPort = new CollectorTestSink<Object>();
+ CollectorTestSink<Object> pojoPort = new CollectorTestSink<Object>();
+ JsonParser parser = new JsonParser();
+
+ @Rule
+ public Watcher watcher = new Watcher();
+
+ public class Watcher extends TestWatcher
+ {
+ @Override
+ protected void starting(Description description)
+ {
+ super.starting(description);
+ parser.err.setSink(error);
+ parser.parsedOutput.setSink(objectPort);
+ parser.out.setSink(pojoPort);
+ parser.setClazz(Product.class);
+ parser.setJsonSchema(SchemaUtils.jarResourceFileToString(filename));
+ parser.setup(null);
+ }
+
+ @Override
+ protected void finished(Description description)
+ {
+ super.finished(description);
+ error.clear();
+ objectPort.clear();
+ pojoPort.clear();
+ }
+ }
+
+ @Test
+ public void testValidInput() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void testValidInputWithoutSchema() throws JSONException
+ {
+ parser.setJsonSchema(null);
+ parser.setup(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void testInvalidPrice() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ Assert.assertEquals("\"/price\":\"number is lower than the required minimum\"", errorKeyValPair.getValue());
+ }
+
+ @Test
+ public void testMultipleViolations() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"width\" : 8.0," + "\"height\": 9.5" + "},"
+ + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4" + "},"
+ + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ Assert.assertEquals(
+ "\"/dimensions\":\"missing required property(ies)\",\"/price\":\"number is lower than the required minimum\"",
+ errorKeyValPair.getValue());
+ }
+
+ @Test
+ public void testJsonSyntaxError() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"width\" : 8.0," + "\"height\": 9.5" + "}"
+ + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4" + "},"
+ + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ }
+
+ @Test
+ public void testValidInputPojoPortNotConnected() throws JSONException
+ {
+ parser.out.setSink(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ }
+
+ @Test
+ public void testValidInputParsedOutputPortNotConnected() throws JSONException
+ {
+ parser.parsedOutput.setSink(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void TestParserValidInputMetricVerification()
+ {
+ Assert.assertEquals(0, parser.parsedOutputCount);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(1, parser.parsedOutputCount);
+ }
+
+ @Test
+ public void TestParserInvalidInputMetricVerification()
+ {
+ Assert.assertEquals(0, parser.parsedOutputCount);
+ String tuple = "{" + "\"id\": 2" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(0, parser.parsedOutputCount);
+ }
+
+ @Test
+ public void TestParserMetricResetVerification()
+ {
+ Assert.assertEquals(0, parser.parsedOutputCount);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
--- End diff --
how is this process happening before beginWindow() call???
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by chinmaykolhatkar <gi...@git.apache.org>.
Github user chinmaykolhatkar commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49312748
--- Diff: contrib/src/test/java/com/datatorrent/contrib/parser/JsonParserApplicationTest.java ---
@@ -0,0 +1,78 @@
+package com.datatorrent.contrib.parser;
--- End diff --
Can you please run mvn apache-rat:check verify -Dlicense.skip=false before uploading the changes?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by shubham-pathak22 <gi...@git.apache.org>.
Github user shubham-pathak22 commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r51849108
--- Diff: contrib/src/main/java/com/datatorrent/contrib/parser/JsonParser.java ---
@@ -0,0 +1,241 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.hadoop.classification.InterfaceStability;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jsonschema.exceptions.ProcessingException;
+import com.github.fge.jsonschema.main.JsonSchema;
+import com.github.fge.jsonschema.main.JsonSchemaFactory;
+import com.github.fge.jsonschema.report.ProcessingMessage;
+import com.github.fge.jsonschema.report.ProcessingReport;
+import com.github.fge.jsonschema.util.JsonLoader;
+import com.google.common.annotations.VisibleForTesting;
+
+import com.datatorrent.api.AutoMetric;
+import com.datatorrent.api.Context.OperatorContext;
+import com.datatorrent.api.DefaultOutputPort;
+import com.datatorrent.lib.parser.Parser;
+import com.datatorrent.lib.util.KeyValPair;
+import com.datatorrent.netlet.util.DTThrowable;
+
+/**
+ * Operator that parses a json string tuple against a specified json schema and
+ * emits JSONObject on one port POJO on other port and tuples that could not be
+ * parsed on error port.<br>
+ * Schema is specified in a json format as per http://json-schema.org/ <br>
+ * Example for the schema can be seen here http://json-schema.org/example1.html <br>
+ * User can choose to skip validations by not specifying the schema at all. <br>
+ * <br>
+ * <b>Properties</b> <br>
+ * <b>jsonSchema</b>:schema as a string<br>
+ * <b>clazz</b>:Pojo class <br>
+ * <b>Ports</b> <br>
+ * <b>in</b>:input tuple as a String. Each tuple represents a json string<br>
+ * <b>parsedOutput</b>:tuples that are validated against the schema are emitted
+ * as JSONObject on this port<br>
+ * <b>out</b>:tuples that are validated against the schema are emitted as pojo
+ * on this port<br>
+ * <b>err</b>:tuples that do not confine to schema are emitted on this port as
+ * KeyValPair<String,String><br>
+ * Key being the tuple and Val being the reason.
+ *
+ *
+ * @displayName JsonParser
+ * @category Parsers
+ * @tags json pojo parser
+ * @since 3.2.0
+ */
+@InterfaceStability.Evolving
+public class JsonParser extends Parser<byte[], KeyValPair<String, String>>
+{
+
+ /**
+ * Contents of the schema.Schema is specified as per http://json-schema.org/
+ */
+ private String jsonSchema;
+ private transient JsonSchema schema;
+ private transient ObjectMapper objMapper;
+ /**
+ * output port to emit validate records as JSONObject
+ */
+ public transient DefaultOutputPort<JSONObject> parsedOutput = new DefaultOutputPort<JSONObject>();
+ /**
+ * metric to keep count of number of tuples emitted on {@link #parsedOutput}
+ * port
+ */
+ @AutoMetric
+ long parsedOutputCount;
+
+ @Override
+ public void beginWindow(long windowId)
+ {
+ super.beginWindow(windowId);
+ parsedOutputCount = 0;
+ }
+
+ @Override
+ public void setup(OperatorContext context)
+ {
+ try {
+ if (jsonSchema != null) {
+ JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
+ JsonNode schemaNode = JsonLoader.fromString(jsonSchema);
+ schema = factory.getJsonSchema(schemaNode);
+ }
+ objMapper = new ObjectMapper();
--- End diff --
Good catch !. Will do the same and add a test case too.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by chinmaykolhatkar <gi...@git.apache.org>.
Github user chinmaykolhatkar commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r51689049
--- Diff: contrib/src/test/java/com/datatorrent/contrib/parser/JsonParserTest.java ---
@@ -0,0 +1,414 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.junit.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+
+import com.datatorrent.lib.appdata.schemas.SchemaUtils;
+import com.datatorrent.lib.testbench.CollectorTestSink;
+import com.datatorrent.lib.util.KeyValPair;
+
+public class JsonParserTest
+{
+ private static final String filename = "json-parser-schema.json";
+ CollectorTestSink<Object> error = new CollectorTestSink<Object>();
+ CollectorTestSink<Object> objectPort = new CollectorTestSink<Object>();
+ CollectorTestSink<Object> pojoPort = new CollectorTestSink<Object>();
+ JsonParser parser = new JsonParser();
+
+ @Rule
+ public Watcher watcher = new Watcher();
+
+ public class Watcher extends TestWatcher
+ {
+ @Override
+ protected void starting(Description description)
+ {
+ super.starting(description);
+ parser.err.setSink(error);
+ parser.parsedOutput.setSink(objectPort);
+ parser.out.setSink(pojoPort);
+ parser.setClazz(Product.class);
+ parser.setJsonSchema(SchemaUtils.jarResourceFileToString(filename));
+ parser.setup(null);
+ }
+
+ @Override
+ protected void finished(Description description)
+ {
+ super.finished(description);
+ error.clear();
+ objectPort.clear();
+ pojoPort.clear();
+ parser.teardown();
+ }
+ }
+
+ @Test
+ public void testValidInput() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void testEmptyInput() throws JSONException
+ {
+ parser.setSchema(null);
+ String tuple = "";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ }
+
+ @Test
+ public void testValidInputWithoutSchema() throws JSONException
+ {
+ parser.setSchema(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void testInvalidPrice() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ Assert.assertEquals("\"/price\":\"number is lower than the required minimum\"", errorKeyValPair.getValue());
+ }
+
+ @Test
+ public void testMultipleViolations() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"width\" : 8.0," + "\"height\": 9.5" + "},"
+ + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4" + "},"
+ + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ Assert.assertEquals(
+ "\"/dimensions\":\"missing required property(ies)\",\"/price\":\"number is lower than the required minimum\"",
+ errorKeyValPair.getValue());
+ }
+
+ @Test
+ public void testJsonSyntaxError() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"width\" : 8.0," + "\"height\": 9.5" + "}"
+ + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4" + "},"
+ + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ }
+
+ @Test
+ public void testValidInputPojoPortNotConnected() throws JSONException
+ {
+ parser.out.setSink(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ }
+
+ @Test
+ public void testValidInputParsedOutputPortNotConnected() throws JSONException
+ {
+ parser.parsedOutput.setSink(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void TestParserValidInputMetricVerification()
+ {
+ parser.beginWindow(0);
+ Assert.assertEquals(0, parser.parsedOutputCount);
+ Assert.assertEquals(0, parser.getIncomingTuplesCount());
+ Assert.assertEquals(0, parser.getErrorTupleCount());
+ Assert.assertEquals(0, parser.getEmittedObjectCount());
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(1, parser.parsedOutputCount);
+ Assert.assertEquals(1, parser.getIncomingTuplesCount());
+ Assert.assertEquals(0, parser.getErrorTupleCount());
+ Assert.assertEquals(1, parser.getEmittedObjectCount());
+ }
+
+ @Test
+ public void TestParserInvalidInputMetricVerification()
+ {
+ parser.beginWindow(0);
+ Assert.assertEquals(0, parser.parsedOutputCount);
+ Assert.assertEquals(0, parser.getIncomingTuplesCount());
+ Assert.assertEquals(0, parser.getErrorTupleCount());
+ Assert.assertEquals(0, parser.getEmittedObjectCount());
+ String tuple = "{" + "\"id\": 2" + "}";
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(0, parser.parsedOutputCount);
+ Assert.assertEquals(1, parser.getIncomingTuplesCount());
+ Assert.assertEquals(1, parser.getErrorTupleCount());
+ Assert.assertEquals(0, parser.getEmittedObjectCount());
+ }
+
+ @Test
+ public void TestParserMetricResetVerification()
--- End diff --
Keep consistency in name of the test case.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by tushargosavi <gi...@git.apache.org>.
Github user tushargosavi commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r51699476
--- Diff: contrib/src/main/java/com/datatorrent/contrib/parser/JsonParser.java ---
@@ -0,0 +1,241 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.hadoop.classification.InterfaceStability;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jsonschema.exceptions.ProcessingException;
+import com.github.fge.jsonschema.main.JsonSchema;
+import com.github.fge.jsonschema.main.JsonSchemaFactory;
+import com.github.fge.jsonschema.report.ProcessingMessage;
+import com.github.fge.jsonschema.report.ProcessingReport;
+import com.github.fge.jsonschema.util.JsonLoader;
+import com.google.common.annotations.VisibleForTesting;
+
+import com.datatorrent.api.AutoMetric;
+import com.datatorrent.api.Context.OperatorContext;
+import com.datatorrent.api.DefaultOutputPort;
+import com.datatorrent.lib.parser.Parser;
+import com.datatorrent.lib.util.KeyValPair;
+import com.datatorrent.netlet.util.DTThrowable;
+
+/**
+ * Operator that parses a json string tuple against a specified json schema and
+ * emits JSONObject on one port POJO on other port and tuples that could not be
+ * parsed on error port.<br>
+ * Schema is specified in a json format as per http://json-schema.org/ <br>
+ * Example for the schema can be seen here http://json-schema.org/example1.html <br>
+ * User can choose to skip validations by not specifying the schema at all. <br>
+ * <br>
+ * <b>Properties</b> <br>
+ * <b>jsonSchema</b>:schema as a string<br>
+ * <b>clazz</b>:Pojo class <br>
+ * <b>Ports</b> <br>
+ * <b>in</b>:input tuple as a String. Each tuple represents a json string<br>
+ * <b>parsedOutput</b>:tuples that are validated against the schema are emitted
+ * as JSONObject on this port<br>
+ * <b>out</b>:tuples that are validated against the schema are emitted as pojo
+ * on this port<br>
+ * <b>err</b>:tuples that do not confine to schema are emitted on this port as
+ * KeyValPair<String,String><br>
+ * Key being the tuple and Val being the reason.
+ *
+ *
+ * @displayName JsonParser
+ * @category Parsers
+ * @tags json pojo parser
+ * @since 3.2.0
+ */
+@InterfaceStability.Evolving
+public class JsonParser extends Parser<byte[], KeyValPair<String, String>>
+{
+
+ /**
+ * Contents of the schema.Schema is specified as per http://json-schema.org/
+ */
+ private String jsonSchema;
+ private transient JsonSchema schema;
+ private transient ObjectMapper objMapper;
+ /**
+ * output port to emit validate records as JSONObject
+ */
+ public transient DefaultOutputPort<JSONObject> parsedOutput = new DefaultOutputPort<JSONObject>();
+ /**
+ * metric to keep count of number of tuples emitted on {@link #parsedOutput}
+ * port
+ */
+ @AutoMetric
+ long parsedOutputCount;
+
+ @Override
+ public void beginWindow(long windowId)
+ {
+ super.beginWindow(windowId);
+ parsedOutputCount = 0;
+ }
+
+ @Override
+ public void setup(OperatorContext context)
+ {
+ try {
+ if (jsonSchema != null) {
+ JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
+ JsonNode schemaNode = JsonLoader.fromString(jsonSchema);
+ schema = factory.getJsonSchema(schemaNode);
+ }
+ objMapper = new ObjectMapper();
+ } catch (ProcessingException | IOException e) {
+ DTThrowable.wrapIfChecked(e);
+ }
+ }
+
+ @Override
+ public void processTuple(byte[] tuple)
+ {
+ if (tuple == null) {
+ if (err.isConnected()) {
+ err.emit(new KeyValPair<String, String>(null, "null tuple"));
+ }
+ errorTupleCount++;
+ return;
+ }
+ String incomingString = new String(tuple);
+ try {
+ if (schema != null) {
+ ProcessingReport report = null;
+ JsonNode data = JsonLoader.fromString(incomingString);
+ report = schema.validate(data);
+ if (report != null && !report.isSuccess()) {
+ Iterator<ProcessingMessage> iter = report.iterator();
+ StringBuilder s = new StringBuilder();
+ while (iter.hasNext()) {
+ ProcessingMessage pm = iter.next();
+ s.append(pm.asJson().get("instance").findValue("pointer")).append(":").append(pm.asJson().get("message"))
+ .append(",");
+ }
+ s.setLength(s.length() - 1);
+ errorTupleCount++;
+ err.emit(new KeyValPair<String, String>(incomingString, s.toString()));
+ return;
+ }
+ }
+ if (parsedOutput.isConnected()) {
+ parsedOutput.emit(new JSONObject(incomingString));
+ parsedOutputCount++;
+ }
+ if (out.isConnected()) {
+ out.emit(objMapper.readValue(tuple, clazz));
+ emittedObjectCount++;
+ }
+ } catch (JSONException | ProcessingException | IOException e) {
+ errorTupleCount++;
+ err.emit(new KeyValPair<String, String>(incomingString, e.getMessage()));
--- End diff --
emit only when error port is connected
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by tweise <gi...@git.apache.org>.
Github user tweise commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r48977268
--- Diff: library/pom.xml ---
@@ -315,7 +315,17 @@
<artifactId>joda-time</artifactId>
<version>2.9.1</version>
</dependency>
-
+ <dependency>
--- End diff --
As discussed on dev@, we don't want to add dependencies to malhar-library that aren't broadly applicable.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by shubham-pathak22 <gi...@git.apache.org>.
Github user shubham-pathak22 commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49314348
--- Diff: contrib/src/main/java/com/datatorrent/contrib/parser/JsonParser.java ---
@@ -0,0 +1,187 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.hadoop.classification.InterfaceStability;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jsonschema.exceptions.ProcessingException;
+import com.github.fge.jsonschema.main.JsonSchema;
+import com.github.fge.jsonschema.main.JsonSchemaFactory;
+import com.github.fge.jsonschema.report.ProcessingMessage;
+import com.github.fge.jsonschema.report.ProcessingReport;
+import com.github.fge.jsonschema.util.JsonLoader;
+
+import com.datatorrent.api.AutoMetric;
+import com.datatorrent.api.Context.OperatorContext;
+import com.datatorrent.api.DefaultOutputPort;
+import com.datatorrent.lib.parser.Parser;
+import com.datatorrent.lib.util.KeyValPair;
+import com.datatorrent.netlet.util.DTThrowable;
+
+/**
+ * Operator that parses a json string tuple against a specified json schema and
+ * emits JSONObject on one port POJO on other port and tuples that could not be
+ * parsed on error port.<br>
+ * Schema is specified in a json format as per http://json-schema.org/ <br>
+ * Example for the schema can be seen here http://json-schema.org/example1.html <br>
+ * User can choose to skip validations by not specifying the schema at all. <br>
+ * <br>
+ * <b>Properties</b> <br>
+ * <b>jsonSchema</b>:schema as a string<br>
+ * <b>clazz</b>:Pojo class <br>
+ * <b>Ports</b> <br>
+ * <b>in</b>:input tuple as a String. Each tuple represents a json string<br>
+ * <b>parsedOutput</b>:tuples that are validated against the schema are emitted
+ * as JSONObject on this port<br>
+ * <b>out</b>:tuples that are validated against the schema are emitted as pojo
+ * on this port<br>
+ * <b>err</b>:tuples that do not confine to schema are emitted on this port as
+ * KeyValPair<String,String><br>
+ * Key being the tuple and Val being the reason.
+ *
+ *
+ * @displayName JsonParser
+ * @category Parsers
+ * @tags json pojo parser
+ * @since 3.2.0
+ */
+@InterfaceStability.Evolving
+public class JsonParser extends Parser<String, KeyValPair<String, String>>
+{
+
+ /**
+ * Contents of the schema.Schema is specified as per http://json-schema.org/
+ */
+ private String jsonSchema;
+ private transient JsonSchema schema;
+ private transient ObjectMapper objMapper;
+ /**
+ * output port to emit validate records as JSONObject
+ */
+ public transient DefaultOutputPort<JSONObject> parsedOutput = new DefaultOutputPort<JSONObject>();
+ /**
+ * metric to keep count of number of tuples emitted on {@link #parsedOutput}
+ * port
+ */
+ @AutoMetric
+ long parsedOutputCount;
+
+ @Override
+ public void beginWindow(long windowId)
+ {
+ super.beginWindow(windowId);
+ parsedOutputCount = 0;
+ }
+
+ @Override
+ public void setup(OperatorContext context)
+ {
+ try {
+ if (jsonSchema != null) {
+ JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
+ JsonNode schemaNode = JsonLoader.fromString(jsonSchema);
+ schema = factory.getJsonSchema(schemaNode);
+ }
+ objMapper = new ObjectMapper();
+ } catch (ProcessingException | IOException e) {
+ DTThrowable.wrapIfChecked(e);
+ }
+ }
+
+ @Override
+ public void processTuple(String tuple)
+ {
+ try {
+ if (schema != null) {
+ ProcessingReport report = null;
+ JsonNode data = JsonLoader.fromString(tuple);
+ report = schema.validate(data);
+ if (report != null && !report.isSuccess()) {
+ Iterator<ProcessingMessage> iter = report.iterator();
+ StringBuilder s = new StringBuilder();
+ while (iter.hasNext()) {
+ ProcessingMessage pm = iter.next();
+ s.append(pm.asJson().get("instance").findValue("pointer")).append(":").append(pm.asJson().get("message"))
+ .append(",");
+ }
+ s.setLength(s.length() - 1);
+ errorTupleCount++;
+ err.emit(new KeyValPair<String, String>(tuple, s.toString()));
+ return;
+ }
+ }
+ if (parsedOutput.isConnected()) {
+ parsedOutput.emit(new JSONObject(tuple));
+ parsedOutputCount++;
+ }
+ if (out.isConnected()) {
+ out.emit(objMapper.readValue(tuple, clazz));
+ emittedObjectCount++;
+ }
+ } catch (JSONException | ProcessingException | IOException e) {
+ errorTupleCount++;
+ err.emit(new KeyValPair<String, String>(tuple, e.getMessage()));
+ logger.error("Failed to parse json tuple {}, Exception = {} ", tuple, e);
+ }
+ }
+
+ @Override
+ public Object convert(String tuple)
+ {
+ throw new UnsupportedOperationException("Not supported");
--- End diff --
throwing UnsupportedOperationException is better approach
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by asfgit <gi...@git.apache.org>.
Github user asfgit closed the pull request at:
https://github.com/apache/incubator-apex-malhar/pull/163
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by shubham-pathak22 <gi...@git.apache.org>.
Github user shubham-pathak22 commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49313488
--- Diff: contrib/src/test/java/com/datatorrent/contrib/parser/JsonParserApplicationTest.java ---
@@ -0,0 +1,78 @@
+package com.datatorrent.contrib.parser;
--- End diff --
Sure.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by chinmaykolhatkar <gi...@git.apache.org>.
Github user chinmaykolhatkar commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49314169
--- Diff: contrib/src/main/java/com/datatorrent/contrib/parser/JsonParser.java ---
@@ -0,0 +1,187 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.hadoop.classification.InterfaceStability;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jsonschema.exceptions.ProcessingException;
+import com.github.fge.jsonschema.main.JsonSchema;
+import com.github.fge.jsonschema.main.JsonSchemaFactory;
+import com.github.fge.jsonschema.report.ProcessingMessage;
+import com.github.fge.jsonschema.report.ProcessingReport;
+import com.github.fge.jsonschema.util.JsonLoader;
+
+import com.datatorrent.api.AutoMetric;
+import com.datatorrent.api.Context.OperatorContext;
+import com.datatorrent.api.DefaultOutputPort;
+import com.datatorrent.lib.parser.Parser;
+import com.datatorrent.lib.util.KeyValPair;
+import com.datatorrent.netlet.util.DTThrowable;
+
+/**
+ * Operator that parses a json string tuple against a specified json schema and
+ * emits JSONObject on one port POJO on other port and tuples that could not be
+ * parsed on error port.<br>
+ * Schema is specified in a json format as per http://json-schema.org/ <br>
+ * Example for the schema can be seen here http://json-schema.org/example1.html <br>
+ * User can choose to skip validations by not specifying the schema at all. <br>
+ * <br>
+ * <b>Properties</b> <br>
+ * <b>jsonSchema</b>:schema as a string<br>
+ * <b>clazz</b>:Pojo class <br>
+ * <b>Ports</b> <br>
+ * <b>in</b>:input tuple as a String. Each tuple represents a json string<br>
+ * <b>parsedOutput</b>:tuples that are validated against the schema are emitted
+ * as JSONObject on this port<br>
+ * <b>out</b>:tuples that are validated against the schema are emitted as pojo
+ * on this port<br>
+ * <b>err</b>:tuples that do not confine to schema are emitted on this port as
+ * KeyValPair<String,String><br>
+ * Key being the tuple and Val being the reason.
+ *
+ *
+ * @displayName JsonParser
+ * @category Parsers
+ * @tags json pojo parser
+ * @since 3.2.0
+ */
+@InterfaceStability.Evolving
+public class JsonParser extends Parser<String, KeyValPair<String, String>>
+{
+
+ /**
+ * Contents of the schema.Schema is specified as per http://json-schema.org/
+ */
+ private String jsonSchema;
+ private transient JsonSchema schema;
+ private transient ObjectMapper objMapper;
+ /**
+ * output port to emit validate records as JSONObject
+ */
+ public transient DefaultOutputPort<JSONObject> parsedOutput = new DefaultOutputPort<JSONObject>();
+ /**
+ * metric to keep count of number of tuples emitted on {@link #parsedOutput}
+ * port
+ */
+ @AutoMetric
+ long parsedOutputCount;
+
+ @Override
+ public void beginWindow(long windowId)
+ {
+ super.beginWindow(windowId);
+ parsedOutputCount = 0;
+ }
+
+ @Override
+ public void setup(OperatorContext context)
+ {
+ try {
+ if (jsonSchema != null) {
+ JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
+ JsonNode schemaNode = JsonLoader.fromString(jsonSchema);
+ schema = factory.getJsonSchema(schemaNode);
+ }
+ objMapper = new ObjectMapper();
+ } catch (ProcessingException | IOException e) {
+ DTThrowable.wrapIfChecked(e);
+ }
+ }
+
+ @Override
+ public void processTuple(String tuple)
+ {
+ try {
+ if (schema != null) {
+ ProcessingReport report = null;
+ JsonNode data = JsonLoader.fromString(tuple);
+ report = schema.validate(data);
+ if (report != null && !report.isSuccess()) {
+ Iterator<ProcessingMessage> iter = report.iterator();
+ StringBuilder s = new StringBuilder();
+ while (iter.hasNext()) {
+ ProcessingMessage pm = iter.next();
+ s.append(pm.asJson().get("instance").findValue("pointer")).append(":").append(pm.asJson().get("message"))
+ .append(",");
+ }
+ s.setLength(s.length() - 1);
+ errorTupleCount++;
+ err.emit(new KeyValPair<String, String>(tuple, s.toString()));
+ return;
+ }
+ }
+ if (parsedOutput.isConnected()) {
+ parsedOutput.emit(new JSONObject(tuple));
+ parsedOutputCount++;
+ }
+ if (out.isConnected()) {
+ out.emit(objMapper.readValue(tuple, clazz));
+ emittedObjectCount++;
+ }
+ } catch (JSONException | ProcessingException | IOException e) {
+ errorTupleCount++;
+ err.emit(new KeyValPair<String, String>(tuple, e.getMessage()));
+ logger.error("Failed to parse json tuple {}, Exception = {} ", tuple, e);
+ }
+ }
+
+ @Override
+ public Object convert(String tuple)
+ {
+ throw new UnsupportedOperationException("Not supported");
+ }
+
+ @Override
+ public KeyValPair<String, String> processErrorTuple(String input)
+ {
+ throw new UnsupportedOperationException("Not supported");
--- End diff --
Again, can you please return null here and log it, instead of throwing exception. This call (if I understand) correctly is coming from super class. If tomorrow super class changes, this should not get impacted.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by chinmaykolhatkar <gi...@git.apache.org>.
Github user chinmaykolhatkar commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49313518
--- Diff: contrib/src/main/java/com/datatorrent/contrib/parser/JsonParser.java ---
@@ -0,0 +1,187 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.hadoop.classification.InterfaceStability;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jsonschema.exceptions.ProcessingException;
+import com.github.fge.jsonschema.main.JsonSchema;
+import com.github.fge.jsonschema.main.JsonSchemaFactory;
+import com.github.fge.jsonschema.report.ProcessingMessage;
+import com.github.fge.jsonschema.report.ProcessingReport;
+import com.github.fge.jsonschema.util.JsonLoader;
+
+import com.datatorrent.api.AutoMetric;
+import com.datatorrent.api.Context.OperatorContext;
+import com.datatorrent.api.DefaultOutputPort;
+import com.datatorrent.lib.parser.Parser;
+import com.datatorrent.lib.util.KeyValPair;
+import com.datatorrent.netlet.util.DTThrowable;
+
+/**
+ * Operator that parses a json string tuple against a specified json schema and
+ * emits JSONObject on one port POJO on other port and tuples that could not be
+ * parsed on error port.<br>
+ * Schema is specified in a json format as per http://json-schema.org/ <br>
+ * Example for the schema can be seen here http://json-schema.org/example1.html <br>
+ * User can choose to skip validations by not specifying the schema at all. <br>
+ * <br>
+ * <b>Properties</b> <br>
+ * <b>jsonSchema</b>:schema as a string<br>
+ * <b>clazz</b>:Pojo class <br>
+ * <b>Ports</b> <br>
+ * <b>in</b>:input tuple as a String. Each tuple represents a json string<br>
+ * <b>parsedOutput</b>:tuples that are validated against the schema are emitted
+ * as JSONObject on this port<br>
+ * <b>out</b>:tuples that are validated against the schema are emitted as pojo
+ * on this port<br>
+ * <b>err</b>:tuples that do not confine to schema are emitted on this port as
+ * KeyValPair<String,String><br>
+ * Key being the tuple and Val being the reason.
+ *
+ *
+ * @displayName JsonParser
+ * @category Parsers
+ * @tags json pojo parser
+ * @since 3.2.0
+ */
+@InterfaceStability.Evolving
+public class JsonParser extends Parser<String, KeyValPair<String, String>>
+{
+
+ /**
+ * Contents of the schema.Schema is specified as per http://json-schema.org/
+ */
+ private String jsonSchema;
+ private transient JsonSchema schema;
+ private transient ObjectMapper objMapper;
+ /**
+ * output port to emit validate records as JSONObject
+ */
+ public transient DefaultOutputPort<JSONObject> parsedOutput = new DefaultOutputPort<JSONObject>();
+ /**
+ * metric to keep count of number of tuples emitted on {@link #parsedOutput}
+ * port
+ */
+ @AutoMetric
+ long parsedOutputCount;
+
+ @Override
+ public void beginWindow(long windowId)
+ {
+ super.beginWindow(windowId);
+ parsedOutputCount = 0;
+ }
+
+ @Override
+ public void setup(OperatorContext context)
+ {
+ try {
+ if (jsonSchema != null) {
+ JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
+ JsonNode schemaNode = JsonLoader.fromString(jsonSchema);
+ schema = factory.getJsonSchema(schemaNode);
+ }
+ objMapper = new ObjectMapper();
+ } catch (ProcessingException | IOException e) {
+ DTThrowable.wrapIfChecked(e);
+ }
+ }
+
+ @Override
+ public void processTuple(String tuple)
+ {
+ try {
+ if (schema != null) {
+ ProcessingReport report = null;
+ JsonNode data = JsonLoader.fromString(tuple);
+ report = schema.validate(data);
+ if (report != null && !report.isSuccess()) {
+ Iterator<ProcessingMessage> iter = report.iterator();
+ StringBuilder s = new StringBuilder();
+ while (iter.hasNext()) {
+ ProcessingMessage pm = iter.next();
+ s.append(pm.asJson().get("instance").findValue("pointer")).append(":").append(pm.asJson().get("message"))
+ .append(",");
+ }
+ s.setLength(s.length() - 1);
+ errorTupleCount++;
+ err.emit(new KeyValPair<String, String>(tuple, s.toString()));
+ return;
+ }
+ }
+ if (parsedOutput.isConnected()) {
+ parsedOutput.emit(new JSONObject(tuple));
+ parsedOutputCount++;
+ }
+ if (out.isConnected()) {
+ out.emit(objMapper.readValue(tuple, clazz));
+ emittedObjectCount++;
+ }
+ } catch (JSONException | ProcessingException | IOException e) {
+ errorTupleCount++;
+ err.emit(new KeyValPair<String, String>(tuple, e.getMessage()));
+ logger.error("Failed to parse json tuple {}, Exception = {} ", tuple, e);
+ }
+ }
+
+ @Override
+ public Object convert(String tuple)
+ {
+ throw new UnsupportedOperationException("Not supported");
+ }
+
+ @Override
+ public KeyValPair<String, String> processErrorTuple(String input)
+ {
+ throw new UnsupportedOperationException("Not supported");
+ }
+
+ /**
+ *
--- End diff --
Description missing for getJsonSchema function.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by shubham-pathak22 <gi...@git.apache.org>.
Github user shubham-pathak22 commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49314262
--- Diff: contrib/src/main/java/com/datatorrent/contrib/parser/JsonParser.java ---
@@ -0,0 +1,187 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.hadoop.classification.InterfaceStability;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jsonschema.exceptions.ProcessingException;
+import com.github.fge.jsonschema.main.JsonSchema;
+import com.github.fge.jsonschema.main.JsonSchemaFactory;
+import com.github.fge.jsonschema.report.ProcessingMessage;
+import com.github.fge.jsonschema.report.ProcessingReport;
+import com.github.fge.jsonschema.util.JsonLoader;
+
+import com.datatorrent.api.AutoMetric;
+import com.datatorrent.api.Context.OperatorContext;
+import com.datatorrent.api.DefaultOutputPort;
+import com.datatorrent.lib.parser.Parser;
+import com.datatorrent.lib.util.KeyValPair;
+import com.datatorrent.netlet.util.DTThrowable;
+
+/**
+ * Operator that parses a json string tuple against a specified json schema and
+ * emits JSONObject on one port POJO on other port and tuples that could not be
+ * parsed on error port.<br>
+ * Schema is specified in a json format as per http://json-schema.org/ <br>
+ * Example for the schema can be seen here http://json-schema.org/example1.html <br>
+ * User can choose to skip validations by not specifying the schema at all. <br>
+ * <br>
+ * <b>Properties</b> <br>
+ * <b>jsonSchema</b>:schema as a string<br>
+ * <b>clazz</b>:Pojo class <br>
+ * <b>Ports</b> <br>
+ * <b>in</b>:input tuple as a String. Each tuple represents a json string<br>
+ * <b>parsedOutput</b>:tuples that are validated against the schema are emitted
+ * as JSONObject on this port<br>
+ * <b>out</b>:tuples that are validated against the schema are emitted as pojo
+ * on this port<br>
+ * <b>err</b>:tuples that do not confine to schema are emitted on this port as
+ * KeyValPair<String,String><br>
+ * Key being the tuple and Val being the reason.
+ *
+ *
+ * @displayName JsonParser
+ * @category Parsers
+ * @tags json pojo parser
+ * @since 3.2.0
+ */
+@InterfaceStability.Evolving
+public class JsonParser extends Parser<String, KeyValPair<String, String>>
+{
+
+ /**
+ * Contents of the schema.Schema is specified as per http://json-schema.org/
+ */
+ private String jsonSchema;
--- End diff --
jsonSchema can be null.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by gauravgopi123 <gi...@git.apache.org>.
Github user gauravgopi123 commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49624797
--- Diff: contrib/src/test/java/com/datatorrent/contrib/parser/JsonParserTest.java ---
@@ -0,0 +1,356 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.junit.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+
+import com.datatorrent.lib.appdata.schemas.SchemaUtils;
+import com.datatorrent.lib.testbench.CollectorTestSink;
+import com.datatorrent.lib.util.KeyValPair;
+
+public class JsonParserTest
+{
+ private static final String filename = "json-parser-schema.json";
+ CollectorTestSink<Object> error = new CollectorTestSink<Object>();
+ CollectorTestSink<Object> objectPort = new CollectorTestSink<Object>();
+ CollectorTestSink<Object> pojoPort = new CollectorTestSink<Object>();
+ JsonParser parser = new JsonParser();
+
+ @Rule
+ public Watcher watcher = new Watcher();
+
+ public class Watcher extends TestWatcher
+ {
+ @Override
+ protected void starting(Description description)
+ {
+ super.starting(description);
+ parser.err.setSink(error);
+ parser.parsedOutput.setSink(objectPort);
+ parser.out.setSink(pojoPort);
+ parser.setClazz(Product.class);
+ parser.setJsonSchema(SchemaUtils.jarResourceFileToString(filename));
+ parser.setup(null);
+ }
+
+ @Override
+ protected void finished(Description description)
+ {
+ super.finished(description);
+ error.clear();
+ objectPort.clear();
+ pojoPort.clear();
+ }
+ }
+
+ @Test
+ public void testValidInput() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void testValidInputWithoutSchema() throws JSONException
+ {
+ parser.setJsonSchema(null);
+ parser.setup(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void testInvalidPrice() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ Assert.assertEquals("\"/price\":\"number is lower than the required minimum\"", errorKeyValPair.getValue());
+ }
+
+ @Test
+ public void testMultipleViolations() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"width\" : 8.0," + "\"height\": 9.5" + "},"
+ + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4" + "},"
+ + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ Assert.assertEquals(
+ "\"/dimensions\":\"missing required property(ies)\",\"/price\":\"number is lower than the required minimum\"",
+ errorKeyValPair.getValue());
+ }
+
+ @Test
+ public void testJsonSyntaxError() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"width\" : 8.0," + "\"height\": 9.5" + "}"
+ + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4" + "},"
+ + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ }
+
+ @Test
+ public void testValidInputPojoPortNotConnected() throws JSONException
+ {
+ parser.out.setSink(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ }
+
+ @Test
+ public void testValidInputParsedOutputPortNotConnected() throws JSONException
+ {
+ parser.parsedOutput.setSink(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void TestParserValidInputMetricVerification()
+ {
+ Assert.assertEquals(0, parser.parsedOutputCount);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(1, parser.parsedOutputCount);
+ }
+
+ @Test
+ public void TestParserInvalidInputMetricVerification()
+ {
+ Assert.assertEquals(0, parser.parsedOutputCount);
+ String tuple = "{" + "\"id\": 2" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(0, parser.parsedOutputCount);
+ }
--- End diff --
I don't see beginWindow() and endWindow() call on parser in any of the above tests?
parser.teardown() has been removed all together. I suggested to move it to finished() function call of TestWatcher...
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by chinmaykolhatkar <gi...@git.apache.org>.
Github user chinmaykolhatkar commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49312703
--- Diff: contrib/src/test/java/com/datatorrent/contrib/parser/JsonParserApplicationTest.java ---
@@ -0,0 +1,78 @@
+package com.datatorrent.contrib.parser;
--- End diff --
License header.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by shubham-pathak22 <gi...@git.apache.org>.
Github user shubham-pathak22 commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r51831337
--- Diff: contrib/src/main/java/com/datatorrent/contrib/parser/JsonParser.java ---
@@ -0,0 +1,241 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.hadoop.classification.InterfaceStability;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jsonschema.exceptions.ProcessingException;
+import com.github.fge.jsonschema.main.JsonSchema;
+import com.github.fge.jsonschema.main.JsonSchemaFactory;
+import com.github.fge.jsonschema.report.ProcessingMessage;
+import com.github.fge.jsonschema.report.ProcessingReport;
+import com.github.fge.jsonschema.util.JsonLoader;
+import com.google.common.annotations.VisibleForTesting;
+
+import com.datatorrent.api.AutoMetric;
+import com.datatorrent.api.Context.OperatorContext;
+import com.datatorrent.api.DefaultOutputPort;
+import com.datatorrent.lib.parser.Parser;
+import com.datatorrent.lib.util.KeyValPair;
+import com.datatorrent.netlet.util.DTThrowable;
+
+/**
+ * Operator that parses a json string tuple against a specified json schema and
+ * emits JSONObject on one port POJO on other port and tuples that could not be
+ * parsed on error port.<br>
+ * Schema is specified in a json format as per http://json-schema.org/ <br>
+ * Example for the schema can be seen here http://json-schema.org/example1.html <br>
+ * User can choose to skip validations by not specifying the schema at all. <br>
+ * <br>
+ * <b>Properties</b> <br>
+ * <b>jsonSchema</b>:schema as a string<br>
+ * <b>clazz</b>:Pojo class <br>
+ * <b>Ports</b> <br>
+ * <b>in</b>:input tuple as a String. Each tuple represents a json string<br>
+ * <b>parsedOutput</b>:tuples that are validated against the schema are emitted
+ * as JSONObject on this port<br>
+ * <b>out</b>:tuples that are validated against the schema are emitted as pojo
+ * on this port<br>
+ * <b>err</b>:tuples that do not confine to schema are emitted on this port as
+ * KeyValPair<String,String><br>
+ * Key being the tuple and Val being the reason.
+ *
+ *
+ * @displayName JsonParser
+ * @category Parsers
+ * @tags json pojo parser
+ * @since 3.2.0
+ */
+@InterfaceStability.Evolving
+public class JsonParser extends Parser<byte[], KeyValPair<String, String>>
+{
+
+ /**
+ * Contents of the schema.Schema is specified as per http://json-schema.org/
+ */
+ private String jsonSchema;
+ private transient JsonSchema schema;
+ private transient ObjectMapper objMapper;
+ /**
+ * output port to emit validate records as JSONObject
+ */
+ public transient DefaultOutputPort<JSONObject> parsedOutput = new DefaultOutputPort<JSONObject>();
+ /**
+ * metric to keep count of number of tuples emitted on {@link #parsedOutput}
+ * port
+ */
+ @AutoMetric
+ long parsedOutputCount;
+
+ @Override
+ public void beginWindow(long windowId)
+ {
+ super.beginWindow(windowId);
+ parsedOutputCount = 0;
+ }
+
+ @Override
+ public void setup(OperatorContext context)
+ {
+ try {
+ if (jsonSchema != null) {
+ JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
+ JsonNode schemaNode = JsonLoader.fromString(jsonSchema);
+ schema = factory.getJsonSchema(schemaNode);
+ }
+ objMapper = new ObjectMapper();
+ } catch (ProcessingException | IOException e) {
+ DTThrowable.wrapIfChecked(e);
+ }
+ }
+
+ @Override
+ public void processTuple(byte[] tuple)
+ {
+ if (tuple == null) {
+ if (err.isConnected()) {
+ err.emit(new KeyValPair<String, String>(null, "null tuple"));
+ }
+ errorTupleCount++;
+ return;
+ }
+ String incomingString = new String(tuple);
+ try {
+ if (schema != null) {
--- End diff --
Agreed. But errorTupleCount must be incremented either ways. I will add the condition before err.emit is called.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by shubham-pathak22 <gi...@git.apache.org>.
Github user shubham-pathak22 commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49043715
--- Diff: library/pom.xml ---
@@ -315,7 +315,17 @@
<artifactId>joda-time</artifactId>
<version>2.9.1</version>
</dependency>
-
+ <dependency>
--- End diff --
I agree, but this case requires it. This is an enhancement to existing operator in malhar-library
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by chinmaykolhatkar <gi...@git.apache.org>.
Github user chinmaykolhatkar commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49313723
--- Diff: contrib/src/main/java/com/datatorrent/contrib/parser/JsonParser.java ---
@@ -0,0 +1,187 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.hadoop.classification.InterfaceStability;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jsonschema.exceptions.ProcessingException;
+import com.github.fge.jsonschema.main.JsonSchema;
+import com.github.fge.jsonschema.main.JsonSchemaFactory;
+import com.github.fge.jsonschema.report.ProcessingMessage;
+import com.github.fge.jsonschema.report.ProcessingReport;
+import com.github.fge.jsonschema.util.JsonLoader;
+
+import com.datatorrent.api.AutoMetric;
+import com.datatorrent.api.Context.OperatorContext;
+import com.datatorrent.api.DefaultOutputPort;
+import com.datatorrent.lib.parser.Parser;
+import com.datatorrent.lib.util.KeyValPair;
+import com.datatorrent.netlet.util.DTThrowable;
+
+/**
+ * Operator that parses a json string tuple against a specified json schema and
+ * emits JSONObject on one port POJO on other port and tuples that could not be
+ * parsed on error port.<br>
+ * Schema is specified in a json format as per http://json-schema.org/ <br>
+ * Example for the schema can be seen here http://json-schema.org/example1.html <br>
+ * User can choose to skip validations by not specifying the schema at all. <br>
+ * <br>
+ * <b>Properties</b> <br>
+ * <b>jsonSchema</b>:schema as a string<br>
+ * <b>clazz</b>:Pojo class <br>
+ * <b>Ports</b> <br>
+ * <b>in</b>:input tuple as a String. Each tuple represents a json string<br>
+ * <b>parsedOutput</b>:tuples that are validated against the schema are emitted
+ * as JSONObject on this port<br>
+ * <b>out</b>:tuples that are validated against the schema are emitted as pojo
+ * on this port<br>
+ * <b>err</b>:tuples that do not confine to schema are emitted on this port as
+ * KeyValPair<String,String><br>
+ * Key being the tuple and Val being the reason.
+ *
+ *
+ * @displayName JsonParser
+ * @category Parsers
+ * @tags json pojo parser
+ * @since 3.2.0
+ */
+@InterfaceStability.Evolving
+public class JsonParser extends Parser<String, KeyValPair<String, String>>
+{
+
+ /**
+ * Contents of the schema.Schema is specified as per http://json-schema.org/
+ */
+ private String jsonSchema;
+ private transient JsonSchema schema;
+ private transient ObjectMapper objMapper;
+ /**
+ * output port to emit validate records as JSONObject
+ */
+ public transient DefaultOutputPort<JSONObject> parsedOutput = new DefaultOutputPort<JSONObject>();
+ /**
+ * metric to keep count of number of tuples emitted on {@link #parsedOutput}
+ * port
+ */
+ @AutoMetric
+ long parsedOutputCount;
+
+ @Override
+ public void beginWindow(long windowId)
+ {
+ super.beginWindow(windowId);
+ parsedOutputCount = 0;
+ }
+
+ @Override
+ public void setup(OperatorContext context)
+ {
+ try {
+ if (jsonSchema != null) {
+ JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
+ JsonNode schemaNode = JsonLoader.fromString(jsonSchema);
+ schema = factory.getJsonSchema(schemaNode);
+ }
+ objMapper = new ObjectMapper();
+ } catch (ProcessingException | IOException e) {
+ DTThrowable.wrapIfChecked(e);
+ }
+ }
+
+ @Override
+ public void processTuple(String tuple)
+ {
+ try {
+ if (schema != null) {
--- End diff --
What happens when schema is null? Is this condition required?
I see the variable gets assigned in setup method.
Still, if this condition is required, please take care of null case.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by tushargosavi <gi...@git.apache.org>.
Github user tushargosavi commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r51699399
--- Diff: contrib/src/main/java/com/datatorrent/contrib/parser/JsonParser.java ---
@@ -0,0 +1,241 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.hadoop.classification.InterfaceStability;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jsonschema.exceptions.ProcessingException;
+import com.github.fge.jsonschema.main.JsonSchema;
+import com.github.fge.jsonschema.main.JsonSchemaFactory;
+import com.github.fge.jsonschema.report.ProcessingMessage;
+import com.github.fge.jsonschema.report.ProcessingReport;
+import com.github.fge.jsonschema.util.JsonLoader;
+import com.google.common.annotations.VisibleForTesting;
+
+import com.datatorrent.api.AutoMetric;
+import com.datatorrent.api.Context.OperatorContext;
+import com.datatorrent.api.DefaultOutputPort;
+import com.datatorrent.lib.parser.Parser;
+import com.datatorrent.lib.util.KeyValPair;
+import com.datatorrent.netlet.util.DTThrowable;
+
+/**
+ * Operator that parses a json string tuple against a specified json schema and
+ * emits JSONObject on one port POJO on other port and tuples that could not be
+ * parsed on error port.<br>
+ * Schema is specified in a json format as per http://json-schema.org/ <br>
+ * Example for the schema can be seen here http://json-schema.org/example1.html <br>
+ * User can choose to skip validations by not specifying the schema at all. <br>
+ * <br>
+ * <b>Properties</b> <br>
+ * <b>jsonSchema</b>:schema as a string<br>
+ * <b>clazz</b>:Pojo class <br>
+ * <b>Ports</b> <br>
+ * <b>in</b>:input tuple as a String. Each tuple represents a json string<br>
+ * <b>parsedOutput</b>:tuples that are validated against the schema are emitted
+ * as JSONObject on this port<br>
+ * <b>out</b>:tuples that are validated against the schema are emitted as pojo
+ * on this port<br>
+ * <b>err</b>:tuples that do not confine to schema are emitted on this port as
+ * KeyValPair<String,String><br>
+ * Key being the tuple and Val being the reason.
+ *
+ *
+ * @displayName JsonParser
+ * @category Parsers
+ * @tags json pojo parser
+ * @since 3.2.0
+ */
+@InterfaceStability.Evolving
+public class JsonParser extends Parser<byte[], KeyValPair<String, String>>
+{
+
+ /**
+ * Contents of the schema.Schema is specified as per http://json-schema.org/
+ */
+ private String jsonSchema;
+ private transient JsonSchema schema;
+ private transient ObjectMapper objMapper;
+ /**
+ * output port to emit validate records as JSONObject
+ */
+ public transient DefaultOutputPort<JSONObject> parsedOutput = new DefaultOutputPort<JSONObject>();
+ /**
+ * metric to keep count of number of tuples emitted on {@link #parsedOutput}
+ * port
+ */
+ @AutoMetric
+ long parsedOutputCount;
+
+ @Override
+ public void beginWindow(long windowId)
+ {
+ super.beginWindow(windowId);
+ parsedOutputCount = 0;
+ }
+
+ @Override
+ public void setup(OperatorContext context)
+ {
+ try {
+ if (jsonSchema != null) {
+ JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
+ JsonNode schemaNode = JsonLoader.fromString(jsonSchema);
+ schema = factory.getJsonSchema(schemaNode);
+ }
+ objMapper = new ObjectMapper();
+ } catch (ProcessingException | IOException e) {
+ DTThrowable.wrapIfChecked(e);
+ }
+ }
+
+ @Override
+ public void processTuple(byte[] tuple)
+ {
+ if (tuple == null) {
+ if (err.isConnected()) {
+ err.emit(new KeyValPair<String, String>(null, "null tuple"));
+ }
+ errorTupleCount++;
+ return;
+ }
+ String incomingString = new String(tuple);
+ try {
+ if (schema != null) {
--- End diff --
validation is only required if error port is connected.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by chinmaykolhatkar <gi...@git.apache.org>.
Github user chinmaykolhatkar commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49313811
--- Diff: contrib/src/main/java/com/datatorrent/contrib/parser/JsonParser.java ---
@@ -0,0 +1,187 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.hadoop.classification.InterfaceStability;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jsonschema.exceptions.ProcessingException;
+import com.github.fge.jsonschema.main.JsonSchema;
+import com.github.fge.jsonschema.main.JsonSchemaFactory;
+import com.github.fge.jsonschema.report.ProcessingMessage;
+import com.github.fge.jsonschema.report.ProcessingReport;
+import com.github.fge.jsonschema.util.JsonLoader;
+
+import com.datatorrent.api.AutoMetric;
+import com.datatorrent.api.Context.OperatorContext;
+import com.datatorrent.api.DefaultOutputPort;
+import com.datatorrent.lib.parser.Parser;
+import com.datatorrent.lib.util.KeyValPair;
+import com.datatorrent.netlet.util.DTThrowable;
+
+/**
+ * Operator that parses a json string tuple against a specified json schema and
+ * emits JSONObject on one port POJO on other port and tuples that could not be
+ * parsed on error port.<br>
+ * Schema is specified in a json format as per http://json-schema.org/ <br>
+ * Example for the schema can be seen here http://json-schema.org/example1.html <br>
+ * User can choose to skip validations by not specifying the schema at all. <br>
+ * <br>
+ * <b>Properties</b> <br>
+ * <b>jsonSchema</b>:schema as a string<br>
+ * <b>clazz</b>:Pojo class <br>
+ * <b>Ports</b> <br>
+ * <b>in</b>:input tuple as a String. Each tuple represents a json string<br>
+ * <b>parsedOutput</b>:tuples that are validated against the schema are emitted
+ * as JSONObject on this port<br>
+ * <b>out</b>:tuples that are validated against the schema are emitted as pojo
+ * on this port<br>
+ * <b>err</b>:tuples that do not confine to schema are emitted on this port as
+ * KeyValPair<String,String><br>
+ * Key being the tuple and Val being the reason.
+ *
+ *
+ * @displayName JsonParser
+ * @category Parsers
+ * @tags json pojo parser
+ * @since 3.2.0
+ */
+@InterfaceStability.Evolving
+public class JsonParser extends Parser<String, KeyValPair<String, String>>
+{
+
+ /**
+ * Contents of the schema.Schema is specified as per http://json-schema.org/
+ */
+ private String jsonSchema;
--- End diff --
You can put @NotNull attribute to jsonSchema variable. After that jsonSchema != null check won't be required in setup.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by chinmaykolhatkar <gi...@git.apache.org>.
Github user chinmaykolhatkar commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49313459
--- Diff: contrib/src/test/resources/json-parser-schema.json ---
@@ -0,0 +1,51 @@
+{
+ "$schema": "http://json-schema.org/draft-04/schema#",
+ "title": "Product set",
+ "type": "object",
+ "properties": {
+ "id": {
+ "description": "The unique identifier for a product",
+ "type": "number"
+ },
+ "name": {
+ "type": "string"
+ },
+ "price": {
+ "type": "number",
+ "minimum": 0,
+ "exclusiveMinimum": true
+ },
+ "tags": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "minItems": 1,
+ "uniqueItems": true
+ },
+ "dimensions": {
+ "type": "object",
+ "properties": {
+ "length": {"type": "number"},
+ "width": {"type": "number"},
+ "height": {"type": "number"}
+ },
+ "required": ["length", "width", "height"]
+ },
+ "warehouseLocation": {
+ "description": "Coordinates of the warehouse with the product",
+ "$ref": "http://json-schema.org/geo"
+ },
+ "dateOfManufacture": {
+ "description": "manufacturing date",
+ "type": "string"
+
+ },
+ "dateOfExpiry": {
+ "description": "expiry date",
+ "type": "string"
+
+ }
+ },
+ "required": ["id", "name", "price"]
+}
--- End diff --
New line at the end of the file is missing.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by shubham-pathak22 <gi...@git.apache.org>.
Github user shubham-pathak22 commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49687536
--- Diff: contrib/src/test/java/com/datatorrent/contrib/parser/JsonParserTest.java ---
@@ -0,0 +1,356 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.junit.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+
+import com.datatorrent.lib.appdata.schemas.SchemaUtils;
+import com.datatorrent.lib.testbench.CollectorTestSink;
+import com.datatorrent.lib.util.KeyValPair;
+
+public class JsonParserTest
+{
+ private static final String filename = "json-parser-schema.json";
+ CollectorTestSink<Object> error = new CollectorTestSink<Object>();
+ CollectorTestSink<Object> objectPort = new CollectorTestSink<Object>();
+ CollectorTestSink<Object> pojoPort = new CollectorTestSink<Object>();
+ JsonParser parser = new JsonParser();
+
+ @Rule
+ public Watcher watcher = new Watcher();
+
+ public class Watcher extends TestWatcher
+ {
+ @Override
+ protected void starting(Description description)
+ {
+ super.starting(description);
+ parser.err.setSink(error);
+ parser.parsedOutput.setSink(objectPort);
+ parser.out.setSink(pojoPort);
+ parser.setClazz(Product.class);
+ parser.setJsonSchema(SchemaUtils.jarResourceFileToString(filename));
+ parser.setup(null);
+ }
+
+ @Override
+ protected void finished(Description description)
+ {
+ super.finished(description);
+ error.clear();
+ objectPort.clear();
+ pojoPort.clear();
+ }
+ }
+
+ @Test
+ public void testValidInput() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void testValidInputWithoutSchema() throws JSONException
+ {
+ parser.setJsonSchema(null);
+ parser.setup(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void testInvalidPrice() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ Assert.assertEquals("\"/price\":\"number is lower than the required minimum\"", errorKeyValPair.getValue());
+ }
+
+ @Test
+ public void testMultipleViolations() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"width\" : 8.0," + "\"height\": 9.5" + "},"
+ + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4" + "},"
+ + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ Assert.assertEquals(
+ "\"/dimensions\":\"missing required property(ies)\",\"/price\":\"number is lower than the required minimum\"",
+ errorKeyValPair.getValue());
+ }
+
+ @Test
+ public void testJsonSyntaxError() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"width\" : 8.0," + "\"height\": 9.5" + "}"
+ + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4" + "},"
+ + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ }
+
+ @Test
+ public void testValidInputPojoPortNotConnected() throws JSONException
+ {
+ parser.out.setSink(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ }
+
+ @Test
+ public void testValidInputParsedOutputPortNotConnected() throws JSONException
+ {
+ parser.parsedOutput.setSink(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void TestParserValidInputMetricVerification()
+ {
+ Assert.assertEquals(0, parser.parsedOutputCount);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(1, parser.parsedOutputCount);
+ }
+
+ @Test
+ public void TestParserInvalidInputMetricVerification()
+ {
+ Assert.assertEquals(0, parser.parsedOutputCount);
+ String tuple = "{" + "\"id\": 2" + "}";
+ parser.in.process(tuple);
+ Assert.assertEquals(0, parser.parsedOutputCount);
+ }
--- End diff --
Sure @gauravgopi123 . Because beingWindow and endWindow did not have any functionality except resetting autometric which actually defaults to 0, i did not explicitly call them. But i agree with you, the test must reflect function calls in the same order as they are called in application. I have added it now.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by chinmaykolhatkar <gi...@git.apache.org>.
Github user chinmaykolhatkar commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r49312662
--- Diff: library/.gitignore ---
@@ -0,0 +1 @@
+/target
--- End diff --
Can you please review this change?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
[GitHub] incubator-apex-malhar pull request: MLHR-1962 json parser enhancem...
Posted by chinmaykolhatkar <gi...@git.apache.org>.
Github user chinmaykolhatkar commented on a diff in the pull request:
https://github.com/apache/incubator-apex-malhar/pull/163#discussion_r51689036
--- Diff: contrib/src/test/java/com/datatorrent/contrib/parser/JsonParserTest.java ---
@@ -0,0 +1,414 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.datatorrent.contrib.parser;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.junit.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+
+import com.datatorrent.lib.appdata.schemas.SchemaUtils;
+import com.datatorrent.lib.testbench.CollectorTestSink;
+import com.datatorrent.lib.util.KeyValPair;
+
+public class JsonParserTest
+{
+ private static final String filename = "json-parser-schema.json";
+ CollectorTestSink<Object> error = new CollectorTestSink<Object>();
+ CollectorTestSink<Object> objectPort = new CollectorTestSink<Object>();
+ CollectorTestSink<Object> pojoPort = new CollectorTestSink<Object>();
+ JsonParser parser = new JsonParser();
+
+ @Rule
+ public Watcher watcher = new Watcher();
+
+ public class Watcher extends TestWatcher
+ {
+ @Override
+ protected void starting(Description description)
+ {
+ super.starting(description);
+ parser.err.setSink(error);
+ parser.parsedOutput.setSink(objectPort);
+ parser.out.setSink(pojoPort);
+ parser.setClazz(Product.class);
+ parser.setJsonSchema(SchemaUtils.jarResourceFileToString(filename));
+ parser.setup(null);
+ }
+
+ @Override
+ protected void finished(Description description)
+ {
+ super.finished(description);
+ error.clear();
+ objectPort.clear();
+ pojoPort.clear();
+ parser.teardown();
+ }
+ }
+
+ @Test
+ public void testValidInput() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void testEmptyInput() throws JSONException
+ {
+ parser.setSchema(null);
+ String tuple = "";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ }
+
+ @Test
+ public void testValidInputWithoutSchema() throws JSONException
+ {
+ parser.setSchema(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void testInvalidPrice() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ Assert.assertEquals("\"/price\":\"number is lower than the required minimum\"", errorKeyValPair.getValue());
+ }
+
+ @Test
+ public void testMultipleViolations() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"width\" : 8.0," + "\"height\": 9.5" + "},"
+ + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4" + "},"
+ + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ Assert.assertEquals(
+ "\"/dimensions\":\"missing required property(ies)\",\"/price\":\"number is lower than the required minimum\"",
+ errorKeyValPair.getValue());
+ }
+
+ @Test
+ public void testJsonSyntaxError() throws JSONException
+ {
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": -1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"width\" : 8.0," + "\"height\": 9.5" + "}"
+ + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4" + "},"
+ + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(1, error.collectedTuples.size());
+ KeyValPair<String, String> errorKeyValPair = (KeyValPair<String, String>)error.collectedTuples.get(0);
+ Assert.assertEquals(tuple, errorKeyValPair.getKey());
+ }
+
+ @Test
+ public void testValidInputPojoPortNotConnected() throws JSONException
+ {
+ parser.out.setSink(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(1, objectPort.collectedTuples.size());
+ Assert.assertEquals(0, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ JSONObject jsonObject = (JSONObject)objectPort.collectedTuples.get(0);
+ Assert.assertEquals(2, jsonObject.getInt("id"));
+ Assert.assertEquals(1, jsonObject.getInt("price"));
+ Assert.assertEquals("An ice sculpture", jsonObject.get("name"));
+ Assert.assertEquals(7.0, jsonObject.getJSONObject("dimensions").getDouble("length"), 0);
+ }
+
+ @Test
+ public void testValidInputParsedOutputPortNotConnected() throws JSONException
+ {
+ parser.parsedOutput.setSink(null);
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.beginWindow(0);
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(0, objectPort.collectedTuples.size());
+ Assert.assertEquals(1, pojoPort.collectedTuples.size());
+ Assert.assertEquals(0, error.collectedTuples.size());
+ Object obj = pojoPort.collectedTuples.get(0);
+ Assert.assertNotNull(obj);
+ Assert.assertEquals(Product.class, obj.getClass());
+ Product pojo = (Product)obj;
+ Assert.assertEquals(2, pojo.getId());
+ Assert.assertEquals(1, pojo.getPrice());
+ Assert.assertEquals("An ice sculpture", pojo.getName());
+ Assert.assertEquals(7.0, (double)pojo.getDimensions().get("length"), 0);
+ }
+
+ @Test
+ public void TestParserValidInputMetricVerification()
+ {
+ parser.beginWindow(0);
+ Assert.assertEquals(0, parser.parsedOutputCount);
+ Assert.assertEquals(0, parser.getIncomingTuplesCount());
+ Assert.assertEquals(0, parser.getErrorTupleCount());
+ Assert.assertEquals(0, parser.getEmittedObjectCount());
+ String tuple = "{" + "\"id\": 2," + "\"name\": \"An ice sculpture\"," + "\"price\": 1,"
+ + "\"tags\": [\"cold\", \"ice\"]," + "\"dimensions\": {" + "\"length\": 7.0," + "\"width\" : 8.0,"
+ + "\"height\": 9.5" + "}," + "\"warehouseLocation\": {" + "\"latitude\": -78.75," + "\"longitude\": 20.4"
+ + "}," + "\"dateOfManufacture\": \"2013/09/29\"," + "\"dateOfExpiry\": \"2013\"" + "}";
+ parser.in.process(tuple.getBytes());
+ parser.endWindow();
+ Assert.assertEquals(1, parser.parsedOutputCount);
+ Assert.assertEquals(1, parser.getIncomingTuplesCount());
+ Assert.assertEquals(0, parser.getErrorTupleCount());
+ Assert.assertEquals(1, parser.getEmittedObjectCount());
+ }
+
+ @Test
+ public void TestParserInvalidInputMetricVerification()
--- End diff --
Test case name should start with "test". That's what is followed everywhere.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---