package de.felixbruns.jotify.gateway.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import com.sun.net.httpserver.HttpExchange;

import de.felixbruns.jotify.gateway.GatewayApplication;

public class URIUtilities {
	public static Map<String, String> parseQuery(String query){
		Map<String, String> map = new HashMap<String, String>();
		
		if(query == null){
			return map;
		}
		
		String[] params = query.split("&");
		
		for(String param : params){  
			String name  = param.split("=")[0];
			String value = param.split("=")[1];
			
			map.put(name, value);
		}
		
		return map;
	}

	public static Map<String, String> parseQuery(HttpExchange exchange) throws IOException {
		String requestMethod = exchange.getRequestMethod();
		String requestQuery  = exchange.getRequestURI().getQuery();

		Map<String, String> params = new HashMap<String, String>();

		if(requestMethod.equalsIgnoreCase("GET")){
			params = parseQuery(requestQuery);
		}
		else if(requestMethod.equalsIgnoreCase("POST")){
			InputStream    input   = exchange.getRequestBody();
			BufferedReader reader  = new BufferedReader(new InputStreamReader(input));
			StringBuilder  builder = new StringBuilder();
			String         line;

			/* Convert input stream to string. */
			while((line = reader.readLine()) != null){
				builder.append(line);
			}

			/* Close input stream. */
			input.close();

			/* Parse query. */
			params = parseQuery(builder.toString());
		}

		if(exchange.getAttribute("session") != null) {
			params.put("session", (String)exchange.getAttribute("session"));
		}

		return params;
	}
}

@@ -573,18 +573,16 @@
 params)%7B
-  
 %0A%09%09%09Stri
@@ -587,14 +587,23 @@
 ring
+%5B%5D
  name
- 
+AndValue
  = p
@@ -621,78 +621,133 @@
 %22=%22)
-%5B0%5D
 ;%0A%09%09%09
-String value = param.split(%22=%22)%5B1%5D;%0A%09%09%09%0A%09%09%09map.put(name, v
+if (nameAndValue.length != 2 %7C%7C nameAndValue%5B0%5D.isEmpty())%0A%09%09%09%09continue;%0A%09%09%09%0A%09%09%09map.put(nameAndValue%5B0%5D, nameAndV
 alue
+%5B1%5D
 );%0A%09

Make parsing of URI parameters more robust