package org.yacos.web.system.session;

import java.net.MalformedURLException;
import java.net.URL;
import javax.servlet.http.HttpServletRequest;

public class YACOSUtils {
	private static String VALID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!?%$()";
	
	public static String generate(Integer length){
		String password = new String();
		
		for(int i=0;i<length;i++){
			password += VALID_CHARS.charAt((int)(Math.random()*((double)VALID_CHARS.length())));
		}
		
		return password;
	}
	
	/**
	 * Constructs an absolute URL from a relative Path
	 * CAN ONLY BE CALLED IN A HttpRequest CONTEXT
	 * @param path A relative path to a server resource
	 * @return The corresponding absolute http URL, null if the URL is malformed
	 */
	public static String fullURL(String path) {
		HttpServletRequest request = SessionService.request;
		
		String resource = request.getContextPath();
		if(! path.substring(0, 1).equals("/")){
			path = "/"+path;
		}
		resource += path;
		
		try {
			URL url = new URL(request.getScheme(),
					request.getServerName(),
					request.getServerPort(),
					resource);
			return url.toString();
		} catch (MalformedURLException e) {
			return null;
		}
		
	}
}
