package com.imasson.commandrouter.driver;

import com.imasson.commandrouter.CommandRouter;

import java.net.URI;

/**
 * The command driver that parse command from {@link URI} or URI in String form.
 *
 * @author Masson
 */
public class UriDriver extends AbstractDriver {

    @Override
    public CommandRouter.Op parseCommand(Object context, Object... rawArgs) {
        URI uri = null;

        final Object rawArg = rawArgs[0];
        if (rawArg instanceof String) {
            try {
                uri = URI.create((String) rawArg);
            } catch (IllegalArgumentException ex) {
                throw new DriverException("Error parsing URI", ex, rawArgs);
            }
        } else if (rawArg instanceof URI) {
            uri = (URI) rawArg;
        } else {
            throw new DriverException("Unexpected format of args", rawArgs);
        }

        final String host = uri.getHost();
        if (host == null) {
            throw new DriverException("No handler name found", rawArgs);
        }

        String path = uri.getPath();
        if (path == null || path.length() <= 1) {
            throw new DriverException("No command name found", rawArgs);
        }
        path = path.substring(1);

        CommandRouter.Op op = new CommandRouter.Op(context, host, path);

        try {
            final String query = uri.getQuery();
            final String[] querySegments = query.split("&");
            for (int i = 0; i < querySegments.length; i++) {
                String seg = querySegments[i];
                String[] kvpair = seg.split("=");
                op.addArgument(kvpair[0], kvpair[1]);
            }
        } catch (Exception ex) {
            throw new DriverException("Error parsing query in URI", ex, rawArgs);
        }

        return op;
    }
}

@@ -105,16 +105,44 @@
 net.URI;
+%0Aimport java.net.URLDecoder;
 %0A%0A/**%0A *
@@ -294,16 +294,69 @@
 iver %7B%0A%0A
+    private static final String ENCODING = %22utf-8%22;%0A%0A
     @Ove
@@ -458,15 +458,8 @@
  uri
- = null
 ;%0A%0A 
@@ -1366,34 +1366,16 @@
 path);%0A%0A
-        try %7B%0A    
         
@@ -1402,16 +1402,19 @@
  uri.get
+Raw
 Query();
@@ -1410,24 +1410,75 @@
 RawQuery();%0A
+        if (query != null) %7B%0A            try %7B%0A    
             
@@ -1538,16 +1538,20 @@
         
+    
 for (int
@@ -1587,24 +1587,28 @@
 gth; i++) %7B%0A
+    
             
@@ -1654,24 +1654,28 @@
             
+    
 String%5B%5D kvp
@@ -1693,19 +1693,28 @@
 plit(%22=%22
-);%0A
+, -2);%0A%0A    
         
@@ -1725,60 +1725,177 @@
     
-op.addArgument(kvpair%5B0%5D, kvpair%5B1%5D);%0A            %7D%0A
+String key = kvpair%5B0%5D;%0A                    String value = URLDecoder.decode(kvpair%5B1%5D, ENCODING);%0A                    op.addArgument(key, value);%0A                %7D%0A    
     
@@ -1915,32 +1915,36 @@
 Exception ex) %7B%0A
+    
             thro
@@ -2001,32 +2001,46 @@
 , ex, rawArgs);%0A
+            %7D%0A
         %7D%0A%0A     

fix Uri parse issue