Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[bin2json] bin2json Transformation #5348

Merged
merged 8 commits into from
Apr 1, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions bundles/org.openhab.transform.bin2json/.classpath
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>
23 changes: 23 additions & 0 deletions bundles/org.openhab.transform.bin2json/.project
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>org.openhab.transform.bin2json</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>
20 changes: 20 additions & 0 deletions bundles/org.openhab.transform.bin2json/NOTICE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
This content is produced and maintained by the openHAB project.

* Project home: https://www.openhab.org

== Declared Project Licenses

This program and the accompanying materials are made available under the terms
of the Eclipse Public License 2.0 which is available at
https://www.eclipse.org/legal/epl-2.0/.

== Source Code

https://github.com/openhab/openhab2-addons

== Third-party Content

jbbp
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can the jbbp-1.4.1.jar library be provided by maven as dependency instead of adding the jar file?

* License: Apache 2.0 License
* Project: https://github.com/raydac/java-binary-block-parser
* Source: https://github.com/raydac/java-binary-block-parser
15 changes: 15 additions & 0 deletions bundles/org.openhab.transform.bin2json/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Binary To JSON Transformation Service

Transforms the input by Java Binary Block Parser syntax.

See details about syntax from [JBBP homepage](https://github.com/raydac/java-binary-block-parser)

## Example

Let's assume we have received string containing bytes in hexa string format `03FAFF` and we want to convert binary data to JSON format. Binary data contains 3 bytes and strict data format is following `byte a; byte b; ubyte c;`.

Binary to JSON converter will return following result `{"a":3,"b":-6,"c":255}`

## Usage as a Profile

Profiles are not supported by this transformation.
25 changes: 25 additions & 0 deletions bundles/org.openhab.transform.bin2json/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>org.openhab.addons.bundles</groupId>
<artifactId>org.openhab.addons.reactor.bundles</artifactId>
<version>2.5.0-SNAPSHOT</version>
</parent>

<artifactId>org.openhab.transform.bin2json</artifactId>

<name>openHAB Add-ons :: Bundles :: Binary To JSON Transformation Service</name>

<dependencies>
<dependency>
<groupId>com.igormaznitsa</groupId>
<artifactId>jbbp</artifactId>
<version>1.4.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
/**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.transform.bin2json.internal;

import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.time.LocalDateTime;

import org.eclipse.smarthome.core.util.HexUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.igormaznitsa.jbbp.JBBPParser;
import com.igormaznitsa.jbbp.exceptions.JBBPException;
import com.igormaznitsa.jbbp.model.JBBPAbstractArrayField;
import com.igormaznitsa.jbbp.model.JBBPAbstractField;
import com.igormaznitsa.jbbp.model.JBBPFieldArrayBit;
import com.igormaznitsa.jbbp.model.JBBPFieldArrayBoolean;
import com.igormaznitsa.jbbp.model.JBBPFieldArrayByte;
import com.igormaznitsa.jbbp.model.JBBPFieldArrayInt;
import com.igormaznitsa.jbbp.model.JBBPFieldArrayLong;
import com.igormaznitsa.jbbp.model.JBBPFieldArrayShort;
import com.igormaznitsa.jbbp.model.JBBPFieldArrayStruct;
import com.igormaznitsa.jbbp.model.JBBPFieldArrayUByte;
import com.igormaznitsa.jbbp.model.JBBPFieldArrayUShort;
import com.igormaznitsa.jbbp.model.JBBPFieldBit;
import com.igormaznitsa.jbbp.model.JBBPFieldBoolean;
import com.igormaznitsa.jbbp.model.JBBPFieldByte;
import com.igormaznitsa.jbbp.model.JBBPFieldInt;
import com.igormaznitsa.jbbp.model.JBBPFieldLong;
import com.igormaznitsa.jbbp.model.JBBPFieldShort;
import com.igormaznitsa.jbbp.model.JBBPFieldStruct;
import com.igormaznitsa.jbbp.model.JBBPFieldUByte;
import com.igormaznitsa.jbbp.model.JBBPFieldUShort;

/**
* This class converts binary data to JSON format.
*
* Parser rules follows Java Binary Block Parser syntax.
*
* <p>
*
* See details from <a href=
* "https://github.com/raydac/java-binary-block-parser">https://github.com/raydac/java-binary-block-parser</a>
*
* <p>
* Usage example:
*
* <pre>
* {@code
* JsonObject json = new Bin2Json("byte a; byte b; ubyte c;").convert("03FAFF");
* json.toString() = {"a":3,"b":-6,"c":255}
* </pre>
*
* @author Pauli Anttila - Initial contribution
*
*/
public class Bin2Json {

private final Logger logger = LoggerFactory.getLogger(Bin2Json.class);

private JBBPParser parser;

/**
*
* @param parserRule Binary data parser rule
* @throws ConversionException
*/
public Bin2Json(String parserRule) throws ConversionException {
try {
parser = JBBPParser.prepare(parserRule);
} catch (JBBPException e) {
throw new ConversionException(String.format("Illegal parser rule, reason: %s", e.getMessage(), e));
}
}

/**
* Convert {@link String} in hexadecimal string format to JSON object.
*
* @param hexString Data in hexadecimal string format. Example data: 03FAFF
* @return Gson {@link JsonObject}
* @throws ConversionException
*/
public JsonObject convert(String hexString) throws ConversionException {
try {
return convert(HexUtils.hexToBytes(hexString));
} catch (IllegalArgumentException e) {
throw new ConversionException(String.format("Illegal hexstring , reason: %s", e.getMessage(), e));
}
}

/**
* Convert byte array to JSON object.
*
* @param data Data in byte array format.
* @return Gson {@link JsonObject}
* @throws ConversionException
*/
public JsonObject convert(byte[] data) throws ConversionException {
try {
return convert(parser.parse(data));
} catch (IOException e) {
throw new ConversionException(String.format("Unexpected error, reason: %s", e.getMessage(), e));
} catch (JBBPException e) {
throw new ConversionException(String.format("Unexpected error, reason: %s", e.getMessage(), e));
}
}

/**
* Convert data from {@link InputStream} to JSON object.
*
* @param inputStream
* @return Gson {@link JsonObject}
* @throws ConversionException
*/
public JsonObject convert(InputStream inputStream) throws ConversionException {
try {
return convert(parser.parse(inputStream));
} catch (IOException e) {
throw new ConversionException(String.format("Unexpected error, reason: %s", e.getMessage(), e));
} catch (JBBPException e) {
throw new ConversionException(String.format("Unexpected error, reason: %s", e.getMessage(), e));
}
}

private JsonObject convert(JBBPFieldStruct data) throws ConversionException {
try {
LocalDateTime start = LocalDateTime.now();
final JsonObject json = convertToJSon(data);
if (logger.isTraceEnabled()) {
Duration duration = Duration.between(start, LocalDateTime.now());
logger.trace("Conversion time={}, json={}", duration, json.toString());
}
return json;
} catch (JBBPException e) {
throw new ConversionException(String.format("Unexpected error, reason: %s", e.getMessage(), e));
}
}

private JsonObject convertToJSon(final JBBPAbstractField field) throws ConversionException {
return convertToJSon(null, field);
}

private JsonObject convertToJSon(final JsonObject json, final JBBPAbstractField field) throws ConversionException {
JsonObject jsn = json == null ? new JsonObject() : json;

final String fieldName = field.getFieldName() == null ? "nonamed" : field.getFieldName();
if (field instanceof JBBPAbstractArrayField) {
final JsonArray jsonArray = new JsonArray();
if (field instanceof JBBPFieldArrayBit) {
for (final byte b : ((JBBPFieldArrayBit) field).getArray()) {
jsonArray.add(new JsonPrimitive(b));
}
} else if (field instanceof JBBPFieldArrayBoolean) {
for (final boolean b : ((JBBPFieldArrayBoolean) field).getArray()) {
jsonArray.add(new JsonPrimitive(b));
}
} else if (field instanceof JBBPFieldArrayByte) {
for (final byte b : ((JBBPFieldArrayByte) field).getArray()) {
jsonArray.add(new JsonPrimitive(b));
}
} else if (field instanceof JBBPFieldArrayInt) {
for (final int b : ((JBBPFieldArrayInt) field).getArray()) {
jsonArray.add(new JsonPrimitive(b));
}
} else if (field instanceof JBBPFieldArrayLong) {
for (final long b : ((JBBPFieldArrayLong) field).getArray()) {
jsonArray.add(new JsonPrimitive(b));
}
} else if (field instanceof JBBPFieldArrayShort) {
for (final short b : ((JBBPFieldArrayShort) field).getArray()) {
jsonArray.add(new JsonPrimitive(b));
}
} else if (field instanceof JBBPFieldArrayStruct) {
final JBBPFieldArrayStruct array = (JBBPFieldArrayStruct) field;
for (int i = 0; i < array.size(); i++) {
jsonArray.add(convertToJSon(new JsonObject(), array.getElementAt(i)));
}
} else if (field instanceof JBBPFieldArrayUByte) {
for (final byte b : ((JBBPFieldArrayUByte) field).getArray()) {
jsonArray.add(new JsonPrimitive(b & 0xFF));
}
} else if (field instanceof JBBPFieldArrayUShort) {
for (final short b : ((JBBPFieldArrayUShort) field).getArray()) {
jsonArray.add(new JsonPrimitive(b & 0xFFFF));
}
} else {
throw new ConversionException(String.format("Unexpected field type '%s'", field));
}
jsn.add(fieldName, jsonArray);
} else {
if (field instanceof JBBPFieldBit) {
jsn.addProperty(fieldName, ((JBBPFieldBit) field).getAsInt());
} else if (field instanceof JBBPFieldBoolean) {
jsn.addProperty(fieldName, ((JBBPFieldBoolean) field).getAsBool());
} else if (field instanceof JBBPFieldByte) {
jsn.addProperty(fieldName, ((JBBPFieldByte) field).getAsInt());
} else if (field instanceof JBBPFieldInt) {
jsn.addProperty(fieldName, ((JBBPFieldInt) field).getAsInt());
} else if (field instanceof JBBPFieldLong) {
jsn.addProperty(fieldName, ((JBBPFieldLong) field).getAsLong());
} else if (field instanceof JBBPFieldShort) {
jsn.addProperty(fieldName, ((JBBPFieldShort) field).getAsInt());
} else if (field instanceof JBBPFieldStruct) {
final JBBPFieldStruct struct = (JBBPFieldStruct) field;
final JsonObject obj = new JsonObject();
for (final JBBPAbstractField f : struct.getArray()) {
convertToJSon(obj, f);
}
if (json == null) {
return obj;
} else {
jsn.add(fieldName, obj);
}
} else if (field instanceof JBBPFieldUByte) {
jsn.addProperty(fieldName, ((JBBPFieldUByte) field).getAsInt());
} else if (field instanceof JBBPFieldUShort) {
jsn.addProperty(fieldName, ((JBBPFieldUShort) field).getAsInt());
} else {
throw new ConversionException(String.format("Unexpected field '%s'", field));
}
}
return jsn;
}
}
Loading