package eworks.RDF.util;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Hashtable;

/**
 * <p><code>UriFactory</code> provides a factory for instances of the class
 * <code>java.net.URI</code>. This class is a helper class for minimizing an
 * application's need for memory, by ensuring that identical URIs are
 * represented by the same <code>java.net.URI</code>-instance.</p>
 * <pre>
 *try {
 *    URI myUriInstance = UriFactory.getURI("http://www.foobar.org");
 *    URI identicalUriInstance = UriFactory.getURI("http://www.foobar.org");
 *} catch(URISyntaxException e) {
 *    System.out.println(e);
 *}
 *</pre>
 * 
 * @author Fabian Wleklinski (<a href="mailto:fabian@wleklinski.de">fabian@wleklinski.de</a>)
 * @version 1.00 (2003-11-03)
 */
public class UriFactory {

	private static Hashtable uriCache = new Hashtable();
	
	private UriFactory() {
	}

	/**
	 * Returns as instance of <code>java.net.URI</code> for the given URI literal.
	 * 
	 * @param literal The URI's string representation, example given
	 *        <code>http://www.foobar.org</code>
	 * @return A cached instance of <code>java.net.URI</code> if avilable, a new
	 *         instance otherwise.
	 * @throws URISyntaxException if the given <code>literal</code> is no valid URI.
	 */
	public static URI getURI( String literal ) throws URISyntaxException {
		URI uri = (URI) uriCache.get(literal);
		if (uri == null) {
			String normalizedLiteral = literal.replace('\\', '/');

			StringBuffer sb = new StringBuffer(normalizedLiteral);
		
			int pos = 0;
			while ((pos = sb.indexOf(" ", pos)) >= 0)
				sb.replace(pos, pos+1, "%20");
			normalizedLiteral = sb.toString();
			sb = null;
			uri=new URI(normalizedLiteral);
		
			uriCache.put(literal, uri);
		}
		return uri;
	}
}