updated Spring Portlet MVC to Portlet API 2.0

This commit is contained in:
Juergen Hoeller
2009-01-19 23:32:32 +00:00
parent 76888e243f
commit 464c7eedf2
64 changed files with 4197 additions and 1140 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,14 +16,6 @@
package org.springframework.mock.web.portlet;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import javax.portlet.ActionRequest;
import javax.portlet.PortalContext;
import javax.portlet.PortletContext;
@@ -36,25 +28,28 @@ import javax.portlet.PortletMode;
* @author Juergen Hoeller
* @since 2.0
*/
public class MockActionRequest extends MockPortletRequest implements ActionRequest {
private String characterEncoding;
private byte[] content;
private String contentType;
public class MockActionRequest extends MockClientDataRequest implements ActionRequest {
/**
* Create a new MockActionRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @see MockPortalContext
* @see MockPortletContext
* @see org.springframework.mock.web.portlet.MockPortalContext
* @see org.springframework.mock.web.portlet.MockPortletContext
*/
public MockActionRequest() {
super();
}
/**
* Create a new MockActionRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @param actionName the name of the action to trigger
*/
public MockActionRequest(String actionName) {
super();
setParameter(ActionRequest.ACTION_NAME, actionName);
}
/**
* Create a new MockActionRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
@@ -83,49 +78,9 @@ public class MockActionRequest extends MockPortletRequest implements ActionReque
}
public void setContent(byte[] content) {
this.content = content;
}
public InputStream getPortletInputStream() throws IOException {
if (this.content != null) {
return new ByteArrayInputStream(this.content);
}
else {
return null;
}
}
public void setCharacterEncoding(String characterEncoding) {
this.characterEncoding = characterEncoding;
}
public BufferedReader getReader() throws UnsupportedEncodingException {
if (this.content != null) {
InputStream sourceStream = new ByteArrayInputStream(this.content);
Reader sourceReader = (this.characterEncoding != null) ?
new InputStreamReader(sourceStream, this.characterEncoding) : new InputStreamReader(sourceStream);
return new BufferedReader(sourceReader);
}
else {
return null;
}
}
public String getCharacterEncoding() {
return characterEncoding;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getContentType() {
return contentType;
}
public int getContentLength() {
return (this.content != null ? content.length : -1);
@Override
protected String getLifecyclePhase() {
return ACTION_PHASE;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,9 @@
package org.springframework.mock.web.portlet;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -27,6 +29,7 @@ import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.WindowState;
import javax.portlet.WindowStateException;
import javax.xml.namespace.QName;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
@@ -38,16 +41,12 @@ import org.springframework.util.CollectionUtils;
* @author Juergen Hoeller
* @since 2.0
*/
public class MockActionResponse extends MockPortletResponse implements ActionResponse {
public class MockActionResponse extends MockStateAwareResponse implements ActionResponse {
private WindowState windowState;
private PortletMode portletMode;
private boolean redirectAllowed = true;
private String redirectedUrl;
private final Map<String, String[]> renderParameters = new LinkedHashMap<String, String[]>();
/**
* Create a new MockActionResponse with a default {@link MockPortalContext}.
@@ -71,93 +70,60 @@ public class MockActionResponse extends MockPortletResponse implements ActionRes
if (this.redirectedUrl != null) {
throw new IllegalStateException("Cannot set WindowState after sendRedirect has been called");
}
if (!CollectionUtils.contains(getPortalContext().getSupportedWindowStates(), windowState)) {
throw new WindowStateException("WindowState not supported", windowState);
}
this.windowState = windowState;
}
public WindowState getWindowState() {
return windowState;
super.setWindowState(windowState);
this.redirectAllowed = false;
}
public void setPortletMode(PortletMode portletMode) throws PortletModeException {
if (this.redirectedUrl != null) {
throw new IllegalStateException("Cannot set PortletMode after sendRedirect has been called");
}
if (!CollectionUtils.contains(getPortalContext().getSupportedPortletModes(), portletMode)) {
throw new PortletModeException("PortletMode not supported", portletMode);
}
this.portletMode = portletMode;
super.setPortletMode(portletMode);
this.redirectAllowed = false;
}
public PortletMode getPortletMode() {
return portletMode;
}
public void sendRedirect(String url) throws IOException {
if (this.windowState != null || this.portletMode != null || !this.renderParameters.isEmpty()) {
throw new IllegalStateException(
"Cannot call sendRedirect after windowState, portletMode, or renderParameters have been set");
}
Assert.notNull(url, "Redirect URL must not be null");
this.redirectedUrl = url;
}
public String getRedirectedUrl() {
return redirectedUrl;
}
public void setRenderParameters(Map parameters) {
public void setRenderParameters(Map<String, String[]> parameters) {
if (this.redirectedUrl != null) {
throw new IllegalStateException("Cannot set render parameters after sendRedirect has been called");
}
Assert.notNull(parameters, "Parameters Map must not be null");
this.renderParameters.clear();
for (Iterator it = parameters.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
Assert.isTrue(entry.getKey() instanceof String, "Key must be of type String");
Assert.isTrue(entry.getValue() instanceof String[], "Value must be of type String[]");
this.renderParameters.put((String) entry.getKey(), (String[]) entry.getValue());
}
super.setRenderParameters(parameters);
this.redirectAllowed = false;
}
public void setRenderParameter(String key, String value) {
if (this.redirectedUrl != null) {
throw new IllegalStateException("Cannot set render parameters after sendRedirect has been called");
}
Assert.notNull(key, "Parameter key must not be null");
Assert.notNull(value, "Parameter value must not be null");
this.renderParameters.put(key, new String[] {value});
}
public String getRenderParameter(String key) {
Assert.notNull(key, "Parameter key must not be null");
String[] arr = this.renderParameters.get(key);
return (arr != null && arr.length > 0 ? arr[0] : null);
super.setRenderParameter(key, value);
this.redirectAllowed = false;
}
public void setRenderParameter(String key, String[] values) {
if (this.redirectedUrl != null) {
throw new IllegalStateException("Cannot set render parameters after sendRedirect has been called");
}
Assert.notNull(key, "Parameter key must not be null");
Assert.notNull(values, "Parameter values must not be null");
this.renderParameters.put(key, values);
super.setRenderParameter(key, values);
this.redirectAllowed = false;
}
public String[] getRenderParameterValues(String key) {
Assert.notNull(key, "Parameter key must not be null");
return this.renderParameters.get(key);
public void sendRedirect(String location) throws IOException {
if (!this.redirectAllowed) {
throw new IllegalStateException(
"Cannot call sendRedirect after windowState, portletMode, or renderParameters have been set");
}
Assert.notNull(location, "Redirect URL must not be null");
this.redirectedUrl = location;
}
public Iterator getRenderParameterNames() {
return this.renderParameters.keySet().iterator();
public void sendRedirect(String location, String renderUrlParamName) throws IOException {
sendRedirect(location);
if (renderUrlParamName != null) {
setRenderParameter(renderUrlParamName, location);
}
}
public Map getRenderParameterMap() {
return Collections.unmodifiableMap(this.renderParameters);
public String getRedirectedUrl() {
return this.redirectedUrl;
}
}

View File

@@ -0,0 +1,152 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* 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 org.springframework.mock.web.portlet;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.portlet.BaseURL;
import javax.portlet.PortletSecurityException;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Mock implementation of the {@link javax.portlet.BaseURL} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public abstract class MockBaseURL implements BaseURL {
public static final String URL_TYPE_RENDER = "render";
public static final String URL_TYPE_ACTION = "action";
private static final String ENCODING = "UTF-8";
protected final Map<String, String[]> parameters = new LinkedHashMap<String, String[]>();
private boolean secure = false;
private final Map<String, String[]> properties = new LinkedHashMap<String, String[]>();
//---------------------------------------------------------------------
// BaseURL methods
//---------------------------------------------------------------------
public void setParameter(String key, String value) {
Assert.notNull(key, "Parameter key must be null");
Assert.notNull(value, "Parameter value must not be null");
this.parameters.put(key, new String[] {value});
}
public void setParameter(String key, String[] values) {
Assert.notNull(key, "Parameter key must be null");
Assert.notNull(values, "Parameter values must not be null");
this.parameters.put(key, values);
}
public void setParameters(Map<String, String[]> parameters) {
Assert.notNull(parameters, "Parameters Map must not be null");
this.parameters.clear();
this.parameters.putAll(parameters);
}
public Set<String> getParameterNames() {
return this.parameters.keySet();
}
public String getParameter(String name) {
String[] arr = this.parameters.get(name);
return (arr != null && arr.length > 0 ? arr[0] : null);
}
public String[] getParameterValues(String name) {
return this.parameters.get(name);
}
public Map<String, String[]> getParameterMap() {
return Collections.unmodifiableMap(this.parameters);
}
public void setSecure(boolean secure) throws PortletSecurityException {
this.secure = secure;
}
public boolean isSecure() {
return this.secure;
}
public void write(Writer out) throws IOException {
out.write(toString());
}
public void write(Writer out, boolean escapeXML) throws IOException {
out.write(toString());
}
public void addProperty(String key, String value) {
String[] values = this.properties.get(key);
if (values != null) {
this.properties.put(key, StringUtils.addStringToArray(values, value));
}
else {
this.properties.put(key, new String[] {value});
}
}
public void setProperty(String key, String value) {
this.properties.put(key, new String[] {value});
}
public Map<String, String[]> getProperties() {
return Collections.unmodifiableMap(this.properties);
}
protected String encodeParameter(String name, String value) {
try {
return URLEncoder.encode(name, ENCODING) + "=" + URLEncoder.encode(value, ENCODING);
}
catch (UnsupportedEncodingException ex) {
return null;
}
}
protected String encodeParameter(String name, String[] values) {
try {
StringBuilder sb = new StringBuilder();
for (int i = 0, n = values.length; i < n; i++) {
sb.append(i > 0 ? ";" : "").append(URLEncoder.encode(name, ENCODING)).append("=")
.append(URLEncoder.encode(values[i], ENCODING));
}
return sb.toString();
}
catch (UnsupportedEncodingException ex) {
return null;
}
}
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* 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 org.springframework.mock.web.portlet;
import javax.portlet.CacheControl;
/**
* Mock implementation of the {@link javax.portlet.CacheControl} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockCacheControl implements CacheControl {
private int expirationTime = 0;
private boolean publicScope = false;
private String etag;
private boolean useCachedContent = false;
public int getExpirationTime() {
return this.expirationTime;
}
public void setExpirationTime(int time) {
this.expirationTime = time;
}
public boolean isPublicScope() {
return this.publicScope;
}
public void setPublicScope(boolean publicScope) {
this.publicScope = publicScope;
}
public String getETag() {
return this.etag;
}
public void setETag(String token) {
this.etag = token;
}
public boolean useCachedContent() {
return this.useCachedContent;
}
public void setUseCachedContent(boolean useCachedContent) {
this.useCachedContent = useCachedContent;
}
}

View File

@@ -0,0 +1,129 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* 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 org.springframework.mock.web.portlet;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import javax.portlet.ClientDataRequest;
import javax.portlet.PortalContext;
import javax.portlet.PortletContext;
import javax.portlet.PortletMode;
/**
* Mock implementation of the {@link javax.portlet.ClientDataRequest} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockClientDataRequest extends MockPortletRequest implements ClientDataRequest {
private String characterEncoding;
private byte[] content;
private String contentType;
private String method;
/**
* Create a new MockClientDataRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @see org.springframework.mock.web.portlet.MockPortalContext
* @see org.springframework.mock.web.portlet.MockPortletContext
*/
public MockClientDataRequest() {
super();
}
/**
* Create a new MockClientDataRequest with a default {@link MockPortalContext}.
* @param portletContext the PortletContext that the request runs in
*/
public MockClientDataRequest(PortletContext portletContext) {
super(portletContext);
}
/**
* Create a new MockClientDataRequest.
* @param portalContext the PortalContext that the request runs in
* @param portletContext the PortletContext that the request runs in
*/
public MockClientDataRequest(PortalContext portalContext, PortletContext portletContext) {
super(portalContext, portletContext);
}
public void setContent(byte[] content) {
this.content = content;
}
public InputStream getPortletInputStream() throws IOException {
if (this.content != null) {
return new ByteArrayInputStream(this.content);
}
else {
return null;
}
}
public void setCharacterEncoding(String characterEncoding) {
this.characterEncoding = characterEncoding;
}
public BufferedReader getReader() throws UnsupportedEncodingException {
if (this.content != null) {
InputStream sourceStream = new ByteArrayInputStream(this.content);
Reader sourceReader = (this.characterEncoding != null) ?
new InputStreamReader(sourceStream, this.characterEncoding) : new InputStreamReader(sourceStream);
return new BufferedReader(sourceReader);
}
else {
return null;
}
}
public String getCharacterEncoding() {
return this.characterEncoding;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getContentType() {
return this.contentType;
}
public int getContentLength() {
return (this.content != null ? content.length : -1);
}
public void setMethod(String method) {
this.method = method;
}
public String getMethod() {
return this.method;
}
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* 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 org.springframework.mock.web.portlet;
import java.io.Serializable;
import javax.portlet.Event;
import javax.xml.namespace.QName;
/**
* Mock implementation of the {@link javax.portlet.Event} interface.
*
* @author Juergen Hoeller
* @since 3.0
* @see MockEventRequest
*/
public class MockEvent implements Event {
private final QName name;
private final Serializable value;
/**
* Create a new MockEvent with the given name.
* @param name the name of the event
*/
public MockEvent(QName name) {
this.name = name;
this.value = null;
}
/**
* Create a new MockEvent with the given name and value.
* @param name the name of the event
* @param value the associated payload of the event
*/
public MockEvent(QName name, Serializable value) {
this.name = name;
this.value = value;
}
/**
* Create a new MockEvent with the given name.
* @param name the name of the event
*/
public MockEvent(String name) {
this.name = new QName(name);
this.value = null;
}
/**
* Create a new MockEvent with the given name and value.
* @param name the name of the event
* @param value the associated payload of the event
*/
public MockEvent(String name, Serializable value) {
this.name = new QName(name);
this.value = value;
}
public QName getQName() {
return this.name;
}
public String getName() {
return this.name.getLocalPart();
}
public Serializable getValue() {
return this.value;
}
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* 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 org.springframework.mock.web.portlet;
import javax.portlet.Event;
import javax.portlet.EventRequest;
import javax.portlet.PortalContext;
import javax.portlet.PortletContext;
/**
* Mock implementation of the {@link javax.portlet.EventRequest} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockEventRequest extends MockPortletRequest implements EventRequest {
private final Event event;
private String method;
/**
* Create a new MockEventRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @param event the event that this request wraps
* @see MockEvent
*/
public MockEventRequest(Event event) {
super();
this.event = event;
}
/**
* Create a new MockEventRequest with a default {@link MockPortalContext}.
* @param event the event that this request wraps
* @param portletContext the PortletContext that the request runs in
* @see MockEvent
*/
public MockEventRequest(Event event, PortletContext portletContext) {
super(portletContext);
this.event = event;
}
/**
* Create a new MockEventRequest.
* @param event the event that this request wraps
* @param portalContext the PortletContext that the request runs in
* @param portletContext the PortletContext that the request runs in
*/
public MockEventRequest(Event event, PortalContext portalContext, PortletContext portletContext) {
super(portalContext, portletContext);
this.event = event;
}
@Override
protected String getLifecyclePhase() {
return EVENT_PHASE;
}
public Event getEvent() {
return this.event;
}
public void setMethod(String method) {
this.method = method;
}
public String getMethod() {
return this.method;
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* 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 org.springframework.mock.web.portlet;
import javax.portlet.EventResponse;
import javax.portlet.EventRequest;
/**
* Mock implementation of the {@link javax.portlet.EventResponse} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockEventResponse extends MockStateAwareResponse implements EventResponse {
public void setRenderParameters(EventRequest request) {
setRenderParameters(request.getParameterMap());
}
}

View File

@@ -0,0 +1,243 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* 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 org.springframework.mock.web.portlet;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Locale;
import javax.portlet.CacheControl;
import javax.portlet.MimeResponse;
import javax.portlet.PortalContext;
import javax.portlet.PortletRequest;
import javax.portlet.PortletURL;
import javax.portlet.ResourceURL;
import org.springframework.util.CollectionUtils;
import org.springframework.web.util.WebUtils;
/**
* Mock implementation of the {@link javax.portlet.MimeResponse} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockMimeResponse extends MockPortletResponse implements MimeResponse {
private PortletRequest request;
private String contentType;
private String characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING;
private PrintWriter writer;
private Locale locale = Locale.getDefault();
private int bufferSize = 4096;
private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
private final CacheControl cacheControl = new MockCacheControl();
private boolean committed;
private String includedUrl;
private String forwardedUrl;
/**
* Create a new MockMimeResponse with a default {@link MockPortalContext}.
* @see org.springframework.mock.web.portlet.MockPortalContext
*/
public MockMimeResponse() {
super();
}
/**
* Create a new MockMimeResponse.
* @param portalContext the PortalContext defining the supported
* PortletModes and WindowStates
*/
public MockMimeResponse(PortalContext portalContext) {
super(portalContext);
}
/**
* Create a new MockMimeResponse.
* @param portalContext the PortalContext defining the supported
* PortletModes and WindowStates
* @param request the corresponding render/resource request that this response
* is being generated for
*/
public MockMimeResponse(PortalContext portalContext, PortletRequest request) {
super(portalContext);
this.request = request;
}
//---------------------------------------------------------------------
// RenderResponse methods
//---------------------------------------------------------------------
public void setContentType(String contentType) {
if (this.request != null) {
Enumeration<String> supportedTypes = this.request.getResponseContentTypes();
if (!CollectionUtils.contains(supportedTypes, contentType)) {
throw new IllegalArgumentException("Content type [" + contentType + "] not in supported list: " +
Collections.list(supportedTypes));
}
}
this.contentType = contentType;
}
public String getContentType() {
return this.contentType;
}
public void setCharacterEncoding(String characterEncoding) {
this.characterEncoding = characterEncoding;
}
public String getCharacterEncoding() {
return this.characterEncoding;
}
public PrintWriter getWriter() throws UnsupportedEncodingException {
if (this.writer == null) {
Writer targetWriter = (this.characterEncoding != null
? new OutputStreamWriter(this.outputStream, this.characterEncoding)
: new OutputStreamWriter(this.outputStream));
this.writer = new PrintWriter(targetWriter);
}
return this.writer;
}
public byte[] getContentAsByteArray() {
flushBuffer();
return this.outputStream.toByteArray();
}
public String getContentAsString() throws UnsupportedEncodingException {
flushBuffer();
return (this.characterEncoding != null)
? this.outputStream.toString(this.characterEncoding)
: this.outputStream.toString();
}
public void setLocale(Locale locale) {
this.locale = locale;
}
public Locale getLocale() {
return this.locale;
}
public void setBufferSize(int bufferSize) {
this.bufferSize = bufferSize;
}
public int getBufferSize() {
return this.bufferSize;
}
public void flushBuffer() {
if (this.writer != null) {
this.writer.flush();
}
if (this.outputStream != null) {
try {
this.outputStream.flush();
}
catch (IOException ex) {
throw new IllegalStateException("Could not flush OutputStream: " + ex.getMessage());
}
}
this.committed = true;
}
public void resetBuffer() {
if (this.committed) {
throw new IllegalStateException("Cannot reset buffer - response is already committed");
}
this.outputStream.reset();
}
public void setCommitted(boolean committed) {
this.committed = committed;
}
public boolean isCommitted() {
return this.committed;
}
public void reset() {
resetBuffer();
this.characterEncoding = null;
this.contentType = null;
this.locale = null;
}
public OutputStream getPortletOutputStream() throws IOException {
return this.outputStream;
}
public PortletURL createRenderURL() {
return new MockPortletURL(getPortalContext(), MockPortletURL.URL_TYPE_RENDER);
}
public PortletURL createActionURL() {
return new MockPortletURL(getPortalContext(), MockPortletURL.URL_TYPE_ACTION);
}
public ResourceURL createResourceURL() {
return new MockResourceURL();
}
public CacheControl getCacheControl() {
return this.cacheControl;
}
//---------------------------------------------------------------------
// Methods for MockPortletRequestDispatcher
//---------------------------------------------------------------------
public void setIncludedUrl(String includedUrl) {
this.includedUrl = includedUrl;
}
public String getIncludedUrl() {
return this.includedUrl;
}
public void setForwardedUrl(String forwardedUrl) {
this.forwardedUrl = forwardedUrl;
}
public String getForwardedUrl() {
return this.forwardedUrl;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,16 +16,19 @@
package org.springframework.mock.web.portlet;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.LinkedHashMap;
import java.util.Collections;
import java.util.Set;
import javax.portlet.PortletConfig;
import javax.portlet.PortletContext;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import org.springframework.util.Assert;
@@ -46,6 +49,18 @@ public class MockPortletConfig implements PortletConfig {
private final Map<String, String> initParameters = new LinkedHashMap<String, String>();
private final Set<String> publicRenderParameterNames = new LinkedHashSet<String>();
private String defaultNamespace = XMLConstants.NULL_NS_URI;
private final Set<QName> publishingEventQNames = new LinkedHashSet<QName>();
private final Set<QName> processingEventQNames = new LinkedHashSet<QName>();
private final Set<Locale> supportedLocales = new LinkedHashSet<Locale>();
private final Map<String, String[]> containerRuntimeOptions = new LinkedHashMap<String, String[]>();
/**
* Create a new MockPortletConfig with a default {@link MockPortletContext}.
@@ -113,4 +128,56 @@ public class MockPortletConfig implements PortletConfig {
return Collections.enumeration(this.initParameters.keySet());
}
public void addPublicRenderParameterName(String name) {
this.publicRenderParameterNames.add(name);
}
public Enumeration<String> getPublicRenderParameterNames() {
return Collections.enumeration(this.publicRenderParameterNames);
}
public void setDefaultNamespace(String defaultNamespace) {
this.defaultNamespace = defaultNamespace;
}
public String getDefaultNamespace() {
return this.defaultNamespace;
}
public void addPublishingEventQName(QName name) {
this.publishingEventQNames.add(name);
}
public Enumeration<QName> getPublishingEventQNames() {
return Collections.enumeration(this.publishingEventQNames);
}
public void addProcessingEventQName(QName name) {
this.processingEventQNames.add(name);
}
public Enumeration<QName> getProcessingEventQNames() {
return Collections.enumeration(this.processingEventQNames);
}
public void addSupportedLocale(Locale locale) {
this.supportedLocales.add(locale);
}
public Enumeration<Locale> getSupportedLocales() {
return Collections.enumeration(this.supportedLocales);
}
public void addContainerRuntimeOption(String key, String value) {
this.containerRuntimeOptions.put(key, new String[] {value});
}
public void addContainerRuntimeOption(String key, String[] values) {
this.containerRuntimeOptions.put(key, values);
}
public Map<String, String[]> getContainerRuntimeOptions() {
return Collections.unmodifiableMap(this.containerRuntimeOptions);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,6 +25,7 @@ import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.portlet.PortletContext;
@@ -63,6 +64,8 @@ public class MockPortletContext implements PortletContext {
private String portletContextName = "MockPortletContext";
private Set<String> containerRuntimeOptions = new LinkedHashSet<String>();
/**
* Create a new MockPortletContext with no base path and a
@@ -248,7 +251,15 @@ public class MockPortletContext implements PortletContext {
}
public String getPortletContextName() {
return portletContextName;
return this.portletContextName;
}
public void addContainerRuntimeOption(String key) {
this.containerRuntimeOptions.add(key);
}
public Enumeration<String> getContainerRuntimeOptions() {
return Collections.enumeration(this.containerRuntimeOptions);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,6 +33,7 @@ import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;
import javax.portlet.WindowState;
import javax.servlet.http.Cookie;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
@@ -90,6 +91,12 @@ public class MockPortletRequest implements PortletRequest {
private int serverPort = 80;
private String windowID;
private Cookie[] cookies;
private final Set<String> publicParameterNames = new HashSet<String>();
/**
* Create a new MockPortletRequest with a default {@link MockPortalContext}
@@ -120,6 +127,7 @@ public class MockPortletRequest implements PortletRequest {
this.portletContext = (portletContext != null ? portletContext : new MockPortletContext());
this.responseContentTypes.add("text/html");
this.locales.add(Locale.ENGLISH);
this.attributes.put(LIFECYCLE_PHASE, getLifecyclePhase());
}
@@ -127,6 +135,13 @@ public class MockPortletRequest implements PortletRequest {
// Lifecycle methods
//---------------------------------------------------------------------
/**
* Return the Portlet 2.0 lifecycle id for the current phase.
*/
protected String getLifecyclePhase() {
return null;
}
/**
* Return whether this request is still active (that is, not completed yet).
*/
@@ -363,7 +378,7 @@ public class MockPortletRequest implements PortletRequest {
return this.parameters.get(name);
}
public Map getParameterMap() {
public Map<String, String[]> getParameterMap() {
return Collections.unmodifiableMap(this.parameters);
}
@@ -459,4 +474,54 @@ public class MockPortletRequest implements PortletRequest {
return this.serverPort;
}
public void setWindowID(String windowID) {
this.windowID = windowID;
}
public String getWindowID() {
return this.windowID;
}
public void setCookies(Cookie[] cookies) {
this.cookies = cookies;
}
public Cookie[] getCookies() {
return this.cookies;
}
public Map<String, String[]> getPrivateParameterMap() {
if (!this.publicParameterNames.isEmpty()) {
Map<String, String[]> filtered = new LinkedHashMap<String, String[]>();
for (String key : this.parameters.keySet()) {
if (!this.publicParameterNames.contains(key)) {
filtered.put(key, this.parameters.get(key));
}
}
return filtered;
}
else {
return Collections.unmodifiableMap(this.parameters);
}
}
public Map<String, String[]> getPublicParameterMap() {
if (!this.publicParameterNames.isEmpty()) {
Map<String, String[]> filtered = new LinkedHashMap<String, String[]>();
for (String key : this.parameters.keySet()) {
if (this.publicParameterNames.contains(key)) {
filtered.put(key, this.parameters.get(key));
}
}
return filtered;
}
else {
return Collections.emptyMap();
}
}
public void registerPublicParameter(String name) {
this.publicParameterNames.add(name);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,9 +17,10 @@
package org.springframework.mock.web.portlet;
import java.io.IOException;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.PortletResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
@@ -53,15 +54,31 @@ public class MockPortletRequestDispatcher implements PortletRequestDispatcher {
public void include(RenderRequest request, RenderResponse response) throws PortletException, IOException {
include((PortletRequest) request, (PortletResponse) response);
}
public void include(PortletRequest request, PortletResponse response) throws PortletException, IOException {
Assert.notNull(request, "Request must not be null");
Assert.notNull(response, "Response must not be null");
if (!(response instanceof MockRenderResponse)) {
throw new IllegalArgumentException("MockPortletRequestDispatcher requires MockRenderResponse");
if (!(response instanceof MockMimeResponse)) {
throw new IllegalArgumentException("MockPortletRequestDispatcher requires MockMimeResponse");
}
((MockRenderResponse) response).setIncludedUrl(this.url);
((MockMimeResponse) response).setIncludedUrl(this.url);
if (logger.isDebugEnabled()) {
logger.debug("MockPortletRequestDispatcher: including URL [" + this.url + "]");
}
}
public void forward(PortletRequest request, PortletResponse response) throws PortletException, IOException {
Assert.notNull(request, "Request must not be null");
Assert.notNull(response, "Response must not be null");
if (!(response instanceof MockMimeResponse)) {
throw new IllegalArgumentException("MockPortletRequestDispatcher requires MockMimeResponse");
}
((MockMimeResponse) response).setForwardedUrl(this.url);
if (logger.isDebugEnabled()) {
logger.debug("MockPortletRequestDispatcher: forwarding to URL [" + this.url + "]");
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,12 +16,20 @@
package org.springframework.mock.web.portlet;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.portlet.PortalContext;
import javax.portlet.PortletResponse;
import javax.servlet.http.Cookie;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.springframework.util.Assert;
@@ -38,6 +46,14 @@ public class MockPortletResponse implements PortletResponse {
private final Map<String, String[]> properties = new LinkedHashMap<String, String[]>();
private String namespace = "";
private final Set<Cookie> cookies = new LinkedHashSet<Cookie>();
private final Map<String, Element[]> xmlProperties = new LinkedHashMap<String, Element[]>();
private Document xmlDocument;
/**
* Create a new MockPortletResponse with a default {@link MockPortalContext}.
@@ -88,8 +104,8 @@ public class MockPortletResponse implements PortletResponse {
this.properties.put(key, new String[] {value});
}
public Set getPropertyNames() {
return this.properties.keySet();
public Set<String> getPropertyNames() {
return Collections.unmodifiableSet(this.properties.keySet());
}
public String getProperty(String key) {
@@ -107,4 +123,73 @@ public class MockPortletResponse implements PortletResponse {
return path;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public String getNamespace() {
return this.namespace;
}
public void addProperty(Cookie cookie) {
Assert.notNull(cookie, "Cookie must not be null");
this.cookies.add(cookie);
}
public Cookie[] getCookies() {
return this.cookies.toArray(new Cookie[this.cookies.size()]);
}
public Cookie getCookie(String name) {
Assert.notNull(name, "Cookie name must not be null");
for (Cookie cookie : this.cookies) {
if (name.equals(cookie.getName())) {
return cookie;
}
}
return null;
}
public void addProperty(String key, Element value) {
Assert.notNull(key, "Property key must not be null");
Element[] oldArr = this.xmlProperties.get(key);
if (oldArr != null) {
Element[] newArr = new Element[oldArr.length + 1];
System.arraycopy(oldArr, 0, newArr, 0, oldArr.length);
newArr[oldArr.length] = value;
this.xmlProperties.put(key, newArr);
}
else {
this.xmlProperties.put(key, new Element[] {value});
}
}
public Set<String> getXmlPropertyNames() {
return Collections.unmodifiableSet(this.xmlProperties.keySet());
}
public Element getXmlProperty(String key) {
Assert.notNull(key, "Property key must not be null");
Element[] arr = this.xmlProperties.get(key);
return (arr != null && arr.length > 0 ? arr[0] : null);
}
public Element[] getXmlProperties(String key) {
Assert.notNull(key, "Property key must not be null");
return this.xmlProperties.get(key);
}
public Element createElement(String tagName) throws DOMException {
if (this.xmlDocument == null) {
try {
this.xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
}
catch (ParserConfigurationException ex) {
throw new DOMException(DOMException.INVALID_STATE_ERR, ex.toString());
}
}
return this.xmlDocument.createElement(tagName);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -184,7 +184,23 @@ public class MockPortletSession implements PortletSession {
}
public PortletContext getPortletContext() {
return portletContext;
return this.portletContext;
}
public Map<String, Object> getAttributeMap() {
return Collections.unmodifiableMap(this.portletAttributes);
}
public Map<String, Object> getAttributeMap(int scope) {
if (scope == PortletSession.PORTLET_SCOPE) {
return Collections.unmodifiableMap(this.portletAttributes);
}
else if (scope == PortletSession.APPLICATION_SCOPE) {
return Collections.unmodifiableMap(this.applicationAttributes);
}
else {
return Collections.emptyMap();
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,18 +16,10 @@
package org.springframework.mock.web.portlet;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.portlet.PortalContext;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.PortletSecurityException;
import javax.portlet.PortletURL;
import javax.portlet.WindowState;
import javax.portlet.WindowStateException;
@@ -42,14 +34,12 @@ import org.springframework.util.CollectionUtils;
* @author Juergen Hoeller
* @since 2.0
*/
public class MockPortletURL implements PortletURL {
public class MockPortletURL extends MockBaseURL implements PortletURL {
public static final String URL_TYPE_RENDER = "render";
public static final String URL_TYPE_ACTION = "action";
private static final String ENCODING = "UTF-8";
private final PortalContext portalContext;
@@ -59,10 +49,6 @@ public class MockPortletURL implements PortletURL {
private PortletMode portletMode;
private final Map<String, String[]> parameters = new LinkedHashMap<String, String[]>();
private boolean secure = false;
/**
* Create a new MockPortletURL for the given URL type.
@@ -90,6 +76,10 @@ public class MockPortletURL implements PortletURL {
this.windowState = windowState;
}
public WindowState getWindowState() {
return this.windowState;
}
public void setPortletMode(PortletMode portletMode) throws PortletModeException {
if (!CollectionUtils.contains(this.portalContext.getSupportedPortletModes(), portletMode)) {
throw new PortletModeException("PortletMode not supported", portletMode);
@@ -97,77 +87,12 @@ public class MockPortletURL implements PortletURL {
this.portletMode = portletMode;
}
public void setParameter(String key, String value) {
Assert.notNull(key, "Parameter key must be null");
Assert.notNull(value, "Parameter value must not be null");
this.parameters.put(key, new String[] {value});
public PortletMode getPortletMode() {
return this.portletMode;
}
public void setParameter(String key, String[] values) {
Assert.notNull(key, "Parameter key must be null");
Assert.notNull(values, "Parameter values must not be null");
this.parameters.put(key, values);
}
public void setParameters(Map parameters) {
Assert.notNull(parameters, "Parameters Map must not be null");
this.parameters.clear();
for (Iterator it = parameters.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
Assert.isTrue(entry.getKey() instanceof String, "Key must be of type String");
Assert.isTrue(entry.getValue() instanceof String[], "Value must be of type String[]");
this.parameters.put((String) entry.getKey(), (String[]) entry.getValue());
}
}
public Set<String> getParameterNames() {
return this.parameters.keySet();
}
public String getParameter(String name) {
String[] arr = this.parameters.get(name);
return (arr != null && arr.length > 0 ? arr[0] : null);
}
public String[] getParameterValues(String name) {
return this.parameters.get(name);
}
public Map<String, String[]> getParameterMap() {
return Collections.unmodifiableMap(this.parameters);
}
public void setSecure(boolean secure) throws PortletSecurityException {
this.secure = secure;
}
public boolean isSecure() {
return this.secure;
}
private String encodeParameter(String name, String value) {
try {
return URLEncoder.encode(name, ENCODING) + "=" + URLEncoder.encode(value, ENCODING);
}
catch (UnsupportedEncodingException ex) {
return null;
}
}
private String encodeParameter(String name, String[] values) {
try {
StringBuilder sb = new StringBuilder();
for (int i = 0, n = values.length; i < n; i++) {
sb.append((i > 0 ? ";" : "") +
URLEncoder.encode(name, ENCODING) + "=" +
URLEncoder.encode(values[i], ENCODING));
}
return sb.toString();
}
catch (UnsupportedEncodingException ex) {
return null;
}
public void removePublicRenderParameter(String name) {
this.parameters.remove(name);
}
@@ -183,7 +108,7 @@ public class MockPortletURL implements PortletURL {
for (Map.Entry<String, String[]> entry : this.parameters.entrySet()) {
sb.append(";").append(encodeParameter("param_" + entry.getKey(), entry.getValue()));
}
return (this.secure ? "https:" : "http:") +
return (isSecure() ? "https:" : "http:") +
"//localhost/mockportlet?" + sb.toString();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@ import javax.portlet.PortalContext;
import javax.portlet.PortletContext;
import javax.portlet.PortletMode;
import javax.portlet.RenderRequest;
import javax.portlet.WindowState;
/**
* Mock implementation of the {@link javax.portlet.RenderRequest} interface.
@@ -50,6 +51,18 @@ public class MockRenderRequest extends MockPortletRequest implements RenderReque
setPortletMode(portletMode);
}
/**
* Create a new MockRenderRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @param portletMode the mode that the portlet runs in
* @param windowState the window state to run the portlet in
*/
public MockRenderRequest(PortletMode portletMode, WindowState windowState) {
super();
setPortletMode(portletMode);
setWindowState(windowState);
}
/**
* Create a new MockRenderRequest with a default {@link MockPortalContext}.
* @param portletContext the PortletContext that the request runs in
@@ -67,4 +80,14 @@ public class MockRenderRequest extends MockPortletRequest implements RenderReque
super(portalContext, portletContext);
}
@Override
protected String getLifecyclePhase() {
return RENDER_PHASE;
}
public String getETag() {
return getProperty(RenderRequest.ETAG);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,21 +16,12 @@
package org.springframework.mock.web.portlet;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Locale;
import java.util.Collection;
import javax.portlet.PortalContext;
import javax.portlet.PortletURL;
import javax.portlet.PortletMode;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.springframework.web.util.WebUtils;
/**
* Mock implementation of the {@link javax.portlet.RenderResponse} interface.
*
@@ -38,27 +29,11 @@ import org.springframework.web.util.WebUtils;
* @author Juergen Hoeller
* @since 2.0
*/
public class MockRenderResponse extends MockPortletResponse implements RenderResponse {
private String contentType;
private String namespace = "MockPortlet";
public class MockRenderResponse extends MockMimeResponse implements RenderResponse {
private String title;
private String characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING;
private PrintWriter writer;
private Locale locale = Locale.getDefault();
private int bufferSize = 4096;
private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
private boolean committed;
private String includedUrl;
private Collection<PortletMode> nextPossiblePortletModes;
/**
@@ -78,139 +53,36 @@ public class MockRenderResponse extends MockPortletResponse implements RenderRes
super(portalContext);
}
/**
* Create a new MockRenderResponse.
* @param portalContext the PortalContext defining the supported
* PortletModes and WindowStates
* @param request the corresponding render request that this response
* is generated for
*/
public MockRenderResponse(PortalContext portalContext, RenderRequest request) {
super(portalContext, request);
}
//---------------------------------------------------------------------
// RenderResponse methods
//---------------------------------------------------------------------
public String getContentType() {
return this.contentType;
}
public PortletURL createRenderURL() {
PortletURL url = new MockPortletURL(getPortalContext(), MockPortletURL.URL_TYPE_RENDER);
return url;
}
public PortletURL createActionURL() {
PortletURL url = new MockPortletURL(getPortalContext(), MockPortletURL.URL_TYPE_ACTION);
return url;
}
public String getNamespace() {
return this.namespace;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
return this.title;
}
public void setContentType(String contentType) {
this.contentType = contentType;
public void setNextPossiblePortletModes(Collection<PortletMode> portletModes) {
this.nextPossiblePortletModes = portletModes;
}
public void setCharacterEncoding(String characterEncoding) {
this.characterEncoding = characterEncoding;
}
public String getCharacterEncoding() {
return this.characterEncoding;
}
public PrintWriter getWriter() throws UnsupportedEncodingException {
if (this.writer == null) {
Writer targetWriter = (this.characterEncoding != null
? new OutputStreamWriter(this.outputStream, this.characterEncoding)
: new OutputStreamWriter(this.outputStream));
this.writer = new PrintWriter(targetWriter);
}
return this.writer;
}
public byte[] getContentAsByteArray() {
flushBuffer();
return this.outputStream.toByteArray();
}
public String getContentAsString() throws UnsupportedEncodingException {
flushBuffer();
return (this.characterEncoding != null)
? this.outputStream.toString(this.characterEncoding)
: this.outputStream.toString();
}
public void setLocale(Locale locale) {
this.locale = locale;
}
public Locale getLocale() {
return this.locale;
}
public void setBufferSize(int bufferSize) {
this.bufferSize = bufferSize;
}
public int getBufferSize() {
return this.bufferSize;
}
public void flushBuffer() {
if (this.writer != null) {
this.writer.flush();
}
if (this.outputStream != null) {
try {
this.outputStream.flush();
}
catch (IOException ex) {
throw new IllegalStateException("Could not flush OutputStream: " + ex.getMessage());
}
}
this.committed = true;
}
public void resetBuffer() {
if (this.committed) {
throw new IllegalStateException("Cannot reset buffer - response is already committed");
}
this.outputStream.reset();
}
public void setCommitted(boolean committed) {
this.committed = committed;
}
public boolean isCommitted() {
return this.committed;
}
public void reset() {
resetBuffer();
this.characterEncoding = null;
this.contentType = null;
this.locale = null;
}
public OutputStream getPortletOutputStream() throws IOException {
return this.outputStream;
}
//---------------------------------------------------------------------
// Methods for MockPortletRequestDispatcher
//---------------------------------------------------------------------
public void setIncludedUrl(String includedUrl) {
this.includedUrl = includedUrl;
}
public String getIncludedUrl() {
return includedUrl;
public Collection<PortletMode> getNextPossiblePortletModes() {
return this.nextPossiblePortletModes;
}
}

View File

@@ -0,0 +1,128 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* 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 org.springframework.mock.web.portlet;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.portlet.PortalContext;
import javax.portlet.PortletContext;
import javax.portlet.RenderRequest;
import javax.portlet.ResourceRequest;
/**
* Mock implementation of the {@link javax.portlet.ResourceRequest} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockResourceRequest extends MockClientDataRequest implements ResourceRequest {
private String resourceID;
private String cacheability;
private final Map<String, String[]> privateRenderParameterMap = new LinkedHashMap<String, String[]>();
/**
* Create a new MockResourceRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @see org.springframework.mock.web.portlet.MockPortalContext
* @see org.springframework.mock.web.portlet.MockPortletContext
*/
public MockResourceRequest() {
super();
}
/**
* Create a new MockResourceRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @param resourceID the resource id for this request
*/
public MockResourceRequest(String resourceID) {
super();
this.resourceID = resourceID;
}
/**
* Create a new MockResourceRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @param url the resource URL for this request
*/
public MockResourceRequest(MockResourceURL url) {
super();
this.resourceID = url.getResourceID();
this.cacheability = url.getCacheability();
}
/**
* Create a new MockResourceRequest with a default {@link MockPortalContext}.
* @param portletContext the PortletContext that the request runs in
*/
public MockResourceRequest(PortletContext portletContext) {
super(portletContext);
}
/**
* Create a new MockResourceRequest.
* @param portalContext the PortalContext that the request runs in
* @param portletContext the PortletContext that the request runs in
*/
public MockResourceRequest(PortalContext portalContext, PortletContext portletContext) {
super(portalContext, portletContext);
}
@Override
protected String getLifecyclePhase() {
return RESOURCE_PHASE;
}
public void setResourceID(String resourceID) {
this.resourceID = resourceID;
}
public String getResourceID() {
return this.resourceID;
}
public void setCacheability(String cacheLevel) {
this.cacheability = cacheLevel;
}
public String getCacheability() {
return this.cacheability;
}
public String getETag() {
return getProperty(RenderRequest.ETAG);
}
public void addPrivateRenderParameter(String key, String value) {
this.privateRenderParameterMap.put(key, new String[] {value});
}
public void addPrivateRenderParameter(String key, String[] values) {
this.privateRenderParameterMap.put(key, values);
}
public Map<String, String[]> getPrivateRenderParameterMap() {
return Collections.unmodifiableMap(this.privateRenderParameterMap);
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* 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 org.springframework.mock.web.portlet;
import javax.portlet.ResourceResponse;
/**
* Mock implementation of the {@link javax.portlet.ResourceResponse} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockResourceResponse extends MockMimeResponse implements ResourceResponse {
private int contentLength = 0;
public void setContentLength(int len) {
this.contentLength = len;
}
public int getContentLength() {
return this.contentLength;
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* 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 org.springframework.mock.web.portlet;
import java.util.Map;
import javax.portlet.ResourceURL;
/**
* Mock implementation of the {@link javax.portlet.ResourceURL} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockResourceURL extends MockBaseURL implements ResourceURL {
private String resourceID;
private String cacheability;
//---------------------------------------------------------------------
// ResourceURL methods
//---------------------------------------------------------------------
public void setResourceID(String resourceID) {
this.resourceID = resourceID;
}
public String getResourceID() {
return this.resourceID;
}
public void setCacheability(String cacheLevel) {
this.cacheability = cacheLevel;
}
public String getCacheability() {
return this.cacheability;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(encodeParameter("resourceID", this.resourceID));
if (this.cacheability != null) {
sb.append(";").append(encodeParameter("cacheability", this.cacheability));
}
for (Map.Entry<String, String[]> entry : this.parameters.entrySet()) {
sb.append(";").append(encodeParameter("param_" + entry.getKey(), entry.getValue()));
}
return (isSecure() ? "https:" : "http:") +
"//localhost/mockportlet?" + sb.toString();
}
}

View File

@@ -0,0 +1,156 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* 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 org.springframework.mock.web.portlet;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.portlet.ActionResponse;
import javax.portlet.PortalContext;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.WindowState;
import javax.portlet.WindowStateException;
import javax.portlet.StateAwareResponse;
import javax.xml.namespace.QName;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* Mock implementation of the {@link javax.portlet.StateAwareResponse} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockStateAwareResponse extends MockPortletResponse implements StateAwareResponse {
private WindowState windowState;
private PortletMode portletMode;
private final Map<String, String[]> renderParameters = new LinkedHashMap<String, String[]>();
private final Map<QName, Serializable> events = new HashMap<QName, Serializable>();
/**
* Create a new MockActionResponse with a default {@link MockPortalContext}.
* @see org.springframework.mock.web.portlet.MockPortalContext
*/
public MockStateAwareResponse() {
super();
}
/**
* Create a new MockActionResponse.
* @param portalContext the PortalContext defining the supported
* PortletModes and WindowStates
*/
public MockStateAwareResponse(PortalContext portalContext) {
super(portalContext);
}
public void setWindowState(WindowState windowState) throws WindowStateException {
if (!CollectionUtils.contains(getPortalContext().getSupportedWindowStates(), windowState)) {
throw new WindowStateException("WindowState not supported", windowState);
}
this.windowState = windowState;
}
public WindowState getWindowState() {
return this.windowState;
}
public void setPortletMode(PortletMode portletMode) throws PortletModeException {
if (!CollectionUtils.contains(getPortalContext().getSupportedPortletModes(), portletMode)) {
throw new PortletModeException("PortletMode not supported", portletMode);
}
this.portletMode = portletMode;
}
public PortletMode getPortletMode() {
return this.portletMode;
}
public void setRenderParameters(Map<String, String[]> parameters) {
Assert.notNull(parameters, "Parameters Map must not be null");
this.renderParameters.clear();
this.renderParameters.putAll(parameters);
}
public void setRenderParameter(String key, String value) {
Assert.notNull(key, "Parameter key must not be null");
Assert.notNull(value, "Parameter value must not be null");
this.renderParameters.put(key, new String[] {value});
}
public void setRenderParameter(String key, String[] values) {
Assert.notNull(key, "Parameter key must not be null");
Assert.notNull(values, "Parameter values must not be null");
this.renderParameters.put(key, values);
}
public String getRenderParameter(String key) {
Assert.notNull(key, "Parameter key must not be null");
String[] arr = this.renderParameters.get(key);
return (arr != null && arr.length > 0 ? arr[0] : null);
}
public String[] getRenderParameterValues(String key) {
Assert.notNull(key, "Parameter key must not be null");
return this.renderParameters.get(key);
}
public Iterator<String> getRenderParameterNames() {
return this.renderParameters.keySet().iterator();
}
public Map<String, String[]> getRenderParameterMap() {
return Collections.unmodifiableMap(this.renderParameters);
}
public void removePublicRenderParameter(String name) {
this.renderParameters.remove(name);
}
public void setEvent(QName name, Serializable value) {
this.events.put(name, value);
}
public void setEvent(String name, Serializable value) {
this.events.put(new QName(name), value);
}
public Iterator<QName> getEventNames() {
return this.events.keySet().iterator();
}
public Serializable getEvent(QName name) {
return this.events.get(name);
}
public Serializable getEvent(String name) {
return this.events.get(new QName(name));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,15 +22,18 @@ import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.Portlet;
import javax.portlet.PortletConfig;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
@@ -50,6 +53,7 @@ import org.springframework.web.multipart.MultipartException;
import org.springframework.web.portlet.bind.PortletRequestBindingException;
import org.springframework.web.portlet.context.PortletRequestHandledEvent;
import org.springframework.web.portlet.context.StaticPortletApplicationContext;
import org.springframework.web.portlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.portlet.handler.ParameterHandlerMapping;
import org.springframework.web.portlet.handler.ParameterMappingInterceptor;
import org.springframework.web.portlet.handler.PortletModeHandlerMapping;
@@ -352,17 +356,18 @@ public class ComplexPortletApplicationContext extends StaticPortletApplicationCo
((MyHandler) delegate).doSomething(request);
return null;
}
public ModelAndView handleResource(ResourceRequest request, ResourceResponse response, Object handler)
throws Exception {
return null;
}
public void handleEvent(EventRequest request, EventResponse response, Object handler) throws Exception {
}
}
public static class MyHandlerInterceptor1 implements HandlerInterceptor {
public boolean preHandleAction(ActionRequest request, ActionResponse response, Object handler) {
return true;
}
public void afterActionCompletion(ActionRequest request, ActionResponse response, Object handler, Exception ex) {
}
public static class MyHandlerInterceptor1 extends HandlerInterceptorAdapter {
public boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler)
throws PortletException {
@@ -398,14 +403,7 @@ public class ComplexPortletApplicationContext extends StaticPortletApplicationCo
}
public static class MyHandlerInterceptor2 implements HandlerInterceptor {
public boolean preHandleAction(ActionRequest request, ActionResponse response, Object handler) {
return true;
}
public void afterActionCompletion(ActionRequest request, ActionResponse response, Object handler, Exception ex) {
}
public static class MyHandlerInterceptor2 extends HandlerInterceptorAdapter {
public boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler)
throws PortletException {

View File

@@ -0,0 +1,923 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* 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 org.springframework.web.portlet.mvc.annotation;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.EventResponse;
import javax.portlet.MimeResponse;
import javax.portlet.PortletContext;
import javax.portlet.PortletMode;
import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.StateAwareResponse;
import javax.portlet.UnavailableException;
import javax.portlet.WindowState;
import junit.framework.TestCase;
import org.springframework.beans.BeansException;
import org.springframework.beans.DerivedTestBean;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.core.MethodParameter;
import org.springframework.mock.web.portlet.MockActionRequest;
import org.springframework.mock.web.portlet.MockActionResponse;
import org.springframework.mock.web.portlet.MockEvent;
import org.springframework.mock.web.portlet.MockEventRequest;
import org.springframework.mock.web.portlet.MockEventResponse;
import org.springframework.mock.web.portlet.MockPortletConfig;
import org.springframework.mock.web.portlet.MockPortletContext;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.mock.web.portlet.MockResourceRequest;
import org.springframework.mock.web.portlet.MockResourceResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.portlet.DispatcherPortlet;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.EventMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;
import org.springframework.web.portlet.bind.annotation.ResourceMapping;
import org.springframework.web.portlet.context.StaticPortletApplicationContext;
import org.springframework.web.portlet.mvc.AbstractController;
/**
* @author Juergen Hoeller
* @since 3.0
*/
public class Portlet20AnnotationControllerTests extends TestCase {
public void testStandardHandleMethod() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(MyController.class));
wac.refresh();
return wac;
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("test", response.getContentAsString());
}
public void testAdaptedHandleMethods() throws Exception {
doTestAdaptedHandleMethods(MyAdaptedController.class);
}
public void testAdaptedHandleMethods2() throws Exception {
doTestAdaptedHandleMethods(MyAdaptedController2.class);
}
public void testAdaptedHandleMethods3() throws Exception {
doTestAdaptedHandleMethods(MyAdaptedController3.class);
}
public void doTestAdaptedHandleMethods(final Class controllerClass) throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerClass));
wac.refresh();
return wac;
}
};
portlet.init(new MockPortletConfig());
MockActionRequest actionRequest = new MockActionRequest(PortletMode.VIEW);
MockActionResponse actionResponse = new MockActionResponse();
portlet.processAction(actionRequest, actionResponse);
assertEquals("value", actionResponse.getRenderParameter("test"));
MockRenderRequest request = new MockRenderRequest(PortletMode.EDIT);
request.addParameter("param1", "value1");
request.addParameter("param2", "2");
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("test-value1-2", response.getContentAsString());
request = new MockRenderRequest(PortletMode.HELP);
request.addParameter("name", "name1");
request.addParameter("age", "2");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("test-name1-2", response.getContentAsString());
request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("name", "name1");
request.addParameter("age", "value2");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("test-name1-typeMismatch", response.getContentAsString());
}
public void testFormController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(MyFormController.class));
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("name", "name1");
request.addParameter("age", "value2");
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString());
}
public void testModelFormController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(MyModelFormController.class));
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("name", "name1");
request.addParameter("age", "value2");
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString());
}
public void testCommandProvidingFormController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(MyCommandProvidingFormController.class));
RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class);
adapterDef.getPropertyValues().addPropertyValue("webBindingInitializer", new MyWebBindingInitializer());
wac.registerBeanDefinition("handlerAdapter", adapterDef);
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("defaultName", "myDefaultName");
request.addParameter("age", "value2");
request.addParameter("date", "2007-10-02");
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString());
}
public void testTypedCommandProvidingFormController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(MyTypedCommandProvidingFormController.class));
wac.registerBeanDefinition("controller2", new RootBeanDefinition(MyOtherTypedCommandProvidingFormController.class));
RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class);
adapterDef.getPropertyValues().addPropertyValue("webBindingInitializer", new MyWebBindingInitializer());
adapterDef.getPropertyValues().addPropertyValue("customArgumentResolver", new MySpecialArgumentResolver());
wac.registerBeanDefinition("handlerAdapter", adapterDef);
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("myParam", "myValue");
request.addParameter("defaultName", "10");
request.addParameter("age", "value2");
request.addParameter("date", "2007-10-02");
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView-Integer:10-typeMismatch-tb1-myOriginalValue", response.getContentAsString());
request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("myParam", "myOtherValue");
request.addParameter("defaultName", "10");
request.addParameter("age", "value2");
request.addParameter("date", "2007-10-02");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myOtherView-Integer:10-typeMismatch-tb1-myOriginalValue", response.getContentAsString());
request = new MockRenderRequest(PortletMode.EDIT);
request.addParameter("myParam", "myValue");
request.addParameter("defaultName", "10");
request.addParameter("age", "value2");
request.addParameter("date", "2007-10-02");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView-myName-typeMismatch-tb1-myOriginalValue", response.getContentAsString());
}
public void testBinderInitializingCommandProvidingFormController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(MyBinderInitializingCommandProvidingFormController.class));
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("defaultName", "myDefaultName");
request.addParameter("age", "value2");
request.addParameter("date", "2007-10-02");
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString());
}
public void testSpecificBinderInitializingCommandProvidingFormController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
StaticPortletApplicationContext wac = new StaticPortletApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(MySpecificBinderInitializingCommandProvidingFormController.class));
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("defaultName", "myDefaultName");
request.addParameter("age", "value2");
request.addParameter("date", "2007-10-02");
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString());
}
public void testParameterDispatchingController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
StaticPortletApplicationContext wac = new StaticPortletApplicationContext();
wac.setPortletContext(new MockPortletContext());
RootBeanDefinition bd = new RootBeanDefinition(MyParameterDispatchingController.class);
bd.setScope(WebApplicationContext.SCOPE_REQUEST);
wac.registerBeanDefinition("controller", bd);
AnnotationConfigUtils.registerAnnotationConfigProcessors(wac);
wac.refresh();
return wac;
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("view", "other");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myOtherView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("view", "my");
request.addParameter("lang", "de");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myLangView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("surprise", "!");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("mySurpriseView", response.getContentAsString());
}
public void testTypeLevelParameterDispatchingController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
StaticPortletApplicationContext wac = new StaticPortletApplicationContext();
wac.setPortletContext(new MockPortletContext());
RootBeanDefinition bd = new RootBeanDefinition(MyTypeLevelParameterDispatchingController.class);
bd.setScope(WebApplicationContext.SCOPE_REQUEST);
wac.registerBeanDefinition("controller", bd);
RootBeanDefinition bd2 = new RootBeanDefinition(MySpecialParameterDispatchingController.class);
bd2.setScope(WebApplicationContext.SCOPE_REQUEST);
wac.registerBeanDefinition("controller2", bd2);
RootBeanDefinition bd3 = new RootBeanDefinition(MyOtherSpecialParameterDispatchingController.class);
bd3.setScope(WebApplicationContext.SCOPE_REQUEST);
wac.registerBeanDefinition("controller3", bd3);
RootBeanDefinition bd4 = new RootBeanDefinition(MyParameterDispatchingController.class);
bd4.setScope(WebApplicationContext.SCOPE_REQUEST);
wac.registerBeanDefinition("controller4", bd4);
AnnotationConfigUtils.registerAnnotationConfigProcessors(wac);
wac.refresh();
return wac;
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.HELP);
MockRenderResponse response = new MockRenderResponse();
try {
portlet.render(request, response);
fail("Should have thrown UnavailableException");
}
catch (UnavailableException ex) {
// expected
}
request = new MockRenderRequest(PortletMode.EDIT);
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myDefaultView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.EDIT);
request.addParameter("myParam", "myValue");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.EDIT);
request.addParameter("myParam", "mySpecialValue");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("mySpecialView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.EDIT);
request.addParameter("myParam", "myOtherSpecialValue");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myOtherSpecialView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.VIEW);
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.EDIT);
request.addParameter("myParam", "myValue");
request.addParameter("view", "other");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myOtherView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.EDIT);
request.addParameter("myParam", "myValue");
request.addParameter("view", "my");
request.addParameter("lang", "de");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myLangView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.EDIT);
request.addParameter("myParam", "myValue");
request.addParameter("surprise", "!");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("mySurpriseView", response.getContentAsString());
}
public void testPortlet20DispatchingController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
StaticPortletApplicationContext wac = new StaticPortletApplicationContext();
wac.setPortletContext(new MockPortletContext());
RootBeanDefinition bd = new RootBeanDefinition(MyPortlet20DispatchingController.class);
bd.setScope(WebApplicationContext.SCOPE_REQUEST);
wac.registerBeanDefinition("controller", bd);
AnnotationConfigUtils.registerAnnotationConfigProcessors(wac);
wac.refresh();
return wac;
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView", response.getContentAsString());
MockActionRequest actionRequest = new MockActionRequest("this");
MockActionResponse actionResponse = new MockActionResponse();
portlet.processAction(actionRequest, actionResponse);
request = new MockRenderRequest(PortletMode.VIEW, WindowState.MAXIMIZED);
request.setParameters(actionResponse.getRenderParameterMap());
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myLargeView-value", response.getContentAsString());
actionRequest = new MockActionRequest("that");
actionResponse = new MockActionResponse();
portlet.processAction(actionRequest, actionResponse);
request = new MockRenderRequest(PortletMode.VIEW, WindowState.MAXIMIZED);
request.setParameters(actionResponse.getRenderParameterMap());
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myLargeView-value2", response.getContentAsString());
MockEventRequest eventRequest = new MockEventRequest(new MockEvent("event1"));
MockEventResponse eventResponse = new MockEventResponse();
portlet.processEvent(eventRequest, eventResponse);
request = new MockRenderRequest(PortletMode.VIEW, WindowState.MAXIMIZED);
request.setParameters(eventResponse.getRenderParameterMap());
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myLargeView-value3", response.getContentAsString());
eventRequest = new MockEventRequest(new MockEvent("event2"));
eventResponse = new MockEventResponse();
portlet.processEvent(eventRequest, eventResponse);
request = new MockRenderRequest(PortletMode.VIEW, WindowState.MAXIMIZED);
request.setParameters(eventResponse.getRenderParameterMap());
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myLargeView-value4", response.getContentAsString());
request = new MockRenderRequest(PortletMode.VIEW, WindowState.NORMAL);
request.setParameters(actionResponse.getRenderParameterMap());
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView", response.getContentAsString());
MockResourceRequest resourceRequest = new MockResourceRequest("resource1");
MockResourceResponse resourceResponse = new MockResourceResponse();
portlet.serveResource(resourceRequest, resourceResponse);
assertEquals("myResource", resourceResponse.getContentAsString());
resourceRequest = new MockResourceRequest("resource2");
resourceResponse = new MockResourceResponse();
portlet.serveResource(resourceRequest, resourceResponse);
assertEquals("myDefaultResource", resourceResponse.getContentAsString());
}
@RequestMapping("VIEW")
private static class MyController extends AbstractController {
protected ModelAndView handleRenderRequestInternal(RenderRequest request, RenderResponse response) throws Exception {
response.getWriter().write("test");
return null;
}
}
@Controller
private static class MyAdaptedController {
@RequestMapping("VIEW")
@ActionMapping
public void myHandle(ActionRequest request, ActionResponse response) throws IOException {
response.setRenderParameter("test", "value");
}
@RequestMapping("EDIT")
@RenderMapping
public void myHandle(@RequestParam("param1")String p1, @RequestParam("param2")int p2, RenderResponse response) throws IOException {
response.getWriter().write("test-" + p1 + "-" + p2);
}
@RequestMapping("HELP")
@RenderMapping
public void myHandle(TestBean tb, RenderResponse response) throws IOException {
response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge());
}
@RequestMapping("VIEW")
@RenderMapping
public void myHandle(TestBean tb, Errors errors, RenderResponse response) throws IOException {
response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode());
}
}
@Controller
private static class MyAdaptedController2 {
@RequestMapping("VIEW")
@ActionMapping
public void myHandle(ActionRequest request, ActionResponse response) throws IOException {
response.setRenderParameter("test", "value");
}
@RequestMapping("EDIT")
@RenderMapping
public void myHandle(@RequestParam("param1")String p1, int param2, RenderResponse response) throws IOException {
response.getWriter().write("test-" + p1 + "-" + param2);
}
@RequestMapping("HELP")
@RenderMapping
public void myHandle(TestBean tb, RenderResponse response) throws IOException {
response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge());
}
@RequestMapping("VIEW")
@RenderMapping
public void myHandle(TestBean tb, Errors errors, RenderResponse response) throws IOException {
response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode());
}
}
@Controller
@RequestMapping({"VIEW", "EDIT", "HELP"})
private static class MyAdaptedController3 {
@ActionMapping
public void myHandle(ActionRequest request, ActionResponse response) {
response.setRenderParameter("test", "value");
}
@RequestMapping("EDIT")
@RenderMapping
public void myHandle(@RequestParam("param1")String p1, @RequestParam("param2")int p2, RenderResponse response) throws IOException {
response.getWriter().write("test-" + p1 + "-" + p2);
}
@RequestMapping("HELP")
@RenderMapping
public void myHandle(TestBean tb, RenderResponse response) throws IOException {
response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge());
}
@RenderMapping
public void myHandle(TestBean tb, Errors errors, RenderResponse response) throws IOException {
response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode());
}
}
@Controller
private static class MyFormController {
@ModelAttribute("testBeanList")
public List<TestBean> getTestBeans() {
List<TestBean> list = new LinkedList<TestBean>();
list.add(new TestBean("tb1"));
list.add(new TestBean("tb2"));
return list;
}
@RequestMapping("VIEW")
@RenderMapping
public String myHandle(@ModelAttribute("myCommand")TestBean tb, BindingResult errors, ModelMap model) {
if (!model.containsKey("myKey")) {
model.addAttribute("myKey", "myValue");
}
return "myView";
}
}
@Controller
private static class MyModelFormController {
@ModelAttribute
public List<TestBean> getTestBeans() {
List<TestBean> list = new LinkedList<TestBean>();
list.add(new TestBean("tb1"));
list.add(new TestBean("tb2"));
return list;
}
@RequestMapping("VIEW")
@RenderMapping
public String myHandle(@ModelAttribute("myCommand")TestBean tb, BindingResult errors, Model model) {
if (!model.containsAttribute("myKey")) {
model.addAttribute("myKey", "myValue");
}
return "myView";
}
}
@Controller
private static class MyCommandProvidingFormController<T, TB, TB2> extends MyFormController {
@ModelAttribute("myCommand")
private TestBean createTestBean(
@RequestParam T defaultName, Map<String, Object> model, @RequestParam Date date) {
model.put("myKey", "myOriginalValue");
return new TestBean(defaultName.getClass().getSimpleName() + ":" + defaultName.toString());
}
@RequestMapping("VIEW")
@RenderMapping
public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, ModelMap model) {
if (!model.containsKey("myKey")) {
model.addAttribute("myKey", "myValue");
}
return "myView";
}
@RequestMapping("EDIT")
@RenderMapping
public String myOtherHandle(TB tb, BindingResult errors, ExtendedModelMap model, MySpecialArg arg) {
TestBean tbReal = (TestBean) tb;
tbReal.setName("myName");
assertTrue(model.get("ITestBean") instanceof DerivedTestBean);
assertNotNull(arg);
return super.myHandle(tbReal, errors, model);
}
@ModelAttribute
protected TB2 getModelAttr() {
return (TB2) new DerivedTestBean();
}
}
private static class MySpecialArg {
public MySpecialArg(String value) {
}
}
@Controller
@RequestMapping(params = "myParam=myValue")
private static class MyTypedCommandProvidingFormController
extends MyCommandProvidingFormController<Integer, TestBean, ITestBean> {
}
@Controller
@RequestMapping(params = "myParam=myOtherValue")
private static class MyOtherTypedCommandProvidingFormController
extends MyCommandProvidingFormController<Integer, TestBean, ITestBean> {
@RequestMapping("VIEW")
@RenderMapping
public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, ModelMap model) {
if (!model.containsKey("myKey")) {
model.addAttribute("myKey", "myValue");
}
return "myOtherView";
}
}
@Controller
private static class MyBinderInitializingCommandProvidingFormController extends MyCommandProvidingFormController {
@InitBinder
private void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
}
@Controller
private static class MySpecificBinderInitializingCommandProvidingFormController extends MyCommandProvidingFormController {
@SuppressWarnings("unused")
@InitBinder({"myCommand", "date"})
private void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
}
private static class MyWebBindingInitializer implements WebBindingInitializer {
public void initBinder(WebDataBinder binder, WebRequest request) {
assertNotNull(request.getLocale());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
}
private static class MySpecialArgumentResolver implements WebArgumentResolver {
public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) {
if (methodParameter.getParameterType().equals(MySpecialArg.class)) {
return new MySpecialArg("myValue");
}
return UNRESOLVED;
}
}
@Controller
@RequestMapping("VIEW")
private static class MyParameterDispatchingController {
@Autowired
private PortletContext portletContext;
@Autowired
private PortletSession session;
@Autowired
private PortletRequest request;
@RenderMapping
public void myHandle(RenderResponse response) throws IOException {
if (this.portletContext == null || this.session == null || this.request == null) {
throw new IllegalStateException();
}
response.getWriter().write("myView");
}
@RenderMapping(params = {"view", "!lang"})
public void myOtherHandle(RenderResponse response) throws IOException {
response.getWriter().write("myOtherView");
}
@RenderMapping(params = {"view=my", "lang=de"})
public void myLangHandle(RenderResponse response) throws IOException {
response.getWriter().write("myLangView");
}
@RenderMapping(params = "surprise")
public void mySurpriseHandle(RenderResponse response) throws IOException {
response.getWriter().write("mySurpriseView");
}
}
@Controller
@RequestMapping(value = "EDIT", params = "myParam=myValue")
private static class MyTypeLevelParameterDispatchingController extends MyParameterDispatchingController {
}
@Controller
@RequestMapping("EDIT")
private static class MySpecialParameterDispatchingController {
@RenderMapping(params = "myParam=mySpecialValue")
public void myHandle(RenderResponse response) throws IOException {
response.getWriter().write("mySpecialView");
}
@RenderMapping
public void myDefaultHandle(RenderResponse response) throws IOException {
response.getWriter().write("myDefaultView");
}
}
@Controller
@RequestMapping("EDIT")
private static class MyOtherSpecialParameterDispatchingController {
@RenderMapping(params = "myParam=myOtherSpecialValue")
public void myHandle(RenderResponse response) throws IOException {
response.getWriter().write("myOtherSpecialView");
}
}
@Controller
@RequestMapping("VIEW")
private static class MyPortlet20DispatchingController {
@ActionMapping("this")
public void myHandle(StateAwareResponse response) {
response.setRenderParameter("test", "value");
}
@ActionMapping("that")
public void myHandle2(StateAwareResponse response) {
response.setRenderParameter("test", "value2");
}
@EventMapping("event1")
public void myHandle(EventResponse response) throws IOException {
response.setRenderParameter("test", "value3");
}
@EventMapping("event2")
public void myHandle2(EventResponse response) throws IOException {
response.setRenderParameter("test", "value4");
}
@RenderMapping("MAXIMIZED")
public void myHandle(Writer writer, @RequestParam("test") String renderParam) throws IOException {
writer.write("myLargeView-" + renderParam);
}
@RenderMapping
public void myDefaultHandle(Writer writer) throws IOException {
writer.write("myView");
}
@ResourceMapping("resource1")
public void myResource(Writer writer) throws IOException {
writer.write("myResource");
}
@ResourceMapping
public void myDefaultResource(Writer writer) throws IOException {
writer.write("myDefaultResource");
}
}
private static class TestView {
public void render(String viewName, Map model, PortletRequest request, MimeResponse response) throws Exception {
TestBean tb = (TestBean) model.get("testBean");
if (tb == null) {
tb = (TestBean) model.get("myCommand");
}
if (tb.getName().endsWith("myDefaultName")) {
assertTrue(tb.getDate().getYear() == 107);
}
Errors errors = (Errors) model.get(BindingResult.MODEL_KEY_PREFIX + "testBean");
if (errors == null) {
errors = (Errors) model.get(BindingResult.MODEL_KEY_PREFIX + "myCommand");
}
if (errors.hasFieldErrors("date")) {
throw new IllegalStateException();
}
List<TestBean> testBeans = (List<TestBean>) model.get("testBeanList");
response.getWriter().write(viewName + "-" + tb.getName() + "-" + errors.getFieldError("age").getCode() +
"-" + testBeans.get(0).getName() + "-" + model.get("myKey"));
}
}
}

View File

@@ -22,9 +22,9 @@ import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.MimeResponse;
import javax.portlet.PortletContext;
import javax.portlet.PortletMode;
import javax.portlet.PortletRequest;
@@ -154,8 +154,7 @@ public class PortletAnnotationControllerTests extends TestCase {
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, RenderRequest request, RenderResponse response) throws Exception {
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
@@ -177,8 +176,7 @@ public class PortletAnnotationControllerTests extends TestCase {
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, RenderRequest request, RenderResponse response) throws Exception {
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
@@ -203,8 +201,7 @@ public class PortletAnnotationControllerTests extends TestCase {
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, RenderRequest request, RenderResponse response) throws Exception {
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
@@ -232,7 +229,7 @@ public class PortletAnnotationControllerTests extends TestCase {
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, RenderRequest request, RenderResponse response) throws Exception {
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
@@ -274,8 +271,7 @@ public class PortletAnnotationControllerTests extends TestCase {
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, RenderRequest request, RenderResponse response) throws Exception {
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
@@ -298,8 +294,7 @@ public class PortletAnnotationControllerTests extends TestCase {
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, RenderRequest request, RenderResponse response) throws Exception {
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
@@ -753,7 +748,7 @@ public class PortletAnnotationControllerTests extends TestCase {
private static class TestView {
public void render(String viewName, Map model, RenderRequest request, RenderResponse response) throws Exception {
public void render(String viewName, Map model, PortletRequest request, MimeResponse response) throws Exception {
TestBean tb = (TestBean) model.get("testBean");
if (tb == null) {
tb = (TestBean) model.get("myCommand");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,21 +16,19 @@
package org.springframework.web.portlet.util;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.portlet.PortletContext;
import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.mock.web.portlet.MockActionRequest;
@@ -41,8 +39,6 @@ import org.springframework.mock.web.portlet.MockPortletSession;
import org.springframework.web.util.WebUtils;
/**
* Unit tests for {@link PortletUtils}.
*
* @author Rick Evans
* @author Chris Beams
*/
@@ -303,27 +299,14 @@ public final class PortletUtilsTests {
PortletUtils.exposeRequestAttributes(new MockPortletRequest(), null);
}
@SuppressWarnings("unchecked")
@Test(expected=ClassCastException.class)
public void testExposeRequestAttributesWithAttributesMapContainingBadKeyType() throws Exception {
MockPortletRequest request = new MockPortletRequest();
Map attributes = new HashMap<Object, Object>();
attributes.put(new Object(), "bad key type");
PortletUtils.exposeRequestAttributes(request, attributes);
}
@SuppressWarnings("unchecked")
@Test
public void testExposeRequestAttributesSunnyDay() throws Exception {
MockPortletRequest request = new MockPortletRequest();
Map attributes = new HashMap<Object, Object>();
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("ace", "Rick Hunter");
attributes.put("mentor", "Roy Fokker");
PortletUtils.exposeRequestAttributes(request, attributes);
assertEquals("Obviously all of the entries in the supplied attributes Map are not being copied over (exposed)",
attributes.size(), countElementsIn(request.getAttributeNames()));
assertEquals("Rick Hunter", request.getAttribute("ace"));
assertEquals("Roy Fokker", request.getAttribute("mentor"));
}
@@ -332,10 +315,8 @@ public final class PortletUtilsTests {
@Test
public void testExposeRequestAttributesWithEmptyAttributesMapIsAnIdempotentOperation() throws Exception {
MockPortletRequest request = new MockPortletRequest();
Map attributes = new HashMap<Object, Object>();
Map<String, String> attributes = new HashMap<String, String>();
PortletUtils.exposeRequestAttributes(request, attributes);
assertEquals("Obviously all of the entries in the supplied attributes Map are not being copied over (exposed)",
attributes.size(), countElementsIn(request.getAttributeNames()));
}
@Test(expected=IllegalArgumentException.class)
@@ -546,16 +527,6 @@ public final class PortletUtilsTests {
}
private static int countElementsIn(Enumeration<?> enumeration) {
int count = 0;
while (enumeration.hasMoreElements()) {
enumeration.nextElement();
++count;
}
return count;
}
private static final class NoPublicCtor {
private NoPublicCtor() {