⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mockhttpservletrequest.java

📁 Wicket一个开发Java Web应用程序框架。它使得开发web应用程序变得容易而轻松。 Wicket利用一个POJO data beans组件使得它可以与任何持久层技术相结合。
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements.  See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.wicket.protocol.http;import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.CharArrayReader;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.security.Principal;import java.text.DateFormat;import java.text.ParseException;import java.util.ArrayList;import java.util.Collections;import java.util.Enumeration;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Locale;import java.util.Map;import javax.servlet.RequestDispatcher;import javax.servlet.ServletContext;import javax.servlet.ServletInputStream;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import org.apache.wicket.Application;import org.apache.wicket.Component;import org.apache.wicket.IPageMap;import org.apache.wicket.IRedirectListener;import org.apache.wicket.IResourceListener;import org.apache.wicket.Page;import org.apache.wicket.WicketRuntimeException;import org.apache.wicket.markup.html.form.Form;import org.apache.wicket.markup.html.form.FormComponent;import org.apache.wicket.markup.html.form.IFormSubmitListener;import org.apache.wicket.markup.html.form.IOnChangeListener;import org.apache.wicket.markup.html.link.BookmarkablePageLink;import org.apache.wicket.markup.html.link.ILinkListener;import org.apache.wicket.protocol.http.request.WebRequestCodingStrategy;import org.apache.wicket.util.file.File;import org.apache.wicket.util.io.IOUtils;import org.apache.wicket.util.lang.Classes;import org.apache.wicket.util.upload.FileUploadBase;import org.apache.wicket.util.value.ValueMap;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * Mock servlet request. Implements all of the methods from the standard HttpServletRequest class * plus helper methods to aid setting up a request. *  * @author Chris Turner */public class MockHttpServletRequest implements HttpServletRequest{	/**	 * A holder class for an uploaded file.	 * 	 * @author Frank Bille (billen)	 */	private class UploadedFile	{		private String fieldName;		private File file;		private String contentType;		/**		 * Construct.		 * 		 * @param fieldName		 * @param file		 * @param contentType		 */		public UploadedFile(String fieldName, File file, String contentType)		{			this.fieldName = fieldName;			this.file = file;			this.contentType = contentType;		}		/**		 * @return The content type of the file. Mime type.		 */		public String getContentType()		{			return contentType;		}		/**		 * @param contentType		 *            The content type.		 */		public void setContentType(String contentType)		{			this.contentType = contentType;		}		/**		 * @return The field name.		 */		public String getFieldName()		{			return fieldName;		}		/**		 * @param fieldName		 */		public void setFieldName(String fieldName)		{			this.fieldName = fieldName;		}		/**		 * @return The uploaded file.		 */		public File getFile()		{			return file;		}		/**		 * @param file		 */		public void setFile(File file)		{			this.file = file;		}	}	/** Logging object */	private static final Logger log = LoggerFactory.getLogger(MockHttpServletRequest.class);	/** The application */	private final Application application;	private final ValueMap attributes = new ValueMap();	private String authType;	private String characterEncoding;	private final ServletContext context;	private final List cookies = new ArrayList();	private final ValueMap headers = new ValueMap();	private String method;	private final ValueMap parameters = new ValueMap();	private String path;	private final HttpSession session;	private String url;	private Map/* <String, UploadedFile> */uploadedFiles;	private boolean useMultiPartContentType;	/**	 * Create the request using the supplied session object.	 * 	 * @param application	 *            The application that this request is for	 * @param session	 *            The session object	 * @param context	 *            The current servlet context	 */	public MockHttpServletRequest(final Application application, final HttpSession session,			final ServletContext context)	{		this.application = application;		this.session = session;		this.context = context;		initialize();	}	/**	 * Add a new cookie.	 * 	 * @param cookie	 *            The cookie	 */	public void addCookie(final Cookie cookie)	{		cookies.add(cookie);	}	/**	 * Add an uploaded file to the request. Use this to simulate a file that has been uploaded to a	 * field.	 * 	 * @param fieldName	 *            The fieldname of the upload field.	 * @param file	 *            The file to upload.	 * @param contentType	 *            The content type of the file. Must be a correct mimetype.	 */	public void addFile(String fieldName, File file, String contentType)	{		if (file == null)		{			throw new IllegalArgumentException("File must not be null");		}		if (file.exists() == false)		{			throw new IllegalArgumentException(					"File does not exists. You must provide an existing file: " +							file.getAbsolutePath());		}		if (file.isFile() == false)		{			throw new IllegalArgumentException(					"You can only add a File, which is not a directory. Only files can be uploaded.");		}		if (uploadedFiles == null)		{			uploadedFiles = new HashMap/* <String, UploadedFile> */();		}		UploadedFile uf = new UploadedFile(fieldName, file, contentType);		uploadedFiles.put(fieldName, uf);	}	/**	 * Add a header to the request.	 * 	 * @param name	 *            The name of the header to add	 * @param value	 *            The value	 */	public void addHeader(String name, String value)	{		List list = (List)headers.get(name);		if (list == null)		{			list = new ArrayList(1);			headers.put(name, list);		}		list.add(value);	}	/**	 * Get an attribute.	 * 	 * @param name	 *            The attribute name	 * @return The value, or null	 */	public Object getAttribute(final String name)	{		return attributes.get(name);	}	/**	 * Get the names of all of the values.	 * 	 * @return The names	 */	public Enumeration getAttributeNames()	{		return Collections.enumeration(attributes.keySet());	}	// HttpServletRequest methods	/**	 * Get the auth type.	 * 	 * @return The auth type	 */	public String getAuthType()	{		return authType;	}	/**	 * Get the current character encoding.	 * 	 * @return The character encoding	 */	public String getCharacterEncoding()	{		return characterEncoding;	}	/**	 * true will force Request generate multiPart ContentType and ContentLength	 * 	 * @param useMultiPartContentType	 */	public void setUseMultiPartContentType(boolean useMultiPartContentType)	{		this.useMultiPartContentType = useMultiPartContentType;	}	/**	 * Return the length of the content. This is always -1 except if useMultiPartContentType set as	 * true. Then the length will be the length of the generated request.	 * 	 * @return -1 if useMultiPartContentType is false. Else the length of the generated request.	 */	public int getContentLength()	{		if (useMultiPartContentType)		{			byte[] request = buildRequest();			return request.length;		}		return -1;	}	/**	 * If useMultiPartContentType set as true return the correct content-type.	 * 	 * @return The correct multipart content-type if useMultiPartContentType is true. Else null.	 */	public String getContentType()	{		if (useMultiPartContentType)		{			return FileUploadBase.MULTIPART_FORM_DATA + "; boundary=abcdefgABCDEFG";		}		return null;	}	/**	 * Get the context path. For this mock implementation the name of the application is always	 * returned.	 * 	 * @return The context path	 */	public String getContextPath()	{		return "/" + application.getName();	}	/**	 * Get all of the cookies for this request.	 * 	 * @return The cookies	 */	public Cookie[] getCookies()	{		if (cookies.size() == 0)		{			return null;		}		Cookie[] result = new Cookie[cookies.size()];		return (Cookie[])cookies.toArray(result);	}	/**	 * Get the given header as a date.	 * 	 * @param name	 *            The header name	 * @return The date, or -1 if header not found	 * @throws IllegalArgumentException	 *             If the header cannot be converted	 */	public long getDateHeader(final String name) throws IllegalArgumentException	{		String value = getHeader(name);		if (value == null)		{			return -1;		}		DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);		try		{			return df.parse(value).getTime();		}		catch (ParseException e)		{			throw new IllegalArgumentException("Can't convert header to date " + name + ": " +					value);		}	}	/**	 * Get the given header value.	 * 	 * @param name	 *            The header name	 * @return The header value or null	 */	public String getHeader(final String name)	{		final List l = (List)headers.get(name);		if (l == null || l.size() < 1)		{			return null;		}		else		{			return (String)l.get(0);		}	}	/**	 * Get the names of all of the headers.	 * 	 * @return The header names	 */	public Enumeration getHeaderNames()	{		return Collections.enumeration(headers.keySet());	}	/**	 * Get enumeration of all header values with the given name.	 * 	 * @param name	 *            The name	 * @return The header values	 */	public Enumeration getHeaders(final String name)	{		List list = (List)headers.get(name);		if (list == null)		{			list = new ArrayList();		}		return Collections.enumeration(list);	}	/**	 * Returns an input stream if there has been added some uploaded files. Use	 * {@link #addFile(String, File, String)} to add some uploaded files.	 * 	 * @return The input stream	 * @throws IOException	 *             If an I/O related problem occurs	 */	public ServletInputStream getInputStream() throws IOException	{		if (uploadedFiles != null && uploadedFiles.size() > 0)		{			byte[] request = buildRequest();			// Ok lets make an input stream to return			final ByteArrayInputStream bais = new ByteArrayInputStream(request);			return new ServletInputStream()			{				public int read()				{					return bais.read();				}			};		}		else		{			return new ServletInputStream()			{				public int read()				{					return -1;				}			};		}	}	/**	 * Get the given header as an int.	 * 	 * @param name	 *            The header name	 * @return The header value or -1 if header not found	 * @throws NumberFormatException	 *             If the header is not formatted correctly	 */	public int getIntHeader(final String name)	{		String value = getHeader(name);		if (value == null)		{			return -1;		}		return Integer.valueOf(value).intValue();	}	/**	 * Get the locale of the request. Attempts to decode the Accept-Language header and if not found	 * returns the default locale of the JVM.	 * 	 * @return The locale	 */	public Locale getLocale()	{		final String header = getHeader("Accept-Language");		if (header == null)		{			return Locale.getDefault();		}		final String[] firstLocale = header.split(",");		if (firstLocale.length < 1)		{			return Locale.getDefault();		}		final String[] bits = firstLocale[0].split("-");		if (bits.length < 1)		{			return Locale.getDefault();		}		final String language = bits[0].toLowerCase();		if (bits.length > 1)		{			final String country = bits[1].toUpperCase();			return new Locale(language, country);		}		else		{			return new Locale(language);		}	}	/**	 * Return all the accepted locales. This implementation always returns just one.	 * 	 * @return The locales	 */	public Enumeration getLocales()	{		List list = new ArrayList(1);		list.add(getLocale());		return Collections.enumeration(list);	}	/**	 * Get the method.	 * 	 * @return The method	 */	public String getMethod()	{		return method;	}	/**	 * Get the request parameter with the given name.	 * 	 * @param name	 *            The parameter name	 * @return The parameter value, or null	 */	public String getParameter(final String name)	{		return parameters.getString(name);	}	/**	 * Get the map of all of the parameters.	 * 	 * @return The parameters	 */	public Map getParameterMap()	{		return parameters;	}	/**	 * Get the names of all of the parameters.	 * 	 * @return The parameter names	 */	public Enumeration getParameterNames()	{		return Collections.enumeration(parameters.keySet());	}	/**	 * Get the values for the given parameter.	 * 	 * @param name	 *            The name of the parameter	 * @return The return values	 */	public String[] getParameterValues(final String name)	{		Object value = parameters.get(name);		if (value == null)		{			return new String[0];		}		if (value instanceof String[])		{			return (String[])value;		}		else		{			String[] result = new String[1];			result[0] = value.toString();			return result;		}	}	/**	 * Get the path info.	 * 	 * @return The path info	 */	public String getPathInfo()	{		return path;	}	/**	 * Always returns null.	 * 	 * @return null	 */	public String getPathTranslated()	{		return null;	}	/**	 * Get the protocol.	 * 	 * @return Always HTTP/1.1	 */	public String getProtocol()	{		return "HTTP/1.1";	}	/**	 * Get the query string part of the request.	 * 	 * @return The query string	 */	public String getQueryString()	{		if (parameters.size() == 0)		{			return null;		}		else		{			final StringBuffer buf = new StringBuffer();			try			{				for (Iterator iterator = parameters.keySet().iterator(); iterator.hasNext();)				{					final String name = (String)iterator.next();					final String value = parameters.getString(name);					buf.append(URLEncoder.encode(name, "UTF-8"));					buf.append('=');					buf.append(URLEncoder.encode(value, "UTF-8"));					if (iterator.hasNext())					{						buf.append('&');					}				}			}			catch (UnsupportedEncodingException e)			{				// Should never happen!			}			return buf.toString();		}	}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -