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

📄 mockhttpservletrequest.java

📁 Wicket一个开发Java Web应用程序框架。它使得开发web应用程序变得容易而轻松。 Wicket利用一个POJO data beans组件使得它可以与任何持久层技术相结合。
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
	/**	 * This feature is not implemented at this time as we are not supporting binary servlet input.	 * This functionality may be added in the future.	 * 	 * @return The reader	 * @throws IOException	 *             If an I/O related problem occurs	 */	public BufferedReader getReader() throws IOException	{		return new BufferedReader(new CharArrayReader(new char[0]));	}	/**	 * Deprecated method - should not be used.	 * 	 * @param name	 *            The name	 * @return The path	 * @deprecated Use ServletContext.getRealPath(String) instead.	 */	public String getRealPath(String name)	{		return context.getRealPath(name);	}	/**	 * Get the remote address of the client.	 * 	 * @return Always 127.0.0.1	 */	public String getRemoteAddr()	{		return "127.0.0.1";	}	/**	 * Get the remote host.	 * 	 * @return Always localhost	 */	public String getRemoteHost()	{		return "localhost";	}	/**	 * Get the name of the remote user from the REMOTE_USER header.	 * 	 * @return The name of the remote user	 */	public String getRemoteUser()	{		return getHeader("REMOTE_USER");	}	/**	 * Return a dummy dispatcher that just records that dispatch has occurred without actually doing	 * anything.	 * 	 * @param name	 *            The name to dispatch to	 * @return The dispatcher	 */	public RequestDispatcher getRequestDispatcher(String name)	{		return context.getRequestDispatcher(name);	}	/**	 * Get the requested session id. Always returns the id of the current session.	 * 	 * @return The session id	 */	public String getRequestedSessionId()	{		return session.getId();	}	/**	 * Returns context path and servlet path concatenated, typically	 * /applicationClassName/applicationClassName	 * 	 * @return The path value	 * @see javax.servlet.http.HttpServletRequest#getRequestURI()	 */	public String getRequestURI()	{		if (url == null)		{			return getContextPath() + getServletPath();		}		return url;	}	/**	 * Try to build a rough URL.	 * 	 * @return The url	 */	public StringBuffer getRequestURL()	{		final StringBuffer buf = new StringBuffer();		buf.append("http://localhost");		buf.append(getContextPath());		if (getPathInfo() != null)		{			buf.append(getPathInfo());		}		final String query = getQueryString();		if (query != null)		{			buf.append('?');			buf.append(query);		}		return buf;	}	/**	 * Get the scheme.	 * 	 * @return Always http	 */	public String getScheme()	{		return "http";	}	/**	 * Get the server name.	 * 	 * @return Always localhost	 */	public String getServerName()	{		return "localhost";	}	/**	 * Get the server port.	 * 	 * @return Always 80	 */	public int getServerPort()	{		return 80;	}	/**	 * The servlet path may either be the application name or /. For test purposes we always return	 * the servlet name.	 * 	 * @return The servlet path	 */	public String getServletPath()	{		return getContextPath();	}	/**	 * Get the sessions.	 * 	 * @return The session	 */	public HttpSession getSession()	{		return session;	}	/**	 * Get the session.	 * 	 * @param b	 *            Ignored, there is always a session	 * @return The session	 */	public HttpSession getSession(boolean b)	{		return session;	}	/**	 * Get the user principal.	 * 	 * @return A user principal	 */	public Principal getUserPrincipal()	{		final String user = getRemoteUser();		if (user == null)		{			return null;		}		else		{			return new Principal()			{				public String getName()				{					return user;				}			};		}	}	/**	 * @return True if there has been added files to this request using	 *         {@link #addFile(String, File, String)}	 */	public boolean hasUploadedFiles()	{		return uploadedFiles != null;	}	/**	 * Reset the request back to a default state.	 */	public void initialize()	{		authType = null;		method = "post";		cookies.clear();		setDefaultHeaders();		path = null;		url = null;		characterEncoding = "UTF-8";		parameters.clear();		attributes.clear();	}	/**	 * Check whether session id is from a cookie. Always returns true.	 * 	 * @return Always true	 */	public boolean isRequestedSessionIdFromCookie()	{		return true;	}	/**	 * Check whether session id is from a url rewrite. Always returns false.	 * 	 * @return Always false	 */	public boolean isRequestedSessionIdFromUrl()	{		return false;	}	/**	 * Check whether session id is from a url rewrite. Always returns false.	 * 	 * @return Always false	 */	public boolean isRequestedSessionIdFromURL()	{		return false;	}	/**	 * Check whether the session id is valid.	 * 	 * @return Always true	 */	public boolean isRequestedSessionIdValid()	{		return true;	}	/**	 * Always returns false.	 * 	 * @return Always false	 */	public boolean isSecure()	{		return false;	}	/**	 * NOT IMPLEMENTED.	 * 	 * @param name	 *            The role name	 * @return Always false	 */	public boolean isUserInRole(String name)	{		return false;	}	/**	 * Remove the given attribute.	 * 	 * @param name	 *            The name of the attribute	 */	public void removeAttribute(final String name)	{		attributes.remove(name);	}	/**	 * Set the given attribute.	 * 	 * @param name	 *            The attribute name	 * @param o	 *            The value to set	 */	public void setAttribute(final String name, final Object o)	{		attributes.put(name, o);	}	/**	 * Set the auth type.	 * 	 * @param authType	 *            The auth type	 */	public void setAuthType(final String authType)	{		this.authType = authType;	}	/**	 * Set the character encoding.	 * 	 * @param encoding	 *            The character encoding	 * @throws UnsupportedEncodingException	 *             If encoding not supported	 */	public void setCharacterEncoding(final String encoding) throws UnsupportedEncodingException	{		characterEncoding = encoding;	}	/**	 * Set the cookies.	 * 	 * @param theCookies	 *            The cookies	 */	public void setCookies(final Cookie[] theCookies)	{		cookies.clear();		for (int i = 0; i < theCookies.length; i++)		{			cookies.add(theCookies[i]);		}	}	/**	 * Set the method.	 * 	 * @param method	 *            The method	 */	public void setMethod(final String method)	{		this.method = method;	}	/**	 * Set a parameter.	 * 	 * @param name	 *            The name	 * @param value	 *            The value	 */	public void setParameter(final String name, final String value)	{		parameters.put(name, value);	}	/**	 * Sets a map of parameters.	 * 	 * @param parameters	 *            the parameters to set	 */	public void setParameters(final Map parameters)	{		this.parameters.putAll(parameters);	}	/**	 * Set the path that this request is supposed to be serving. The path is relative to the web	 * application root and should start with a / character	 * 	 * @param path	 */	public void setPath(final String path)	{		this.path = path;	}	/**	 * Set the complete url for this request. The url will be analyzed.	 * 	 * @param url	 */	public void setURL(String url)	{		if (url.startsWith("http://"))		{			int index = url.indexOf("/", 7);			url = url.substring(index);		}		this.url = url;		if (url.startsWith(getContextPath()))		{			url = url.substring(getContextPath().length());		}		if (url.startsWith(getServletPath()))		{			url = url.substring(getServletPath().length());		}		int index = url.indexOf("?");		if (index == -1)		{			path = url;		}		else		{			path = url.substring(0, index);			String queryString = url.substring(index + 1);			RequestUtils.decodeParameters(queryString, parameters);		}	}	/**	 * Initialize the request parameters to point to the given bookmarkable page.	 * 	 * @param page	 *            The page to point to	 * @param params	 *            Additional parameters	 */	public void setRequestToBookmarkablePage(final Page page, final Map params)	{		parameters.putAll(params);		parameters.put(WebRequestCodingStrategy.BOOKMARKABLE_PAGE_PARAMETER_NAME, page.getClass()				.getName());	}	/**	 * Initialize the request parameters to point to the given component.	 * 	 * @param component	 *            The component	 */	public void setRequestToComponent(final Component component)	{		final IPageMap pageMap = component.getPage().getPageMap();		final String pageMapName = pageMap.isDefault() ? "" : pageMap.getName();		if (component instanceof BookmarkablePageLink)		{			final Class clazz = ((BookmarkablePageLink)component).getPageClass();			parameters.put(WebRequestCodingStrategy.BOOKMARKABLE_PAGE_PARAMETER_NAME, pageMapName +					':' + clazz.getName());		}		else		{			int version = component.getPage().getCurrentVersionNumber();			Class clazz = null;			if (component instanceof IRedirectListener)			{				clazz = IRedirectListener.class;			}			else if (component instanceof IResourceListener)			{				clazz = IResourceListener.class;			}			else if (component instanceof IFormSubmitListener)			{				clazz = IFormSubmitListener.class;			}			else if (component instanceof ILinkListener)			{				clazz = ILinkListener.class;			}			else if (component instanceof IOnChangeListener)			{				clazz = IOnChangeListener.class;			}			else			{				throw new IllegalArgumentException(						"The component class doesn't seem to implement any of the known *Listener interfaces: " +								component.getClass());			}			parameters.put(WebRequestCodingStrategy.INTERFACE_PARAMETER_NAME, pageMapName + ':' +					component.getPath() + ':' + (version == 0 ? "" : "" + version) + ':' +					Classes.simpleName(clazz) + "::");			if (component.isStateless() && component.getPage().isBookmarkable())			{				parameters.put(WebRequestCodingStrategy.BOOKMARKABLE_PAGE_PARAMETER_NAME,						pageMapName + ':' + component.getPage().getClass().getName());			}		}	}	/**	 * Initialize the request parameters to point to the given form component. The additional map	 * should contain mappings between individual components that appear in the form and the string	 * value that should be submitted for each of these components.	 * 	 * @param form	 *            The for to send the request to	 * @param values	 *            The values for each of the form components	 */	public void setRequestToFormComponent(final Form form, final Map values)	{		setRequestToComponent(form);		final Map valuesApplied = new HashMap();		form.visitChildren(new Component.IVisitor()		{			public Object component(final Component component)			{				if (component instanceof FormComponent)				{					String value = (String)values.get(component);					if (value != null)					{						parameters.put(((FormComponent)component).getInputName(), values								.get(component));						valuesApplied.put(component.getId(), component);					}				}				return CONTINUE_TRAVERSAL;			}		});		if (values.size() != valuesApplied.size())		{			Map diff = new HashMap();			diff.putAll(values);			Iterator iter = valuesApplied.keySet().iterator();			while (iter.hasNext())			{				diff.remove(iter.next());			}			log					.error("Parameter mismatch: didn't find all components referenced in parameter 'values': " +							diff.keySet());		}	}	/**	 * Initialize the request parameters from the given redirect string that redirects back to a	 * particular component for display.	 * 	 * @param redirect	 *            The redirect string to display from	 */	public void setRequestToRedirectString(final String redirect)	{		parameters.clear();		int queryStringPos = redirect.indexOf('?');		// Decode the parameters		if (queryStringPos != -1)		{			final String queryString = redirect.substring(queryStringPos + 1);			RequestUtils.decodeParameters(queryString, parameters);		}		// We need to absolutize the redirect URL as we are not as smart as a web-browser		// (WICKET-702)		url = getContextPath() + getServletPath() + "/" + redirect;		// Remove occurrences of ".." from the path		url = RequestUtils.removeDoubleDots(url);		log.info("Redirecting to " + url);	}	/**	 * Helper method to create some default headers for the request	 */	private void setDefaultHeaders()	{		headers.clear();		addHeader("Accept", "text/xml,application/xml,application/xhtml+xml,"				+ "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");		addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");		Locale l = Locale.getDefault();		addHeader("Accept-Language", l.getLanguage().toLowerCase() + "-" +				l.getCountry().toLowerCase() + "," + l.getLanguage().toLowerCase() + ";q=0.5");		addHeader("User-Agent",				"Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7) Gecko/20040707 Firefox/0.9.2");	}	private static final String crlf = "\r\n";	private static final String boundary = "--abcdefgABCDEFG";	private void newAttachment(OutputStream out) throws IOException	{		out.write(boundary.getBytes());		out.write(crlf.getBytes());		out.write("Content-Disposition: form-data".getBytes());	}	/**	 * Build the request based on the uploaded files and the parameters.	 * 	 * @return The request as a string.	 */	private byte[] buildRequest()	{		try		{			// Build up the input stream based on the files and parameters			ByteArrayOutputStream out = new ByteArrayOutputStream();			// Add parameters			for (Iterator iterator = parameters.keySet().iterator(); iterator.hasNext();)			{				final String name = (String)iterator.next();				newAttachment(out);				out.write("; name=\"".getBytes());				out.write(name.getBytes());				out.write("\"".getBytes());				out.write(crlf.getBytes());				out.write(crlf.getBytes());				out.write(parameters.get(name).toString().getBytes());				out.write(crlf.getBytes());			}			// Add files			if (uploadedFiles != null)			{				for (Iterator iterator = uploadedFiles.keySet().iterator(); iterator.hasNext();)				{					String fieldName = (String)iterator.next();					UploadedFile uf = (UploadedFile)uploadedFiles.get(fieldName);					newAttachment(out);					out.write("; name=\"".getBytes());					out.write(fieldName.getBytes());					out.write("\"; filename=\"".getBytes());					out.write(uf.getFile().getName().getBytes());					out.write("\"".getBytes());					out.write(crlf.getBytes());					out.write("Content-Type: ".getBytes());					out.write(uf.getContentType().getBytes());					out.write(crlf.getBytes());					out.write(crlf.getBytes());					// Load the file and put it into the the inputstream					FileInputStream fis = new FileInputStream(uf.getFile());					IOUtils.copy(fis, out);					fis.close();					out.write(crlf.getBytes());				}			}			out.write(boundary.getBytes());			out.write("--".getBytes());			out.write(crlf.getBytes());			return out.toByteArray();		}		catch (IOException e)		{			// NOTE: IllegalStateException(Throwable) only exists since Java 1.5			throw new WicketRuntimeException(e);		}	}	public String getLocalAddr()	{		return "127.0.0.1";	}	public String getLocalName()	{		return "127.0.0.1";	}	public int getLocalPort()	{		return 80;	}	public int getRemotePort()	{		return 80;	}}

⌨️ 快捷键说明

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