package com.jxml.protocol.classpath;
import java.net.*;
import java.io.*;

/**
 * Implements the jxml classpath protocol.
 */
public class ClassPathURLConnection extends URLConnection
{
	/**
	 * By default, output is permitted if the CLASSPATH 
	 * starts with ".".
	 */
		protected static boolean
	doOutputDefault;

	static
	{
		String classpath=System.getProperty("java.class.path");
		if (".".equals(classpath))
			doOutputDefault=true;
		else
		{
			String desired="."+System.getProperty("path.separator");
			String prefix=classpath.substring(0,desired.length());
			doOutputDefault=desired.equals(prefix);
		}
	}

	/**
	 * Called by Handler to open a classpath connection.
	 */
		public
	ClassPathURLConnection(URL url)
	{
		super(url);
		doInput=true;
		doOutput=doOutputDefault;
	}

	/**
	 * Opens a connection to the item on the classpath.
	 */
		public void
	connect()
	{
		connected=true;
	}

	/**
	 * Returns an input stream to the item on the classpath.
	 */
		public InputStream
	getInputStream()
		throws IOException
	{
		String name=url.getFile().substring(1);
		ClassLoader classLoader=getClass().getClassLoader();
		return classLoader.getResourceAsStream(name);
	}

	/**
	 * Returns an output stream to the item on the classpath.
	 */
		public OutputStream
	getOutputStream()
		throws IOException
	{
		String name=url.getFile().substring(1);
		File file=new File(name);
		int i=name.lastIndexOf("/");
		if (i>-1)
		{
			String dirName=name.substring(0,i);
			File dir=new File(dirName);
			if (!dir.exists())
			{
				if (!dir.mkdirs())
					throw new IOException(
"Unable to create new directory in current working directory: "+dirName);
			}
		}
		return new FileOutputStream(file);
	}
}
