Projekt

Obecné

Profil

« Předchozí | Další » 

Revize 961cd43a

Přidáno uživatelem Michal Horký před více než 4 roky(ů)

#7794

Rozpoznávání polí, úprava JSON

Zobrazit rozdíly:

demo_mh/Deserializer/.classpath
2 2
<classpath>
3 3
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
4 4
	<classpathentry kind="src" path="src"/>
5
	<classpathentry kind="lib" path="libs/json-simple-1.1.1.jar"/>
5
	<classpathentry kind="lib" path="D:/Michal/University/1/LS/ASWI/semestralky/Deserializer/aswi2020horky/demo_mh/Deserializer/libs/jackson-core-asl-1.9.13.jar"/>
6
	<classpathentry kind="lib" path="D:/Michal/University/1/LS/ASWI/semestralky/Deserializer/aswi2020horky/demo_mh/Deserializer/libs/jackson-mapper-asl-1.9.13.jar"/>
7
	<classpathentry kind="lib" path="D:/Michal/University/1/LS/ASWI/semestralky/Deserializer/aswi2020horky/demo_mh/Deserializer/libs/jdeserialize-1.2.jar"/>
6 8
	<classpathentry kind="output" path="bin"/>
7 9
</classpath>
demo_mh/Deserializer/Deserializer.iml
1
<?xml version="1.0" encoding="UTF-8"?>
2
<module type="JAVA_MODULE" version="4">
3
  <component name="EclipseModuleManager">
4
    <libelement value="jar://$MODULE_DIR$/libs/json-simple-1.1.1.jar!/" />
5
    <src_description expected_position="1">
6
      <src_folder value="file://$MODULE_DIR$/src" expected_position="1" />
7
    </src_description>
8
  </component>
9
  <component name="NewModuleRootManager">
10
    <output url="file://$MODULE_DIR$/bin" />
11
    <exclude-output />
12
    <content url="file://$MODULE_DIR$">
13
      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
14
    </content>
15
    <orderEntry type="inheritedJdk" />
16
    <orderEntry type="sourceFolder" forTests="false" />
17
    <orderEntry type="module-library">
18
      <library name="json-simple-1.1.1.jar">
19
        <CLASSES>
20
          <root url="jar://$MODULE_DIR$/libs/json-simple-1.1.1.jar!/" />
21
        </CLASSES>
22
        <JAVADOC />
23
        <SOURCES />
24
      </library>
25
    </orderEntry>
26
  </component>
27
</module>
demo_mh/Deserializer/libs/Licenses
1
JSON Simple
2
	https://code.google.com/archive/p/json-simple/
3
	Apache License 2.0
1

  
2
JACKSON JSON
3

  
4
This copy of Jackson JSON processor streaming parser/generator is licensed under the
5
Apache (Software) License, version 2.0 ("the License").
6
See the License for details about distribution rights, and the
7
specific rights regarding derivate works.
8

  
9
You may obtain a copy of the License at:
10

  
11
http://www.apache.org/licenses/LICENSE-2.0
12

  
13
************************************************************
14

  
15
JDESERIALIZE
16

  
17
https://code.google.com/archive/p/jdeserialize/
18
https://opensource.org/licenses/BSD-3-Clause
19
Copyright <YEAR> <COPYRIGHT HOLDER>
20

  
21
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
22

  
23
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
24

  
25
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
26

  
27
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
28

  
29
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
demo_mh/Deserializer/results.json
1
{"parent":{"variables":{"str":"ABCD","abc":true,"y":59.87},"name":"class serialize.Parent","interface":"java.io.Serializable"},"variables":{"x":10.0,"variable":{"variables":{"array":"NON_IMPLEMENTED"},"name":"class serialize.Contain","interface":"java.io.Serializable"},"numberX":7},"name":"class serialize.Example","interface":"java.io.Serializable"}
1
{
2
  "class serialize.Example extends serialize.Example implements java.io.Serializable" : {
3
    "numberX" : "7",
4
    "x" : "10.0",
5
    "variable" : {
6
      "class serialize.Contain implements java.io.Serializable" : {
7
        "array" : "[W, X, Y, Z]",
8
        "array2" : "NOT_IMPLEMENTED"
9
      }
10
    },
11
    "parent" : {
12
      "class serialize.Parent implements java.io.Serializable" : {
13
        "abc" : "true",
14
        "y" : "59.87",
15
        "str" : "ABCD"
16
      }
17
    }
18
  }
19
}
demo_mh/Deserializer/src/deserialize/ClassDescription.java
3 3
import java.util.ArrayList;
4 4
import java.util.List;
5 5

  
6
import org.json.simple.JSONObject;
6
import org.codehaus.jackson.JsonNode;
7
import org.codehaus.jackson.map.ObjectMapper;
8
import org.codehaus.jackson.node.ObjectNode;
7 9

  
8 10
public class ClassDescription {
9 11

  
......
15 17
	byte flags;
16 18
	boolean isClass; // or enum
17 19
	
18
	private List<ClassDescription> parents = new ArrayList<ClassDescription>();
20
	// Class is in the first place, parents are in the other positions.
21
	private List<ClassDescription> instances = new ArrayList<ClassDescription>();
19 22
	private int actParentIndex = -1;
20 23
	
21 24
	private List<Variable> variables = new ArrayList<Variable>();
......
23 26
	
24 27
	
25 28
	
26
	public List<ClassDescription> getParents() {
27
		return parents;
29
	public List<ClassDescription> getInstances() {
30
		return instances;
28 31
	}
29 32
	
30 33
	public List<Variable> getVariables() {
......
42 45
	}
43 46
	
44 47
	public void addParent(ClassDescription parent) {
45
		parents.add(parent);
48
		instances.add(parent);
46 49
		actParentIndex++;
47 50
	}
48 51
	
49 52
	public Variable getActVariable() {
50 53
		for (; actParentIndex >= 0; actParentIndex--) {
51
			Variable var = parents.get(actParentIndex).nextVariable();
54
			Variable var = instances.get(actParentIndex).nextVariable();
52 55
			if (var != null) {
53 56
				return var;
54 57
			}
......
60 63
		this.variables = variables;
61 64
	}
62 65
	
63
	@SuppressWarnings("unchecked")
64
	public JSONObject getJSONObject() {
66
	public JsonNode getJsonNode() {
65 67
		int actIndex = ++actParentIndex;
66
		JSONObject obj = new JSONObject();
67 68
		
68
		JSONObject vars = new JSONObject();
69
		ObjectMapper mapper = new ObjectMapper();
70
		
71
		JsonNode childNode = mapper.createObjectNode();
69 72
		for (int j = 0; j < variables.size(); j++) {
70
			variables.get(j).putToJSON(vars);
73
			variables.get(j).putToJson((ObjectNode) childNode);
71 74
		}
72
		obj.put("variables", vars);
73
		
74
		String i = "";
75
		if (flags == SC_SERIALIZABLE) {
76
			i = "java.io.Serializable";
77
		} else if (flags == SC_EXTERNALIZABLE) {
78
			i = "java.io.Externalizable";
75
		if ((actIndex + 1) < instances.size()) {
76
			((ObjectNode) childNode).put("parent", instances.get(actIndex + 1).getJsonNode());
79 77
		}
80
		obj.put("interface", i);
81
		
78

  
82 79
		String name;
83 80
		if (isClass) {
84 81
			name = "class";
85 82
		} else {
86 83
			name = "enum";
87 84
		}
85
		
88 86
		name += " " + className;
89
		obj.put("name", name);
90 87
		
91
		if ((actIndex + 1) < parents.size()) {
92
			obj.put("parent", parents.get(actIndex + 1).getJSONObject());
88
		if (actIndex < instances.size()) {
89
			name += " extends " + instances.get(actIndex).className;
93 90
		}
94 91
		
95
		return obj;
92
		if (flags == SC_SERIALIZABLE) {
93
			name += " implements java.io.Serializable";
94
		} else if (flags == SC_EXTERNALIZABLE) {
95
			name += " implements java.io.Externalizable";
96
		}
97
		
98
		JsonNode rootNode = mapper.createObjectNode();
99
		((ObjectNode) rootNode).put(name, childNode);
100
		return rootNode;
96 101
	}
97
	
102

  
98 103
	@Override
99 104
	public String toString() {
100 105
		actParentIndex++;
......
108 113
		
109 114
		retValue += " " + className;
110 115
		
111
		if ((actParentIndex + 1) < parents.size()) {
112
			retValue += " extends " + parents.get(actParentIndex + 1).className;
116
		if ((actParentIndex + 1) < instances.size()) {
117
			retValue += " extends " + instances.get(actParentIndex + 1).className;
113 118
		}
114 119
		
115 120
		if (flags == SC_SERIALIZABLE) {
......
127 132
		}
128 133
		retValue += "\n}\n";
129 134
		
130
		if ((actParentIndex + 1) < parents.size()) {
131
			retValue += parents.get(actParentIndex + 1).toString();
135
		if ((actParentIndex + 1) < instances.size()) {
136
			retValue += instances.get(actParentIndex + 1).toString();
132 137
		}
133 138
		
134 139
		return retValue;
demo_mh/Deserializer/src/deserialize/Deserializer.java
35 35
	@Override
36 36
	public void init() throws Exception {
37 37
		super.init();
38
		testing = true;
38
		testing = false;
39 39
	}
40 40
	
41 41
	@Override
demo_mh/Deserializer/src/deserialize/Grammar.java
1 1
package deserialize;
2 2

  
3
import java.nio.ByteBuffer;
4 3
import java.util.ArrayList;
5
import java.util.HashMap;
4
import java.util.Arrays;
6 5
import java.util.List;
7 6

  
8
import org.json.simple.JSONObject;
7
import org.codehaus.jackson.JsonNode;
9 8

  
10 9
/**
11 10
 * https://docs.oracle.com/javase/7/docs/platform/serialization/spec/protocol.html
......
43 42
		reader = new ByteReader(buffer);
44 43
	}
45 44
	
46
	
45

  
47 46
	List<ClassDescription> classes = new ArrayList<ClassDescription>();
48 47
	ClassDescription actClass = null;
49 48
	
50
	public JSONObject process() {
49
	public JsonNode process() {
51 50
		System.out.println("Kontrola hlavicky souboru: " + (reader.readShort() == STREAM_MAGIC && reader.readShort() == STREAM_VERSION));
52 51
		
53 52
		while (!reader.end()) {
......
59 58
			}
60 59
		}
61 60
		
62
		return classes.get(0).getJSONObject();
61
		return classes.get(0).getJsonNode();
63 62
		// System.out.println(classes.get(0).toString());
64 63
	}
65 64
	
......
114 113
				}
115 114
				break;
116 115
			case TC_ARRAY: {
117
					System.out.println("X3");
118 116
					ClassDescription desc = (ClassDescription) object();
117
					System.out.println("X3 " /*+ desc*/);
119 118
					// TODO int size = readInt();
120 119
					retValue = desc; // TODO + "[" + size + "]";
121 120
				}
122 121
				break;
123 122
			case TC_STRING: {
124
					System.out.println("X4");
125 123
					String str = reader.readUtf();
124
					System.out.println("X4 " + str);
126 125
					retValue = str;
127 126
				}
128 127
				break;
......
166 165
					System.out.println("X8");
167 166
					int count = reader.readInt();
168 167
					String name = reader.readUtf();
169
					retValue = name + "[" + +count + "]";
168
					retValue = name + "[" + count + "]";
170 169
					// TODO object(null); classDesc();
171
					
172 170
				}
173 171
				break;
174 172
			case TC_NULL: {
......
199 197
							object(); // END BLOK
200 198
							object(); // NULL
201 199
							
202
							int count = reader.readInt();
203
							System.out.println("------------- VELIKOST POLE = " + count);
204
							for (int i = 0; i < count; i++) {
205
								System.out.println("------------- HODNOTA = " + reader.readChar());
200
							String dataType = desccc.className.substring(1);
201
							
202
							Object array[] = new Object[reader.readInt()];
203
							for (int i = 0; i < array.length; i++) {
204
								Object element = null;
205
								switch (dataType.charAt(0)) {
206
								case 'B': element = reader.readByte(); break;
207
								case 'C': element = reader.readChar(); break;
208
								case 'D': element = reader.readDouble(); break;
209
								case 'F': element = reader.readFloat(); break;
210
								case 'I': element = reader.readInt(); break;
211
								case 'J': element = reader.readLong(); break;
212
								case 'S': element = reader.readShort(); break;
213
								case 'Z': element = reader.readBoolean(); break;
214
								case '[': object(); break; // TODO
215
								case 'L': element = object(); break;
216
								}
217
								array[i] = element;
206 218
							}
207
							//actVar.setValue(readByte());
219
							
220
							System.out.println(Arrays.toString(array));
221
							actVar.setValue(array);
208 222
							break;
209 223
						case 'L': actVar.setValue(object()); break;
210 224
						}
......
213 227
				break;
214 228
			case TC_REFERENCE: {
215 229
					System.out.println("---REFERENCE---");
230
					int ref = reader.readInt();
231
					System.out.println(String.format("%X", ref));
232
					int num = reader.readInt();
233
					System.out.println(String.format("%X", num));
216 234
					// TODO (ClassDesc) TC_REFERENCE (int)handle ?!?
217 235
					retValue = null;
218 236
				}
......
220 238
				
221 239
				
222 240
			case TC_EXCEPTION: {
223
					// TODO (Throwable)object(null);
224
					retValue = "(Throwable)";
241
					// (Throwable)object;
242
					retValue = (Throwable) object();
225 243
				}
226 244
				break;
227 245
			case TC_RESET: {
......
233 251
			case TC_BLOCKDATA: {
234 252
					System.out.println("X13");
235 253
					char size = reader.readUnsignedByte();
254
					byte[] data = new byte[size];
255
					for (int i = 0; i < size; i++) {
256
						data[i] = reader.readByte();
257
					}
236 258
					// (unsigned byte)<size> (byte)[size];
237
					retValue = "byte [" + (int) size + "]";
259
					retValue = data;
238 260
				}
239 261
				break;
240 262
			case TC_BLOCKDATALONG: {
241 263
					System.out.println("X14");
242 264
					int size = reader.readInt();
265
					byte[] data = new byte[size];
266
					for (int i = 0; i < size; i++) {
267
						data[i] = reader.readByte();
268
					}
243 269
					// (int)<size> (byte)[size];
244
					retValue = "byte [" + size + "]";
270
					retValue = data;
245 271
				}
246 272
				break;
247 273
			case TC_ENDBLOCKDATA: {
demo_mh/Deserializer/src/deserialize/ToJSON.java
11 11
import java.util.zip.ZipEntry;
12 12
import java.util.zip.ZipFile;
13 13

  
14
import org.json.simple.JSONObject;
14
import org.codehaus.jackson.JsonNode;
15
import org.codehaus.jackson.map.ObjectMapper;
15 16

  
16 17
public class ToJSON extends Thread {
17 18
	
......
44 45
		System.out.println("Spoustim univerzalni deserializer.");
45 46
		
46 47
		Grammar g = new Grammar(buffer);
47
		JSONObject results = g.process();
48
		JsonNode results = g.process();
48 49
		
49 50
		save(results);
50 51
		
......
117 118
	    return array;
118 119
	}
119 120
	
120
	private void save(JSONObject obj) {
121
	private void save(JsonNode node) {
121 122
        try {
122 123
            FileWriter fw = new FileWriter(output);
123 124
            BufferedWriter bw = new BufferedWriter(fw);
124
            bw.write(obj.toJSONString());
125
            String jsonString = (new ObjectMapper()).writerWithDefaultPrettyPrinter().writeValueAsString(node);
126
            bw.write(jsonString);
125 127
            bw.flush();
126 128
            bw.close();
127 129
            Report.info("JSON", null, "Ulo?en? souboru prob?hlo v po??dku.");
......
130 132
            Report.info("JSON", null, "P?i ukl?d?n? souboru nastala chyba.");
131 133
        }
132 134
	}
133
	
135

  
134 136
}
demo_mh/Deserializer/src/deserialize/Variable.java
1 1
package deserialize;
2 2

  
3
import org.json.simple.JSONObject;
3
import java.util.Arrays;
4

  
5
import org.codehaus.jackson.node.ObjectNode;
4 6

  
5 7
public class Variable {
6 8
	
......
8 10
	private String variable;
9 11
	private String typeName;
10 12
	private Object value = null;
13
	private Object array[] = null;
11 14
	
12 15
	public Variable(char type, String variable, String typeName) {
13 16
		this.type = type;
......
34 37
	}
35 38
	
36 39
	public boolean isValueSet() {
37
		return value != null;
40
		return value != null || array != null;
38 41
	}
39 42
	
40 43
	public void setValue(Object value) {
41 44
		this.value = value;
42 45
	}
43 46
	
44
	@SuppressWarnings("unchecked")
45
	public void putToJSON(JSONObject obj) {
46
		if (value != null) {
47
			if (value.getClass().toString().equals(ClassDescription.class.toString())) {
47
	public void setValue(Object array[]) {
48
		this.array = array;
49
	}
50
	
51
	public void putToJson(ObjectNode node) {
52
		if (value != null || array != null) {
53
			if (value != null && value.getClass().toString().equals(ClassDescription.class.toString())) {
48 54
				ClassDescription desc = (ClassDescription) value;
49
				obj.put(variable, desc.getJSONObject());
50
			} else {
51
				obj.put(variable, value);
55
				node.put(variable, desc.getJsonNode());
56
			} else if (value != null) {
57
				node.put(variable, value.toString());
58
			} else if (array != null) {
59
				node.put(variable, Arrays.toString(array));
52 60
			}
53 61
		} else {
54
			obj.put(variable, "NON_IMPLEMENTED");
62
			node.put(variable, "NOT_IMPLEMENTED");
55 63
		}
56 64
	}
57 65
	
......
72 80
			if (value.getClass().toString().equals(ClassDescription.class.toString())) {
73 81
				ClassDescription desc = (ClassDescription) value;
74 82
				result += desc.toString();
75
			} else {
83
			} else if (value != null) {
76 84
				result += value;
85
			} else if (array != null) {
86
				result += Arrays.toString(array);
77 87
			}
78 88
		}
79 89
		
demo_mh/Deserializer/src/serialize/Contain.java
7 7
	private static final long serialVersionUID = 1L;
8 8
	
9 9
	char array[] = new char[] {'W', 'X', 'Y', 'Z'};
10
	// float realNum = 15.6f;
10
	String array2[] = new String[] { "AbC", "dEfGhI", "xyz", "jKlMnOpQ"};
11 11
	
12 12
}
demo_mh/Deserializer/src/serialize/Parent.java
9 9
	String str = "ABCD";
10 10
	boolean abc = true;
11 11
	double y = 59.87;
12
	// TODO Contain c[] = new Contain[] {new Contain(), new Contain(), new Contain()};
12 13
	
13 14
}
demo_mh/example.json
1
{
2
  "class serialize.Example extends serialize.Example implements java.io.Serializable" : {
3
    "numberX" : "7",
4
    "x" : "10.0",
5
    "variable" : {
6
      "class serialize.Contain implements java.io.Serializable" : {
7
        "array" : "[W, X, Y, Z]",
8
        "array2" : "NOT_IMPLEMENTED"
9
      }
10
    },
11
    "parent" : {
12
      "class serialize.Parent implements java.io.Serializable" : {
13
        "abc" : "true",
14
        "y" : "59.87",
15
        "str" : "ABCD"
16
      }
17
    }
18
  }
19
}

Také k dispozici: Unified diff