Advertisement
Guest User

SerializedPHPParser.java

a guest
May 29th, 2013
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.61 KB | None | 0 0
  1. /*
  2. Copyright (c) 2007 Zsolt Sz?sz <zsolt at lorecraft dot com>
  3.  
  4. Permission is hereby granted, free of charge, to any person obtaining
  5. a copy of this software and associated documentation files (the
  6. "Software"), to deal in the Software without restriction, including
  7. without limitation the rights to use, copy, modify, merge, publish,
  8. distribute, sublicense, and/or sell copies of the Software, and to
  9. permit persons to whom the Software is furnished to do so, subject to
  10. the following conditions:
  11.  
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14.  
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  19. LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  20. OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  21. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23.  
  24. package utils;
  25.  
  26. import java.util.HashMap;
  27. import java.util.LinkedHashMap;
  28. import java.util.Map;
  29. import java.util.regex.Pattern;
  30.  
  31. /**
  32.  * Deserializes a serialized PHP data structure into corresponding Java objects. It supports
  33.  * the integer, float, boolean, string primitives that are mapped to their Java
  34.  * equivalent, plus arrays that are parsed into <code>Map</code> instances and objects
  35.  * that are represented by {@link SerializedPhpParser.PhpObject} instances.
  36.  * <p>
  37.  * Example of use:
  38.  * <pre>
  39.  *      String input = "O:8:"TypeName":1:{s:3:"foo";s:3:"bar";}";
  40.  *      SerializedPhpParser serializedPhpParser = new SerializedPhpParser(input);
  41.  *      Object result = serializedPhpParser.parse();
  42.  * </pre>
  43.  *
  44.  * The <code>result</code> object will be a <code>PhpObject</code> with the name "TypeName" and
  45.  * the attribute "foo" = "bar".
  46.  */
  47. public class SerializedPhpParser {
  48.  
  49.     private final String input;
  50.  
  51.     private int index;
  52.  
  53.     private boolean assumeUTF8 = true;
  54.  
  55.     private Pattern acceptedAttributeNameRegex = null;
  56.  
  57.     public SerializedPhpParser(String input) {
  58.         this.input = input;
  59.     }
  60.  
  61.     public SerializedPhpParser(String input, boolean assumeUTF8) {
  62.         this.input = input;
  63.         this.assumeUTF8 = assumeUTF8;
  64.     }
  65.  
  66.     public Object parse() {
  67.         char type = input.charAt(index);
  68.         switch (type) {
  69.             case 'i':
  70.                 index += 2;
  71.                 // Patch Integer/Double for the PHP x64.
  72.                 Object tmp;
  73.                 tmp = parseInt();
  74.                 if (tmp == null) {
  75.                     tmp = parseFloat();
  76.                 }
  77.                 return tmp;
  78.             // End of Patch Integer/Double for the PHP x64.
  79.             case 'd':
  80.                 index += 2;
  81.                 return parseFloat();
  82.             case 'b':
  83.                 index += 2;
  84.                 return parseBoolean();
  85.             case 's':
  86.                 index += 2;
  87.                 return parseString();
  88.             case 'a':
  89.                 index += 2;
  90.                 return parseArray();
  91.             case 'O':
  92.                 index += 2;
  93.                 return parseObject();
  94.             case 'N':
  95.                 index += 2;
  96.                 return NULL;
  97.             default:
  98.                 throw new IllegalStateException("Encountered unknown type [" + type
  99.                         + "]");
  100.         }
  101.     }
  102.  
  103.     private Object parseObject() {
  104.         PhpObject phpObject = new PhpObject();
  105.         int strLen = readLength();
  106.         phpObject.name = input.substring(index, index + strLen);
  107.         index = index + strLen + 2;
  108.         int attrLen = readLength();
  109.         for (int i = 0; i < attrLen; i++) {
  110.             Object key = parse();
  111.             Object value = parse();
  112.             if (isAcceptedAttribute(key)) {
  113.                 phpObject.attributes.put(key, value);
  114.             }
  115.         }
  116.         index++;
  117.         return phpObject;
  118.     }
  119.  
  120.     private Map<Object, Object> parseArray() {
  121.         int arrayLen = readLength();
  122.         Map<Object, Object> result = new LinkedHashMap<Object, Object>();
  123.         for (int i = 0; i < arrayLen; i++) {
  124.             Object key = parse();
  125.             Object value = parse();
  126.             if (isAcceptedAttribute(key)) {
  127.                 result.put(key, value);
  128.             }
  129.         }
  130.         index++;
  131.         return result;
  132.     }
  133.  
  134.     private boolean isAcceptedAttribute(Object key) {
  135.         if (acceptedAttributeNameRegex == null) {
  136.             return true;
  137.         }
  138.         if (!(key instanceof String)) {
  139.             return true;
  140.         }
  141.         return acceptedAttributeNameRegex.matcher((String)key).matches();
  142.     }
  143.  
  144.     private int readLength() {
  145.         int delimiter = input.indexOf(':', index);
  146.         int arrayLen = Integer.valueOf(input.substring(index, delimiter));
  147.         index = delimiter + 2;
  148.         return arrayLen;
  149.     }
  150.  
  151.     /**
  152.      * Assumes strings are utf8 encoded
  153.      *
  154.      * @return
  155.      */
  156.     private String parseString() {
  157.         int strLen = readLength();
  158.  
  159.         int utfStrLen = 0;
  160.         int byteCount = 0;
  161.         while (byteCount != strLen) {
  162.             char ch = input.charAt(index + utfStrLen++);
  163.             if (assumeUTF8) {
  164.                 if ((ch >= 0x0001) && (ch <= 0x007F)) {
  165.                     byteCount++;
  166.                 } else if (ch > 0x07FF) {
  167.                     byteCount += 3;
  168.                 } else {
  169.                     byteCount += 2;
  170.                 }
  171.             } else {
  172.                 byteCount++;
  173.             }
  174.         }
  175.         String value = input.substring(index, index + utfStrLen);
  176.         index = index + utfStrLen + 2;
  177.         return value;
  178.     }
  179.  
  180.     private Boolean parseBoolean() {
  181.         int delimiter = input.indexOf(';', index);
  182.         String value = input.substring(index, delimiter);
  183.         if (value.equals("1")) {
  184.             value = "true";
  185.         } else if (value.equals("0")) {
  186.             value = "false";
  187.         }
  188.         index = delimiter + 1;
  189.         return Boolean.valueOf(value);
  190.     }
  191.  
  192.     private Double parseFloat() {
  193.         int delimiter = input.indexOf(';', index);
  194.         String value = input.substring(index, delimiter);
  195.         index = delimiter + 1;
  196.         return Double.valueOf(value);
  197.     }
  198.  
  199.     private Integer parseInt() {
  200.         int delimiter = input.indexOf(';', index);
  201.         // Let's store old value of the index for the patch Integer/Double for the PHP x64.
  202.         int index_old=index;
  203.         String value = input.substring(index, delimiter);
  204.         index = delimiter + 1;
  205.         // Patch Integer/Double for the PHP x64.
  206.         try {
  207.             return Integer.valueOf(value);
  208.         } catch (Exception ex) {
  209.             index=index_old;
  210.         }
  211.         return null;
  212.         // End of Patch Integer/Double for the PHP x64.
  213.     }
  214.  
  215.     public void setAcceptedAttributeNameRegex(String acceptedAttributeNameRegex) {
  216.         this.acceptedAttributeNameRegex = Pattern.compile(acceptedAttributeNameRegex);
  217.     }
  218.  
  219.     public static final Object NULL = new Object() {
  220.         @Override
  221.         public String toString() {
  222.             return "NULL";
  223.         }
  224.     };
  225.  
  226.     /**
  227.      * Represents an object that has a name and a map of attributes
  228.      */
  229.     public static class PhpObject {
  230.         public String name;
  231.         public Map<Object, Object> attributes = new HashMap<Object, Object>();
  232.  
  233.         @Override
  234.         public String toString() {
  235.             return "\"" + name + "\" : " + attributes.toString();
  236.         }
  237.     }
  238. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement