aboutsummaryrefslogtreecommitdiff
path: root/juick-www/src/main/java/ru/sape/SerializedPhpParser.java
blob: a24551b9d80ba3ac89e0b87647d09108977933c2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/*
Copyright (c) 2007 Zsolt Szász <zsolt at lorecraft dot com>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package ru.sape;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Deserializes a serialized PHP data structure into corresponding Java objects. It supports
 * the integer, float, boolean, string primitives that are mapped to their Java
 * equivalent, plus arrays that are parsed into <code>Map</code> instances and objects
 * that are represented by {@link SerializedPhpParser.PhpObject} instances.
 * <p>
 * Example of use:
 * <pre>
 *      String input = "O:8:"TypeName":1:{s:3:"foo";s:3:"bar";}";
 *      SerializedPhpParser serializedPhpParser = new SerializedPhpParser(input);
 *      Object result = serializedPhpParser.parse();
 * </pre>
 *
 * The <code>result</code> object will be a <code>PhpObject</code> with the name "TypeName" and
 * the attribute "foo" = "bar".
 */
class SerializedPhpParser {

    private final String input;
    private int index;
    private boolean assumeUTF8 = true;
    private Pattern acceptedAttributeNameRegex = null;

    public SerializedPhpParser(String input) {
        this.input = input;
    }

    public Object parse() {
        char type = input.charAt(index);
        switch (type) {
            case 'i':
                index += 2;
                return parseInt();
            case 'd':
                index += 2;
                return parseFloat();
            case 'b':
                index += 2;
                return parseBoolean();
            case 's':
                index += 2;
                return parseString();
            case 'a':
                index += 2;
                return parseArray();
            case 'O':
                index += 2;
                return parseObject();
            case 'N':
                index += 2;
                return NULL;
            default:
                throw new IllegalStateException("Encountered unknown type [" + type + "], str=" + input.substring(index));
        }
    }

    private Object parseObject() {
        PhpObject phpObject = new PhpObject();
        int strLen = readLength();
        phpObject.name = input.substring(index, index + strLen);
        index = index + strLen + 2;
        int attrLen = readLength();
        for (int i = 0; i < attrLen; i++) {
            Object key = parse();
            Object value = parse();
            if (isAcceptedAttribute(key)) {
                phpObject.attributes.put(key, value);
            }
        }
        index++;
        return phpObject;
    }

    private Map<Object, Object> parseArray() {
        int arrayLen = readLength();
        Map<Object, Object> result = new LinkedHashMap<Object, Object>();
        for (int i = 0; i < arrayLen; i++) {
            Object key = parse();
            Object value = parse();
            if (isAcceptedAttribute(key)) {
                result.put(key, value);
            }
        }
        index++;
        return result;
    }

    private boolean isAcceptedAttribute(Object key) {
        if (acceptedAttributeNameRegex == null) {
            return true;
        }
        if (!(key instanceof String)) {
            return true;
        }
        return acceptedAttributeNameRegex.matcher((String) key).matches();
    }

    private int readLength() {
        int delimiter = input.indexOf(':', index);
        int arrayLen = Integer.valueOf(input.substring(index, delimiter));
        index = delimiter + 2;
        return arrayLen;
    }

    /**
     * Assumes strings are utf8 encoded
     *
     * @return
     */
    private String parseString() {
        int strLen = readLength();

        int utfStrLen = 0;
        int byteCount = 0;
        while (byteCount != strLen) {
            char ch = input.charAt(index + utfStrLen++);

            /*
            if (ch == '\'') {
            utfStrLen -= 1;
            break;
            }
             */

            if (assumeUTF8) {
                if ((ch >= 0x0001) && (ch <= 0x007F)) {
                    byteCount++;
                } else if (ch > 0x07FF) {
                    byteCount += 3;
                } else {
                    byteCount += 2;
                }
            } else {
                byteCount++;
            }
        }
        String value = input.substring(index, index + utfStrLen);
        index = index + utfStrLen + 2;
        return value;
    }

    private Boolean parseBoolean() {
        int delimiter = input.indexOf(';', index);
        String value = input.substring(index, delimiter);
        if (value.equals("1")) {
            value = "true";
        } else if (value.equals("0")) {
            value = "false";
        }
        index = delimiter + 1;
        return Boolean.valueOf(value);
    }

    private Double parseFloat() {
        int delimiter = input.indexOf(';', index);
        String value = input.substring(index, delimiter);
        index = delimiter + 1;
        return Double.valueOf(value);
    }

    private Integer parseInt() {
        int delimiter = input.indexOf(';', index);
        String value = input.substring(index, delimiter);
        index = delimiter + 1;
        return Integer.valueOf(value);
    }

    public void setAcceptedAttributeNameRegex(String acceptedAttributeNameRegex) {
        this.acceptedAttributeNameRegex = Pattern.compile(acceptedAttributeNameRegex);
    }
    public static final Object NULL = new Object() {

        @Override
        public String toString() {
            return "NULL";
        }
    };

    /**
     * Represents an object that has a name and a map of attributes
     */
    public static class PhpObject {

        public String name;
        public Map<Object, Object> attributes = new HashMap<Object, Object>();

        @Override
        public String toString() {
            return "\"" + name + "\" : " + attributes.toString();
        }
    }
}