hanze/game-client

src/main/java/nl/isygameclient/network/EventParser.java in main
Repositories | Summary | Log | Files

EventParser.java (2114B) download


 1package nl.isygameclient.network;
 2
 3import java.util.HashMap;
 4import java.util.LinkedList;
 5
 6public class EventParser {
 7	private final String str;
 8
 9	private int index = 0;
10
11	private void stripLeft() {
12		while (Character.isSpaceChar(str.charAt(index)))
13			index++;
14	}
15
16	public EventParser(String str) {
17		this.str = str;
18	}
19
20	public Object parseData() throws GameClientException {
21		try {
22			stripLeft();
23
24			if (index >= str.length())
25				return null;
26
27			switch (str.charAt(index)) {
28				case '"':
29					index++;
30					var string = str.substring(index, str.indexOf("\"", index));
31					index	   = str.indexOf("\"", index) + 1;
32					return string;
33				case '[':
34					index++;
35					var array = new LinkedList<Object>();
36					for (;;) {
37						array.add(parseData());
38						stripLeft();
39						if (str.charAt(index) == ']') {
40							index++;
41							return array;
42						} else if (str.charAt(index) == ',') {
43							index++;
44						} else {
45							throw new GameClientException(String.format("invalid server response: unexpected '%c' at %d in '%s'", str.charAt(index), index, str));
46						}
47					}
48				case '{':
49					index++;
50					var map = new HashMap<String, Object>();
51					for (;;) {
52						stripLeft();
53						var key = str.substring(index, str.indexOf(":", index)).toLowerCase();
54
55						index = str.indexOf(":", index) + 1;
56						map.put(key, parseData());
57						stripLeft();
58						if (str.charAt(index) == '}') {
59							index++;
60							return map;
61						} else if (str.charAt(index) == ',') {
62							index++;
63						} else {
64							throw new GameClientException(String.format("invalid server response: unexpected '%c' at %d in '%s'", str.charAt(index), index, str));
65						}
66					}
67				default:
68					if (index != 0)
69						throw new GameClientException(String.format("invalid server response: unexpected '%c' at %d in '%s'", str.charAt(index), index, str));
70					index = str.length();
71					return str;
72			}
73		} catch (Exception ext) {
74			throw new GameClientException(String.format("invalid server response: unexpected '%c' at %d in '%s'", str.charAt(index), index, str));
75		}
76	}
77
78	public void reset() {
79		index = 0;
80	}
81}