Projekt

Obecné

Profil

« Předchozí | Další » 

Revize 9744d223

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

#7767

Zprovoznění exportu do JSON. Přidáno zpracovávání binárních zazipovaných dat. Úprava struktury.

Zobrazit rozdíly:

demo_mh/Deserializer/results.json
1
{"States":["Madhya Pradesh","Maharastra","Rajasthan"],"Population":1000000,"Name":"India"}
1
{"parent":{"variables":{"str":"ABCD"},"name":"class serialize.Parent","interface":"java.io.Serializable"},"variables":{"x":10.0,"variable":{"variables":{"realNum":15.6},"name":"class serialize.Contain","interface":"java.io.Serializable"},"numberX":7},"name":"class serialize.Example","interface":"java.io.Serializable"}
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;
7

  
6 8
public class ClassDescription {
7 9

  
8
	final static byte SC_SERIALIZABLE = (byte) 0x02;
9
	final static byte SC_EXTERNALIZABLE = (byte) 0x04;
10
	private final static byte SC_SERIALIZABLE = (byte) 0x02;
11
	private final static byte SC_EXTERNALIZABLE = (byte) 0x04;
10 12
	
11 13
	String className;
12 14
	long serialVersionUID;
13 15
	byte flags;
14 16
	boolean isClass; // or enum
15
	List<String> variables = new ArrayList<String>();
17
	
18
	private List<ClassDescription> parents = new ArrayList<ClassDescription>();
19
	private int actParentIndex = -1;
20
	
21
	private List<Variable> variables = new ArrayList<Variable>();
22
	private int actVariableIndex = -1;
23
	
24
	public Variable nextVariable() {
25
		if (++actVariableIndex < variables.size()) {
26
			return variables.get(actVariableIndex);
27
		} else {
28
			return null;
29
		}
30
	}
31
	
32
	public void addParent(ClassDescription parent) {
33
		parents.add(parent);
34
		actParentIndex++;
35
	}
36
	
37
	public Variable getActVariable() {
38
		for (; actParentIndex >= 0; actParentIndex--) {
39
			Variable var = parents.get(actParentIndex).nextVariable();
40
			if (var != null) {
41
				return var;
42
			}
43
		}
44
		return null;
45
	}
46
	
47
	public void setVariables(List<Variable> variables) {
48
		this.variables = variables;
49
	}
50
	
51
	@SuppressWarnings("unchecked")
52
	public JSONObject getJSONObject() {
53
		int actIndex = ++actParentIndex;
54
		JSONObject obj = new JSONObject();
55
		
56
		JSONObject vars = new JSONObject();
57
		for (int j = 0; j < variables.size(); j++) {
58
			variables.get(j).putToJSON(vars);
59
		}
60
		obj.put("variables", vars);
61
		
62
		String i = "";
63
		if (flags == SC_SERIALIZABLE) {
64
			i = "java.io.Serializable";
65
		} else if (flags == SC_EXTERNALIZABLE) {
66
			i = "java.io.Externalizable";
67
		}
68
		obj.put("interface", i);
69
		
70
		String name;
71
		if (isClass) {
72
			name = "class";
73
		} else {
74
			name = "enum";
75
		}
76
		name += " " + className;
77
		obj.put("name", name);
78
		
79
		if ((actIndex + 1) < parents.size()) {
80
			obj.put("parent", parents.get(actIndex + 1).getJSONObject());
81
		}
82
		
83
		return obj;
84
	}
16 85
	
17 86
	@Override
18 87
	public String toString() {
88
		actParentIndex++;
19 89
		String retValue = "";
20 90
		
21 91
		if (isClass) {
......
25 95
		}
26 96
		
27 97
		retValue += " " + className;
98
		
99
		if ((actParentIndex + 1) < parents.size()) {
100
			retValue += " extends " + parents.get(actParentIndex + 1).className;
101
		}
102
		
28 103
		if (flags == SC_SERIALIZABLE) {
29 104
			retValue += " implements java.io.Serializable";
30 105
		} else if (flags == SC_EXTERNALIZABLE) {
......
36 111
			if (i > 0) {
37 112
				retValue += "\n";
38 113
			}
39
			retValue += "    " + variables.get(i) + ";";
114
			retValue += "    " + variables.get(i).toString() + ";";
115
		}
116
		retValue += "\n}\n";
117
		
118
		if ((actParentIndex + 1) < parents.size()) {
119
			retValue += parents.get(actParentIndex + 1).toString();
40 120
		}
41
		retValue += "\n}";
42 121
		
43 122
		return retValue;
44 123
	}
demo_mh/Deserializer/src/deserialize/DataType.java
1
package deserialize;
2

  
3
import java.util.HashMap;
4

  
5
public class DataType {
6

  
7
	public final static HashMap<Character, String> primTypeCodes;
8
	public final static HashMap<Character, String> objTypeCodes;
9
	
10
	static {
11
		primTypeCodes = new HashMap<Character, String>();
12
		primTypeCodes.put('B', "byte");
13
		primTypeCodes.put('C', "char");
14
		primTypeCodes.put('D', "double");
15
		primTypeCodes.put('F', "float");
16
		primTypeCodes.put('I', "integer");
17
		primTypeCodes.put('J', "long");
18
		primTypeCodes.put('S', "short");
19
		primTypeCodes.put('Z', "boolean");
20
		
21
		objTypeCodes = new HashMap<Character, String>();
22
		objTypeCodes.put('[', "array");
23
		objTypeCodes.put('L', "object");
24
    }
25
	
26
	public static boolean isPrimaryType(char type) {
27
		return primTypeCodes.containsKey(type);
28
	}
29
	
30
}
demo_mh/Deserializer/src/deserialize/Deserializer.java
1 1
package deserialize;
2 2

  
3
import java.io.BufferedInputStream;
4 3
import java.io.File;
5
import java.io.FileInputStream;
6
import java.io.IOException;
7
import java.io.ObjectInputStream;
8 4

  
9
import general.*;
5
import javafx.application.Application;
6
import javafx.geometry.Insets;
7
import javafx.geometry.Pos;
8
import javafx.scene.Parent;
9
import javafx.scene.Scene;
10
import javafx.scene.control.Button;
11
import javafx.scene.control.Label;
12
import javafx.scene.control.Separator;
13
import javafx.scene.layout.HBox;
14
import javafx.scene.layout.Pane;
15
import javafx.scene.layout.Priority;
16
import javafx.scene.layout.VBox;
17
import javafx.stage.FileChooser;
18
import javafx.stage.Stage;
10 19

  
11
public class Deserializer {
20
import serialize.Example;
21

  
22
public class Deserializer extends Application {
23
	
24
	private Stage stage;
25
	private File inputFile;
26
	private File outputFile;
27
	
28
	// TODO delete after deserializer debugging is complete...
29
	private boolean testing;
12 30
	
13 31
	public static void main(String[] args) {
14
		try {
15
			
16
			// Try to deserialize classically.
17
			FileInputStream fis = new FileInputStream(Constants.SERIALIZED_FILE);
18
			ObjectInputStream ois = new ObjectInputStream(fis);
19
			Deserializer d = (Deserializer) ois.readObject();
20
			System.out.println(d.toString());
21
			ois.close();
22
			
23
		} catch (IOException e) {
24
			
25
			// Stream error.
26
			System.out.println("Chyba pri otevirani (uzavirani) streamu.");
27
			e.printStackTrace();
28
			
29
		} catch (Exception e) {
30
			
31
			// Others: ClassNotFoundException, ClassCastException, ...
32
			// Usually due to problems with classical deserialization.
33
			byte buffer[];
34
			try {
35
				File f = new File(Constants.SERIALIZED_FILE);
36
				buffer = new byte[(int) f.length()];
37
				
38
				BufferedInputStream fis = new BufferedInputStream(new FileInputStream(f));
39
		        fis.read(buffer);
40
		        fis.close();
41
		        
42
		        System.out.println("Doslo k chybe pri deserializaci.");
43
				System.out.println("Spoustim univerzalni deserializer.");
44
				
45
				ToJSON thread = new ToJSON(buffer);
46
				thread.start();
47
				try {
48
					thread.join();
49
					System.out.println("JSON byl vytvoren.");
50
				} catch (InterruptedException e1) {
51
					e1.printStackTrace();
52
				}
53
				
54
		    } catch (IOException e1) {
55
		        e1.printStackTrace();
56
		    }
57
			
32
		launch(args);
33
	}
34

  
35
	@Override
36
	public void init() throws Exception {
37
		super.init();
38
		testing = false;
39
	}
40
	
41
	@Override
42
	public void start(Stage stage) throws Exception {
43
		this.stage = stage;
44
		stage.setTitle("Java object universal deserializer");
45
		stage.setScene(createScene());
46
		stage.setMinWidth(400);
47
		stage.show();
48
	}
49
	
50
	private Scene createScene() {
51
		return new Scene(createLayout());
52
	}
53
	
54
	private Parent createLayout() {
55
		VBox layout = new VBox();
56
		layout.setPadding(new Insets(10.0));
57
		layout.setSpacing(10.0);
58
		
59
		Label forDefaultBinFile = new Label("Chcete vytvo?it defaultn? bin?rn? soubor?");
60
		Button createBinFile = new Button("Vytvo?it");
61
		createBinFile.setOnAction(event -> {
62
			FileChooser fCh = new FileChooser();
63
			fCh.setInitialDirectory(new File("."));
64
			fCh.getExtensionFilters().add(new FileChooser.ExtensionFilter("Binary Files", "*.out"));
65
			File file = fCh.showSaveDialog(stage);
66
			if (file != null) {
67
				createSerializedFile(file);
68
			}
69
		});
70
		final Pane spacer = new Pane();
71
	    HBox.setHgrow(spacer, Priority.ALWAYS);
72
		HBox header = new HBox();
73
		header.setAlignment(Pos.CENTER_LEFT);
74
		header.getChildren().add(forDefaultBinFile);
75
		header.getChildren().add(spacer);
76
		header.getChildren().add(createBinFile);
77
		
78
		Label forInputFile = new Label("Soubor k deserializaci:");
79
		Label inputFile = new Label("    Je?t? nebyl vybr?n ??dn? soubor...");
80
		inputFile.setStyle("-fx-font-style: italic;");
81
		VBox forInput = new VBox();
82
		forInput.getChildren().add(forInputFile);
83
		forInput.getChildren().add(inputFile);
84
		
85
		Label forOutputFile = new Label("V?stupn? soubor:");
86
		Label outputFile = new Label("    Je?t? nebyl vybr?n ??dn? soubor...");
87
		outputFile.setStyle("-fx-font-style: italic;");
88
		VBox forOutput = new VBox();
89
		forOutput.getChildren().add(forOutputFile);
90
		forOutput.getChildren().add(outputFile);
91
		
92
		Button convert = new Button("P?ev?st");
93
		convert.setOnAction(event -> {
94
			ToJSON thread = new ToJSON(testing ? new File("data.out") : this.inputFile, this.outputFile);
95
			thread.start();
96
		});
97
		convert.setDisable(!testing);
98
		Button setInputFile = new Button("Vstupn? soubor");
99
		setInputFile.setOnAction(event -> {
100
			FileChooser fCh = new FileChooser();
101
			fCh.setInitialDirectory(new File("."));
102
			// The input can be a zip file or file without a specific extension -> file chooser without extension filters...
103
			// fCh.getExtensionFilters().add(new FileChooser.ExtensionFilter("Binary Files", "*.out"));
104
			File file = fCh.showOpenDialog(stage);
105
			if (file != null) {
106
				this.inputFile = file;
107
				inputFile.setText(this.inputFile == null ? "" : this.inputFile.getAbsolutePath());
108
				inputFile.setStyle("-fx-font-weight: bold;");
109
				convert.setDisable(this.inputFile == null || this.outputFile == null);
110
			}
111
		});
112
		Button setOutputFile = new Button("V?stupn? soubor");
113
		setOutputFile.setOnAction(event -> {
114
			FileChooser fCh = new FileChooser();
115
			fCh.setInitialDirectory(new File("."));
116
			fCh.getExtensionFilters().add(new FileChooser.ExtensionFilter("JSON Files", "*.json"));
117
			File file = fCh.showSaveDialog(stage);
118
			if (file != null) {
119
				this.outputFile = file;
120
				outputFile.setText(this.outputFile == null ? "" : this.outputFile.getAbsolutePath());
121
				outputFile.setStyle("-fx-font-weight: bold;");
122
				convert.setDisable(this.inputFile == null || this.outputFile == null);
123
			}
124
		});
125
		HBox footer = new HBox();
126
		footer.setSpacing(10.0);
127
		footer.setAlignment(Pos.CENTER_RIGHT);
128
		footer.getChildren().add(setInputFile);
129
		footer.getChildren().add(setOutputFile);
130
		footer.getChildren().add(convert);
131
		
132
		layout.getChildren().add(header);
133
		layout.getChildren().add(new Separator());
134
		layout.getChildren().add(forInput);
135
		layout.getChildren().add(forOutput);
136
		layout.getChildren().add(footer);
137
		
138
		return layout;
139
	}
140
	
141
	private void createSerializedFile(File file) {
142
		String title = "Vytvo?en? defaultn?ho souboru";
143
		if (Example.serialize(file)) {
144
			Report.info(title, null, "Vytvo?en? prob?hlo v po??dku.");
145
		} else {
146
			Report.error(title, null, "Vytvo?en? souboru se nepovedlo.");
58 147
		}
59 148
	}
60 149
	
demo_mh/Deserializer/src/deserialize/Grammar.java
1 1
package deserialize;
2 2

  
3
import java.io.ByteArrayInputStream;
4
import java.io.DataInputStream;
5
import java.nio.ByteBuffer;
6 3
import java.util.ArrayList;
7 4
import java.util.HashMap;
8 5
import java.util.List;
9 6

  
7
import org.json.simple.JSONObject;
8

  
10 9
/**
11 10
 * https://docs.oracle.com/javase/7/docs/platform/serialization/spec/protocol.html
12 11
 */
......
14 13
	
15 14
	private final static short STREAM_MAGIC = (short) 0xACED;
16 15
	private final static short STREAM_VERSION = 5;
17
	private final static byte TC_NULL = (byte) 0x70;
18
	private final static byte TC_REFERENCE = (byte) 0x71;
19
	private final static byte TC_CLASSDESC = (byte) 0x72;
20
	private final static byte TC_OBJECT = (byte) 0x73;
21
	private final static byte TC_STRING = (byte) 0x74;
22
	private final static byte TC_ARRAY = (byte) 0x75;
23
	private final static byte TC_CLASS = (byte) 0x76;
24
	private final static byte TC_BLOCKDATA = (byte) 0x77;
25
	private final static byte TC_ENDBLOCKDATA = (byte) 0x78;
26
	private final static byte TC_RESET = (byte) 0x79;
27
	private final static byte TC_BLOCKDATALONG = (byte) 0x7A;
28
	private final static byte TC_EXCEPTION = (byte) 0x7B;
29
	private final static byte TC_LONGSTRING = (byte) 0x7C;
30
	private final static byte TC_PROXYCLASSDESC = (byte) 0x7D;
31
	private final static byte TC_ENUM = (byte) 0x7E;
16
	private final static byte TC_NULL = 0x70;
17
	private final static byte TC_REFERENCE = 0x71;
18
	private final static byte TC_CLASSDESC = 0x72;
19
	private final static byte TC_OBJECT = 0x73;
20
	private final static byte TC_STRING = 0x74;
21
	private final static byte TC_ARRAY = 0x75;
22
	private final static byte TC_CLASS = 0x76;
23
	private final static byte TC_BLOCKDATA = 0x77;
24
	private final static byte TC_ENDBLOCKDATA = 0x78;
25
	private final static byte TC_RESET = 0x79;
26
	private final static byte TC_BLOCKDATALONG = 0x7A;
27
	private final static byte TC_EXCEPTION = 0x7B;
28
	private final static byte TC_LONGSTRING = 0x7C;
29
	private final static byte TC_PROXYCLASSDESC = 0x7D;
30
	private final static byte TC_ENUM = 0x7E;
32 31
	private final static int baseWireHandle = (int) 0x7E0000;
33 32
	
34
	final static byte SC_WRITE_METHOD = (byte) 0x01; // if SC_SERIALIZABLE
35
	final static byte SC_BLOCK_DATA = (byte) 0x08; // if SC_EXTERNALIZABLE
36
	final static byte SC_SERIALIZABLE = (byte) 0x02;
37
	final static byte SC_EXTERNALIZABLE = (byte) 0x04;
38
	final static byte SC_ENUM = (byte) 0x10;
33
	final static byte SC_WRITE_METHOD = 0x01; // if SC_SERIALIZABLE
34
	final static byte SC_BLOCK_DATA = 0x08; // if SC_EXTERNALIZABLE
35
	final static byte SC_SERIALIZABLE = 0x02;
36
	final static byte SC_EXTERNALIZABLE = 0x04;
37
	final static byte SC_ENUM = 0x10;
39 38

  
40
	HashMap<Character, String> primTypeCodes;
41
	HashMap<Character, String> objTypeCodes;
42
	
43
	
44
	// Note. (XXX) This token has the XXX type specified
45
	
46
	
47 39
	private List<Byte> buffer;
48
	public Grammar(List<Byte> buffer) {
49
		this.buffer = buffer;
50
		
51
		primTypeCodes = new HashMap<Character, String>();
52
		primTypeCodes.put('B', "byte");
53
		primTypeCodes.put('C', "char");
54
		primTypeCodes.put('D', "double");
55
		primTypeCodes.put('F', "float");
56
		primTypeCodes.put('I', "integer");
57
		primTypeCodes.put('J', "long");
58
		primTypeCodes.put('S', "short");
59
		primTypeCodes.put('Z', "boolean");
60
		
61
		objTypeCodes = new HashMap<Character, String>();
62
		objTypeCodes.put('[', "array");
63
		objTypeCodes.put('L', "object");
40
	public Grammar(byte buffer[]) {
41
		this.buffer = new ArrayList<Byte>();
42
		for (int i = 0; i < buffer.length; i++) {
43
			this.buffer.add(buffer[i]);
44
		}
64 45
	}
65 46
	
66 47
	
......
104 85
		return str;
105 86
	}
106 87
	
107
	
108
	
109
	
110
	
111 88
	public String readUtf() {
112 89
		short length = readShort();
113 90
		return readString(length);
......
118 95
		return readString(length);
119 96
	}
120 97
	
98
	public float readFloat() {
99
		return Float.intBitsToFloat(readInt());
100
	}
121 101
	
102
	public double readDouble() {
103
		return Double.longBitsToDouble(readLong());
104
	}
122 105
	
106
	public boolean readBoolean() {
107
		// TODO zkontrolovat
108
		return readByte() != 0;
109
	}
123 110
	
124 111
	
112
	List<ClassDescription> classes = new ArrayList<ClassDescription>();
113
	ClassDescription actClass = null;
125 114
	
126
	
127
	
128
	public void start() {
115
	public JSONObject process() {
129 116
		System.out.println("Kontrola hlavicky souboru: " + (readShort() == STREAM_MAGIC && readShort() == STREAM_VERSION));
117
		
130 118
		while (!buffer.isEmpty()) {
131
			object();
119
			try {
120
				object();
121
			} catch (Exception e) {
122
				break;
123
			}
132 124
		}
125
		
126
		return classes.get(0).getJSONObject();
127
		// System.out.println(classes.get(0).toString());
133 128
	}
134 129
	
135 130
	// FOR VALUES : 
......
185 180
			case TC_ARRAY: {
186 181
					System.out.println("X3");
187 182
					ClassDescription desc = (ClassDescription) object();
188
					int size = readInt();
189
					retValue = desc.className + "[" + size + "]";
183
					// TODO int size = readInt();
184
					retValue = desc.className;; // TODO + "[" + size + "]";
190 185
				}
191 186
				break;
192 187
			case TC_STRING: {
188
					System.out.println("X4");
193 189
					String str = readUtf();
194
					System.out.println("X4 " + str);
195 190
					retValue = str;
196 191
				}
197 192
				break;
......
218 213
					desc.serialVersionUID = readLong();
219 214
					desc.flags = readByte();
220 215
					desc.isClass = true;
221
					desc.variables = fields();
216
					desc.setVariables(fields());
217
					
218
					if (actClass == null) {
219
						actClass = desc;
220
					}
221
					// TODO
222
					actClass.addParent(desc);
223
					
222 224
					// TODO object(null); classDesc();
223
					System.out.println(desc.toString());
225
					// TODO System.out.println(desc.toString());
224 226
					retValue = desc;
225 227
				}
226 228
				break;
......
237 239
					// TODO
238 240
					System.out.println("---NULL---");
239 241
					retValue = null;
242
					
243
					classes.add(actClass);
244
					actClass = null;
245
					while (true) {
246
						Variable actVar = classes.get(classes.size() - 1).getActVariable();
247
						if (actVar == null) {
248
							break;
249
						}
250
						
251
						switch (actVar.getType()) {
252
						case 'B': actVar.setValue(readByte()); break;
253
						case 'C': actVar.setValue((char) readByte()); break;
254
						case 'D': actVar.setValue(readDouble()); break;
255
						case 'F': actVar.setValue(readFloat()); break;
256
						case 'I': actVar.setValue(readInt()); break;
257
						case 'J': actVar.setValue(readLong()); break;
258
						case 'S': actVar.setValue(readShort()); break;
259
						case 'Z': actVar.setValue(readBoolean()); break;
260
						case '[':
261
							// int count = readShort();
262
							// TODO
263
							for (int i = 0; i < 3; i++) {
264
								object();
265
								// System.out.println("DEF: " + " " + (char) xxx + " " + xxx);
266
							}
267
							int count = readInt();
268
							System.out.println("------------- VELIKOST POLE = " + count);
269
							for (int i = 0; i < count; i++) {
270
								System.out.println("------------- HODNOTA = " + (char) readShort());
271
							}
272
							//actVar.setValue(readByte());
273
							break;
274
						case 'L': actVar.setValue(object()); break;
275
						}
276
					}
240 277
				}
241 278
				break;
242 279
			case TC_REFERENCE: {
......
286 323
		return retValue;
287 324
	}
288 325
	
289
	public List<String> fields() {
290
		List<String> rows = new ArrayList<String>();
326
	public List<Variable> fields() {
327
		List<Variable> variables = new ArrayList<Variable>();
291 328
		
292 329
		short count = readShort();
293 330
		for (int i = 0; i < count; i++) {
294 331
			char type = (char) readByte();
295
			
296
			String row;
297
			if (primTypeCodes.containsKey(type)) {
298
				row = primTypeCodes.get(type) + " " + readUtf();
299
			} else {
300
				String variable = readUtf();
301
				String dataType = (String) object();
302
				dataType = dataType.substring(1);
303
				
304
				if (primTypeCodes.containsKey(dataType.charAt(0)))
305
					dataType = primTypeCodes.get(dataType.charAt(0)); // remove type
306
				
307
				row = dataType + " " + variable;
308
				if (objTypeCodes.get(type) == "array")
309
					row += "[]";
310
			}
311
			
312
			rows.add(row);
332
			String variable = readUtf();
333
			String typeName = null;
334
			if (!DataType.isPrimaryType(type))
335
				typeName = (String) object();
336
			variables.add(new Variable(type, variable, typeName));
313 337
		}
314 338
		
315
		return rows;
339
		return variables;
316 340
	}
317 341
	
318 342
}
demo_mh/Deserializer/src/deserialize/Report.java
1
package deserialize;
2
import com.sun.javafx.stage.StageHelper;
3

  
4
import javafx.application.Platform;
5
import javafx.geometry.Rectangle2D;
6
import javafx.scene.control.Alert;
7
import javafx.scene.control.Alert.AlertType;
8
import javafx.stage.Screen;
9

  
10
public class Report {
11
	
12
	private static final int HEIGHT = 200;
13
	private static final int WIDTH = 500;
14
	
15
	private static void setPosition(Alert alert) {
16
		if (StageHelper.getStages() != null && StageHelper.getStages().size() != 0) {
17
			if (Screen.getPrimary() != null && Screen.getPrimary().getVisualBounds() != null) {
18
				Rectangle2D primScreenBounds = Screen.getPrimary().getVisualBounds();
19
				alert.setX((primScreenBounds.getWidth() - WIDTH - 20) / 2);
20
		        alert.setY((primScreenBounds.getHeight() - HEIGHT - 20) / 3);
21
			}
22
			alert.initOwner(StageHelper.getStages().get(StageHelper.getStages().size() - 1));
23
		}
24
	}
25
	
26
	private static Alert createAlert(AlertType type, String title, String header, String content) {
27
		Alert alert = new Alert(type);
28
		alert.setResizable(true);
29
		alert.getDialogPane().setPrefWidth(WIDTH);
30
		alert.setTitle(title);
31
		alert.setHeaderText(header);
32
		alert.setContentText(content);
33
		setPosition(alert);
34
		return alert;
35
	}
36
	
37
	public static void error(String title, String header, String content) {
38
		Platform.runLater(()->{
39
			createAlert(AlertType.WARNING, title, header, content).showAndWait();
40
        });
41
	}
42
	
43
	public static void info(String title, String header, String content) {
44
		Platform.runLater(()->{
45
			createAlert(AlertType.INFORMATION, title, header, content).showAndWait();
46
        });
47
	}
48
	
49
	public static boolean confirm(String title, String header, String content) {
50
		Alert alert = createAlert(AlertType.CONFIRMATION, title, header, content);
51
		alert.showAndWait();
52
		if (alert.getResult().getText().equals("OK")) {
53
			return true;
54
		} else {
55
			return false;
56
		}
57
	}
58
	
59
}
demo_mh/Deserializer/src/deserialize/ToJSON.java
1 1
package deserialize;
2 2

  
3
import java.io.BufferedInputStream;
3 4
import java.io.BufferedWriter;
5
import java.io.ByteArrayInputStream;
6
import java.io.File;
7
import java.io.FileInputStream;
4 8
import java.io.FileWriter;
5 9
import java.io.IOException;
6
import java.nio.ByteBuffer;
7
import java.util.ArrayList;
8
import java.util.HashMap;
9
import java.util.List;
10
import java.util.concurrent.atomic.AtomicInteger;
10
import java.io.ObjectInputStream;
11
import java.util.zip.ZipEntry;
12
import java.util.zip.ZipInputStream;
11 13

  
12
import org.json.simple.JSONArray;
13 14
import org.json.simple.JSONObject;
14 15

  
15
import general.Constants;
16

  
17 16
public class ToJSON extends Thread {
18 17
	
18
	private File input;
19
	private File output;
20
	
19 21
	private byte buffer[];
20 22
	
21
	public ToJSON(byte buffer[]) {
22
		this.buffer = buffer;
23
	public ToJSON(File inputFilename, File outputFilename) {
24
		this.input = inputFilename;
25
		this.output = outputFilename;
23 26
	}
24 27
	
25 28
	@Override
26 29
	public void run() {
27 30
		super.run();
28 31
		
29
		List<Byte> buffer = new ArrayList<Byte>();
30
		for (int i = 0; i < this.buffer.length; i++) {
31
			buffer.add(this.buffer[i]);
32
		buffer = readByteArray();
33
		if (buffer == null) {
34
			// TODO Chyba na??t?n? dat
35
		} else if (deserializeClassically()) {
36
			// TODO Chyba klasick? deserializace
37
		} else {
38
			// Univerzalni deserializer.
39
			convert();
32 40
		}
41
	}
42
	
43
	private void convert() {
44
		System.out.println("Spoustim univerzalni deserializer.");
33 45
		
34 46
		Grammar g = new Grammar(buffer);
35
		g.start();
36

  
37
		/*for (int i = 0; i < buffer.length; i++) {
38
			if (buffer[i] == TC_CLASSDESC) {
39
				// Class name
40
				int nameLength = Formatter.createInt(buffer[++i], buffer[++i]);
41
				String name = new String(buffer, ++i, nameLength);
42
				i += nameLength - 1;
43
				System.out.println(name);
44
				
45
				// UID
46
				ByteBuffer toLong = ByteBuffer.allocate(Long.BYTES);
47
				toLong.put(buffer, i + 1, 8);
48
				toLong.flip();
49
		        System.out.println(toLong.getLong());
50
		        
51
		        // implements ...
52
				i += 9;
53
				System.out.println(buffer[i] == SC_SERIALIZABLE);
54
				
55
				// Variables
56
				int vCount = Formatter.createInt(buffer[++i], buffer[++i]);
57
				for (int j = 0; j < vCount; j++) {
58
					// Type
59
					char vType = (char) (buffer[++i]);
60
					// Name
61
					int vNameLength = Formatter.createInt(buffer[++i], buffer[++i]);
62
					String vName = new String(buffer, ++i, vNameLength);
63
					i += vNameLength - 1;
64
					// toString()
65
					System.out.println(typeCodes.get(vType) + " " + new String(vName));
66
				}
67
				
68
				// TODO
69
				System.out.println(buffer[++i] == TC_ENDBLOCKDATA);
70
			}
71
		}*/
47
		JSONObject results = g.process();
48
		
49
		save(results);
50
		
51
		System.out.println("JSON byl vytvoren.");
72 52
	}
73 53
	
74
	@SuppressWarnings("unchecked")
75
	private void save() {
54
	private boolean deserializeClassically() {
55
		try {
56
			
57
			// Try to deserialize classically.
58
			ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(buffer));
59
			@SuppressWarnings("unused")
60
			Deserializer d = (Deserializer) ois.readObject();
61
			System.out.println("Klasicka deserializace probehla v poradku.");
62
			ois.close();
63
			
64
		} catch (IOException e) {
65
			
66
			// Stream error.
67
			System.out.println("Chyba pri otevirani (uzavirani) streamu pri pokusu o klasickou deserializaci.");
68
			e.printStackTrace();
69
			
70
		} catch (Exception e) {
71
			
72
			// Others: ClassNotFoundException, ClassCastException, ...
73
			// Usually due to problems with classical deserialization.
74
			return false;
75
			
76
		}
77
		return true;
78
	}
79
	
80
	private byte[] readByteArray() {
81
		byte array[] = null;
82
		
76 83
		/*
77
		JSONObject countryObj = new JSONObject();
78
        countryObj.put("Name", "India");
79
        countryObj.put("Population", new Integer(1000000));
80
 
81
        JSONArray listOfStates = new JSONArray();
82
        listOfStates.add("Madhya Pradesh");
83
        listOfStates.add("Maharastra");
84
        listOfStates.add("Rajasthan");
85
 
86
        countryObj.put("States", listOfStates);
87
 
84
		 * Note.
85
		 * For ZIP - the first four bytes should be one of the following combinations:
86
		 *     50 4B 03 04
87
		 *     50 4B 05 06 (empty archive)
88
		 *     50 4B 07 08 (spanned archive)
89
		 * Source: https://en.wikipedia.org/wiki/List_of_file_signatures
90
		 */
91
		ZipInputStream zipInputStream = null;
92
		ZipEntry entry = null;
93
	    try {
94
	    	zipInputStream = new ZipInputStream(new FileInputStream(input));
95
	    	entry = zipInputStream.getNextEntry();
96
			System.out.println("Velikost ZIP dat je " + entry.getSize() + "B.");
97
		} catch (Exception e) {
98
			System.out.println("Soubor neni zazipovany...");
99
		}
100
	    
101
	    try {
102
	    	if (entry != null) {
103
		    	array = new byte[(int) entry.getSize()];
104
				zipInputStream.read(array);
105
				zipInputStream.close();
106
		    } else {
107
		    	array = new byte[(int) input.length()];
108
				BufferedInputStream bis = new BufferedInputStream(new FileInputStream(input));
109
				bis.read(array);
110
				bis.close();
111
		    }
112
	    	System.out.println("Byty ze souboru byly v poradku nacteny.");
113
	    } catch (IOException e) {
114
	    	System.out.println("Pri nacitani bytu doslo k chybe.");
115
	    	return null;
116
	    }
117
	    
118
	    return array;
119
	}
120
	
121
	private void save(JSONObject obj) {
88 122
        try {
89
            // Writing to a file
90
            FileWriter fw = new FileWriter(Constants.JSON_FILE);
123
            FileWriter fw = new FileWriter(output);
91 124
            BufferedWriter bw = new BufferedWriter(fw);
92
            System.out.println("Zapisuji JSON objekt do souboru.");
93
            bw.write(countryObj.toJSONString());
125
            bw.write(obj.toJSONString());
94 126
            bw.flush();
95 127
            bw.close();
128
            Report.info("JSON", null, "Ulo?en? souboru prob?hlo v po??dku.");
96 129
        } catch (IOException e) {
97 130
            e.printStackTrace();
131
            Report.info("JSON", null, "P?i ukl?d?n? souboru nastala chyba.");
98 132
        }
99
        */
100 133
	}
101 134
	
102 135
}
demo_mh/Deserializer/src/deserialize/Variable.java
1
package deserialize;
2

  
3
import org.json.simple.JSONObject;
4

  
5
public class Variable {
6
	
7
	private char type;
8
	private String variable;
9
	private String typeName;
10
	private Object value = null;
11
	
12
	public Variable(char type, String variable, String typeName) {
13
		this.type = type;
14
		this.variable = variable;
15
		this.typeName = typeName;
16
		
17
		if (!DataType.primTypeCodes.containsKey(type)) {
18
			if (typeName.contains("/")) {
19
				typeName = typeName.substring(typeName.lastIndexOf("/") + 1, typeName.length() - 1);
20
			} else {
21
				System.out.println(typeName);
22
				typeName = typeName.substring(1);
23
			}
24

  
25
			if (typeName.length() == 1 && DataType.primTypeCodes.containsKey(typeName.charAt(0)))
26
				typeName = DataType.primTypeCodes.get(typeName.charAt(0)); // remove type
27
			
28
			this.typeName = typeName;
29
		}
30
	}
31
	
32
	public char getType() {
33
		return type;
34
	}
35
	
36
	public boolean isValueSet() {
37
		return value != null;
38
	}
39
	
40
	public void setValue(Object value) {
41
		this.value = value;
42
	}
43
	
44
	@SuppressWarnings("unchecked")
45
	public void putToJSON(JSONObject obj) {
46
		if (value != null) {
47
			if (value.getClass().toString().equals(ClassDescription.class.toString())) {
48
				ClassDescription desc = (ClassDescription) value;
49
				obj.put(variable, desc.getJSONObject());
50
			} else {
51
				obj.put(variable, value);
52
			}
53
		} else {
54
			obj.put(variable, "NON_IMPLEMENTED");
55
		}
56
	}
57
	
58
	@Override
59
	public String toString() {
60
		String result;
61
		
62
		if (DataType.primTypeCodes.containsKey(type)) {
63
			result = DataType.primTypeCodes.get(type) + " " + variable;
64
		} else {
65
			result = typeName + " " + variable;
66
			if (DataType.objTypeCodes.get(type) == "array")
67
				result += "[]";
68
		}
69
		
70
		if (value != null) {
71
			result += " = ";
72
			if (value.getClass().toString().equals(ClassDescription.class.toString())) {
73
				ClassDescription desc = (ClassDescription) value;
74
				result += desc.toString();
75
			} else {
76
				result += value;
77
			}
78
		}
79
		
80
		return result;
81
	}
82

  
83
}
demo_mh/Deserializer/src/general/Constants.java
1
package general;
2

  
3
public class Constants {
4

  
5
	public static String SERIALIZED_FILE = "data.out";
6
	public static String JSON_FILE = "results.json";
7
	
8
}
demo_mh/Deserializer/src/serialize/Contain.java
6 6

  
7 7
	private static final long serialVersionUID = 1L;
8 8
	
9
	char array[] = new char[] {'W', 'X', 'Y', 'Z'};
9
	// TODO jeste nefunguje char array[] = new char[] {'W', 'X', 'Y', 'Z'};
10
	float realNum = 15.6f;
10 11
	
11 12
}
demo_mh/Deserializer/src/serialize/Example.java
1 1
package serialize;
2 2

  
3
import java.io.File;
3 4
import java.io.FileOutputStream;
4 5
import java.io.ObjectOutputStream;
5 6
import java.io.Serializable;
6 7

  
7
import general.*;
8

  
9 8
public class Example extends Parent implements Serializable {
10 9
	
11 10
	private static final long serialVersionUID = 1L;
12
	
13
	private int numberx = 7;
11
	public static String SERIALIZED_FILE = "data.out";
12

  
13
	private int numberX = 7;
14 14
	Contain variable = new Contain();
15 15
	float x = 10;
16
	// TODO chyba char y[] = new char[5];
17
	// char y[] = {'B'};
18 16
	
19 17
	public long getNumber() {
20
		return numberx;
18
		return numberX;
21 19
	}
22

  
23
	public static void main(String[] args) {
20
	
21
	public static boolean serialize(File file) {
22
		boolean retValue = false;
24 23
		try {
25
			FileOutputStream fos = new FileOutputStream(Constants.SERIALIZED_FILE);
24
			FileOutputStream fos = new FileOutputStream(file);
26 25
			ObjectOutputStream oos = new ObjectOutputStream(fos);
27 26
			Example s = new Example();
28 27
			oos.writeObject(s);
29 28
			oos.flush();
30 29
			oos.close();
31
			System.out.println("File " + Constants.SERIALIZED_FILE + " created.");
30
			System.out.println("File " + SERIALIZED_FILE + " created.");
32 31
			
33 32
			/*
33
			--- DESERIALIZATION ---
34 34
			FileInputStream fis = new FileInputStream(Constants.FILE_NAME);
35 35
			ObjectInputStream ois = new ObjectInputStream(fis);
36 36
			s = (Example) ois.readObject();
37 37
			System.out.println("DATA: " + s.string + " " + s.number + " " + Arrays.toString(s.variable.array));
38 38
			ois.close();
39 39
			*/
40
			
41
			retValue =  true;
40 42
		} catch (Exception e) {
41 43
			e.printStackTrace();
42 44
		}
45
		return retValue;
46
	}
47

  
48
	public static void main(String[] args) {
49
		serialize(new File(SERIALIZED_FILE));
43 50
	}
44 51

  
45 52
}
demo_mh/Deserializer/src/serialize/Parent.java
6 6

  
7 7
	private static final long serialVersionUID = 1L;
8 8
	
9
	String string = "ABCD";
9
	String str = "ABCD";
10 10
	
11 11
}

Také k dispozici: Unified diff