<commit_before>/*
 * $Id$ $Revision:
 * 1.2 $ $Date$
 * 
 * ==============================================================================
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package wicket.util.resource;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import wicket.util.time.Time;

/**
 * UrlResourceStream implements IResource for URLs.
 * 
 * @see wicket.util.resource.IResourceStream
 * @see wicket.util.watch.IModifiable
 * @author <NAME>
 */
public final class UrlResourceStream extends AbstractResourceStream
{
	/** Logging. */
	private static Log log = LogFactory.getLog(UrlResourceStream.class);

	/** Resource stream. */
	private transient InputStream inputStream;

	/** The URL to this resource. */
	private URL url;
	
	/**
	 * the handle to the file if it is a file resource
	 */
	private File file;

	/** Length of stream. */
	private int contentLength;

	/** Content type for stream. */
	private String contentType;

	/** Last known time the stream was last modified. */
	private long lastModified;

	/**
	 * Private constructor to force use of static factory methods.
	 * 
	 * @param url
	 *            URL of resource
	 */
	public UrlResourceStream(final URL url)
	{
		// Save URL
		this.url = url;
		URLConnection connection = null;
		try
		{
			connection = url.openConnection();
			contentLength = connection.getContentLength();
			contentType = connection.getContentType();
			lastModified = connection.getLastModified();
			try
			{
				file = new File(new URI(url.toExternalForm()));
			}
			catch (Exception ex)
			{
				log.debug("cannot convert url: " + url + " to file (" + ex.getMessage() +
						"), falling back to the inputstream for polling");
			}
			if (file != null && !file.exists())
			{
				file = null;
			}
		}
		catch (IOException ex)
		{
			// It should be impossible to get here or the original URL
			// couldn't have been constructed. But we re-throw with details
			// anyway.
			final IllegalArgumentException illegalArgumentException = new IllegalArgumentException(
					"Invalid URL parameter " + url);
			illegalArgumentException.initCause(ex);
			throw illegalArgumentException;
		}
		finally
		{
			// if applicable, disconnect
			if (connection != null)
			{
				if (connection instanceof HttpURLConnection)
		        { 
		             ((HttpURLConnection)connection).disconnect();
		        }
				else
				{
					try
					{
						connection.getInputStream().close();
					}
					catch (Exception ex)
					{
						// ignore
					}
				}
			}
		}
	}

	/**
	 * Closes this resource.
	 * 
	 * @throws IOException
	 */
	public void close() throws IOException
	{
		if (inputStream != null)
		{
			inputStream.close();
			inputStream = null;
		}
	}

	/**
	 * @return The content type of this resource, such as "image/jpeg" or
	 *         "text/html"
	 */
	public String getContentType()
	{
		if (contentType == null)
		{
			return URLConnection.getFileNameMap().getContentTypeFor(url.getFile());
		}
		return contentType;
	}

	/**
	 * @return A readable input stream for this resource.
	 * @throws ResourceStreamNotFoundException
	 */
	public InputStream getInputStream() throws ResourceStreamNotFoundException
	{
		if (inputStream == null)
		{
			try
			{
				inputStream = url.openStream();
			}
			catch (IOException e)
			{
				throw new ResourceStreamNotFoundException("Resource " + url
						+ " could not be opened", e);
			}
		}

		return inputStream;
	}
<commit_msg>getContentType check for null or  'unknown' uses the ServletContext.getMimeType()<commit_after>/*
 * $Id$ $Revision:
 * 1.2 $ $Date$
 * 
 * ==============================================================================
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package wicket.util.resource;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import wicket.RequestCycle;
import wicket.protocol.http.WebApplication;
import wicket.util.time.Time;

/**
 * UrlResourceStream implements IResource for URLs.
 * 
 * @see wicket.util.resource.IResourceStream
 * @see wicket.util.watch.IModifiable
 * @author <NAME>
 */
public final class UrlResourceStream extends AbstractResourceStream
{
	/** Logging. */
	private static Log log = LogFactory.getLog(UrlResourceStream.class);

	/** Resource stream. */
	private transient InputStream inputStream;

	/** The URL to this resource. */
	private URL url;
	
	/**
	 * the handle to the file if it is a file resource
	 */
	private File file;

	/** Length of stream. */
	private int contentLength;

	/** Content type for stream. */
	private String contentType;

	/** Last known time the stream was last modified. */
	private long lastModified;

	/**
	 * Private constructor to force use of static factory methods.
	 * 
	 * @param url
	 *            URL of resource
	 */
	public UrlResourceStream(final URL url)
	{
		// Save URL
		this.url = url;
		URLConnection connection = null;
		try
		{
			connection = url.openConnection();
			contentLength = connection.getContentLength();
			contentType = connection.getContentType();
			lastModified = connection.getLastModified();
			try
			{
				file = new File(new URI(url.toExternalForm()));
			}
			catch (Exception ex)
			{
				log.debug("cannot convert url: " + url + " to file (" + ex.getMessage() +
						"), falling back to the inputstream for polling");
			}
			if (file != null && !file.exists())
			{
				file = null;
			}
		}
		catch (IOException ex)
		{
			// It should be impossible to get here or the original URL
			// couldn't have been constructed. But we re-throw with details
			// anyway.
			final IllegalArgumentException illegalArgumentException = new IllegalArgumentException(
					"Invalid URL parameter " + url);
			illegalArgumentException.initCause(ex);
			throw illegalArgumentException;
		}
		finally
		{
			// if applicable, disconnect
			if (connection != null)
			{
				if (connection instanceof HttpURLConnection)
		        { 
		             ((HttpURLConnection)connection).disconnect();
		        }
				else
				{
					try
					{
						connection.getInputStream().close();
					}
					catch (Exception ex)
					{
						// ignore
					}
				}
			}
		}
	}

	/**
	 * Closes this resource.
	 * 
	 * @throws IOException
	 */
	public void close() throws IOException
	{
		if (inputStream != null)
		{
			inputStream.close();
			inputStream = null;
		}
	}

	/**
	 * @return The content type of this resource, such as "image/jpeg" or
	 *         "text/html"
	 */
	public String getContentType()
	{
		testContentType();
		return contentType;
	}

	/**
	 * Method to test the content type on null or unknown.
	 * if this is the case the content type is tried to be resolved throw the servlet context
	 */
	private void testContentType()
	{
		if(contentType == null || contentType.indexOf("unknown") != -1)
		{
			RequestCycle rc = RequestCycle.get();
			if(rc != null && (rc.getApplication() instanceof WebApplication))
			{
				// TODO for non webapplication another method should be implemented (getMimeType on application?)
				contentType = ((WebApplication)rc.getApplication()).getWicketServlet().getServletContext().getMimeType(url.getFile());
				if(contentType == null)
				{
					contentType = URLConnection.getFileNameMap().getContentTypeFor(url.getFile());
				}
			}
			else
			{
				contentType = URLConnection.getFileNameMap().getContentTypeFor(url.getFile());
			}
		}
	}

	/**
	 * @return A readable input stream for this resource.
	 * @throws ResourceStreamNotFoundException
	 */
	public InputStream getInputStream() throws ResourceStreamNotFoundException
	{
		if (inputStream == null)
		{
			try
			{
				inputStream = url.openStream();
			}
			catch (IOException e)
			{
				throw new ResourceStreamNotFoundException("Resource " + url
						+ " could not be opened", e);
			}
		}

		return inputStream;
	}

{'fraction_non_alphanumeric': 0.12159965319171995, 'fraction_numerical': 0.001408908637693725, 'mean_word_length': 3.1362617660242043, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3631007', 'n_tokens_mistral': 3038, 'n_tokens_neox': 2554, 'n_words': 811}