package com.github.davidcarboni.restolino.helpers;

import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

/**
 * Provides path parsing. This helps with getting parameters from the path, or
 * the name of the current endpoint.
 * 
 * @author david
 *
 */
public class Path {

	public static Path newInstance(HttpServletRequest request) {
		return new Path(request);
	}

	private List<String> segments = new ArrayList<String>();

	Path(HttpServletRequest request) {
		URI uri = URI.create(request.getPathInfo());
		String path = uri.getPath();
		String[] segments = StringUtils.split(path, '/');
		this.segments = Arrays.asList(segments);
	}

	/**
	 * @return The first path segment. This should be the endpoint name.
	 */
	public String firstSegment() {
		String result = null;
		if (segments.size() > 0)
			result = segments.get(0);
		return result;
	}

	/**
	 * @return The last path segment. This is useful if you're expecting a
	 *         parameter such as an ID, e.g.:
	 * 
	 *         <pre>
	 * /users/{ID}
	 * </pre>
	 */
	public String lastSegment() {
		String result = null;
		if (segments.size() > 0)
			result = segments.get(segments.size() - 1);
		return result;
	}

	public List<String> segments() {
		return segments;
	}

}

@@ -49,29 +49,8 @@
 s;%0A%0A
-import java.net.URI;%0A
 impo
@@ -73,16 +73,16 @@
 ayList;%0A
+
 import j
@@ -579,80 +579,41 @@
 %7B%0A%09%09
-URI uri = URI.create(request.getPathInfo());%0A%09%09String path = uri.getPath
+String path = request.getPathInfo
 ();%0A
@@ -865,32 +865,34 @@
 ents.size() %3E 0)
+ %7B
 %0A%09%09%09result = seg
@@ -905,16 +905,20 @@
 get(0);%0A
+%09%09%7D%0A
 %09%09return
@@ -1186,16 +1186,18 @@
 e() %3E 0)
+ %7B
 %0A%09%09%09resu
@@ -1236,16 +1236,20 @@
 ) - 1);%0A
+%09%09%7D%0A
 %09%09return

Fix for paths that include spaces.