Delete deprecated Servlet classes

This commit is contained in:
Harald Kuhr
2021-12-14 19:35:13 +01:00
parent 25c703f4b2
commit b0ad6b2a4b
83 changed files with 3 additions and 17379 deletions
@@ -1,469 +0,0 @@
/*
* Copyright (c) 2008, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.servlet;
import com.twelvemonkeys.lang.ObjectAbstractTest;
import org.junit.Test;
import javax.servlet.*;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
/**
* FilterAbstractTestCase
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-servlet/src/test/java/com/twelvemonkeys/servlet/FilterAbstractTestCase.java#1 $
*/
public abstract class FilterAbstractTest extends ObjectAbstractTest {
protected Object makeObject() {
return makeFilter();
}
protected abstract Filter makeFilter();
// TODO: Is it a good thing to have an API like this?
protected FilterConfig makeFilterConfig() {
return makeFilterConfig(new HashMap());
}
protected FilterConfig makeFilterConfig(Map pParams) {
return new MockFilterConfig(pParams);
}
protected ServletRequest makeRequest() {
return new MockServletRequest();
}
protected ServletResponse makeResponse() {
return new MockServletResponse();
}
protected FilterChain makeFilterChain() {
return new MockFilterChain();
}
@Test
public void testInitNull() {
Filter filter = makeFilter();
// The spec seems to be a little unclear on this issue, but anyway,
// the container should never invoke init(null)...
try {
filter.init(null);
fail("Should throw Exception on init(null)");
}
catch (IllegalArgumentException e) {
// Good
}
catch (NullPointerException e) {
// Bad (but not unreasonable)
}
catch (ServletException e) {
// Hmmm.. The jury is still out.
}
}
@Test
public void testInit() {
Filter filter = makeFilter();
try {
filter.init(makeFilterConfig());
}
catch (ServletException e) {
assertNotNull(e.getMessage());
}
finally {
filter.destroy();
}
}
@Test
public void testLifeCycle() throws ServletException {
Filter filter = makeFilter();
try {
filter.init(makeFilterConfig());
}
finally {
filter.destroy();
}
}
@Test
public void testFilterBasic() throws ServletException, IOException {
Filter filter = makeFilter();
try {
filter.init(makeFilterConfig());
filter.doFilter(makeRequest(), makeResponse(), makeFilterChain());
}
finally {
filter.destroy();
}
}
@Test
public void testDestroy() {
// TODO: Implement
}
static class MockFilterConfig implements FilterConfig {
private final Map<String, String> params;
MockFilterConfig(Map<String, String> pParams) {
if (pParams == null) {
throw new IllegalArgumentException("params == null");
}
params = pParams;
}
public String getFilterName() {
return "mock-filter";
}
public String getInitParameter(String pName) {
return params.get(pName);
}
public Enumeration getInitParameterNames() {
return Collections.enumeration(params.keySet());
}
public ServletContext getServletContext() {
return new MockServletContext();
}
private static class MockServletContext implements ServletContext {
private final Map<String, Object> attributes;
private final Map<String, String> params;
MockServletContext() {
attributes = new HashMap<>();
params = new HashMap<>();
}
public Object getAttribute(String s) {
return attributes.get(s);
}
public Enumeration getAttributeNames() {
return Collections.enumeration(attributes.keySet());
}
public ServletContext getContext(String s) {
return null; // TODO: Implement
}
public String getInitParameter(String s) {
return params.get(s);
}
public Enumeration getInitParameterNames() {
return Collections.enumeration(params.keySet());
}
public int getMajorVersion() {
return 0; // TODO: Implement
}
public String getMimeType(String s) {
return null; // TODO: Implement
}
public int getMinorVersion() {
return 0; // TODO: Implement
}
public RequestDispatcher getNamedDispatcher(String s) {
return null; // TODO: Implement
}
public String getRealPath(String s) {
return null; // TODO: Implement
}
public RequestDispatcher getRequestDispatcher(String s) {
return null; // TODO: Implement
}
public URL getResource(String s) throws MalformedURLException {
return null; // TODO: Implement
}
public InputStream getResourceAsStream(String s) {
return null; // TODO: Implement
}
public Set getResourcePaths(String s) {
return null; // TODO: Implement
}
public String getServerInfo() {
return null; // TODO: Implement
}
public Servlet getServlet(String s) throws ServletException {
return null; // TODO: Implement
}
public String getServletContextName() {
return "mock";
}
public Enumeration getServletNames() {
return null; // TODO: Implement
}
public Enumeration getServlets() {
return null; // TODO: Implement
}
public void log(Exception exception, String s) {
}
public void log(String s) {
}
public void log(String s, Throwable throwable) {
}
public void removeAttribute(String s) {
attributes.remove(s);
}
public void setAttribute(String s, Object obj) {
attributes.put(s, obj);
}
}
}
static class MockServletRequest implements ServletRequest {
final private Map<String, Object> attributes;
public MockServletRequest() {
attributes = new HashMap<String, Object>();
}
public Object getAttribute(String pKey) {
return attributes.get(pKey);
}
public Enumeration getAttributeNames() {
return Collections.enumeration(attributes.keySet());
}
public String getCharacterEncoding() {
return null; // TODO: Implement
}
public void setCharacterEncoding(String pMessage) throws UnsupportedEncodingException {
// TODO: Implement
}
public int getContentLength() {
return 0; // TODO: Implement
}
public String getContentType() {
return null; // TODO: Implement
}
public ServletInputStream getInputStream() throws IOException {
return null; // TODO: Implement
}
public String getParameter(String pMessage) {
return null; // TODO: Implement
}
public Enumeration getParameterNames() {
return null; // TODO: Implement
}
public String[] getParameterValues(String pMessage) {
return new String[0]; // TODO: Implement
}
public Map getParameterMap() {
return null; // TODO: Implement
}
public String getProtocol() {
return null; // TODO: Implement
}
public String getScheme() {
return null; // TODO: Implement
}
public String getServerName() {
return null; // TODO: Implement
}
public int getServerPort() {
return 0; // TODO: Implement
}
public BufferedReader getReader() throws IOException {
return null; // TODO: Implement
}
public String getRemoteAddr() {
return null; // TODO: Implement
}
public String getRemoteHost() {
return null; // TODO: Implement
}
public void setAttribute(String pKey, Object pValue) {
attributes.put(pKey, pValue);
}
public void removeAttribute(String pKey) {
attributes.remove(pKey);
}
public Locale getLocale() {
return null; // TODO: Implement
}
public Enumeration getLocales() {
return null; // TODO: Implement
}
public boolean isSecure() {
return false; // TODO: Implement
}
public RequestDispatcher getRequestDispatcher(String pMessage) {
return null; // TODO: Implement
}
public String getRealPath(String pMessage) {
return null; // TODO: Implement
}
public int getRemotePort() {
throw new UnsupportedOperationException("Method getRemotePort not implemented");// TODO: Implement
}
public String getLocalName() {
throw new UnsupportedOperationException("Method getLocalName not implemented");// TODO: Implement
}
public String getLocalAddr() {
throw new UnsupportedOperationException("Method getLocalAddr not implemented");// TODO: Implement
}
public int getLocalPort() {
throw new UnsupportedOperationException("Method getLocalPort not implemented");// TODO: Implement
}
}
static class MockServletResponse implements ServletResponse {
public void flushBuffer() throws IOException {
// TODO: Implement
}
public int getBufferSize() {
return 0; // TODO: Implement
}
public String getCharacterEncoding() {
return null; // TODO: Implement
}
public String getContentType() {
throw new UnsupportedOperationException("Method getContentType not implemented");// TODO: Implement
}
public Locale getLocale() {
return null; // TODO: Implement
}
public ServletOutputStream getOutputStream() throws IOException {
return null; // TODO: Implement
}
public PrintWriter getWriter() throws IOException {
return null; // TODO: Implement
}
public void setCharacterEncoding(String charset) {
throw new UnsupportedOperationException("Method setCharacterEncoding not implemented");// TODO: Implement
}
public boolean isCommitted() {
return false; // TODO: Implement
}
public void reset() {
// TODO: Implement
}
public void resetBuffer() {
// TODO: Implement
}
public void setBufferSize(int pLength) {
// TODO: Implement
}
public void setContentLength(int pLength) {
// TODO: Implement
}
public void setContentType(String pMessage) {
// TODO: Implement
}
public void setLocale(Locale pLocale) {
// TODO: Implement
}
}
static class MockFilterChain implements FilterChain {
public void doFilter(ServletRequest pRequest, ServletResponse pResponse) throws IOException, ServletException {
// TODO: Implement
}
}
}
@@ -1,181 +0,0 @@
/*
* Copyright (c) 2008, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.servlet;
import org.junit.Test;
import javax.servlet.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
/**
* GenericFilterTestCase
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-servlet/src/test/java/com/twelvemonkeys/servlet/GenericFilterTestCase.java#1 $
*/
public final class GenericFilterTest extends FilterAbstractTest {
protected Filter makeFilter() {
return new GenericFilterImpl();
}
@Test
public void testInitOncePerRequest() {
// Default FALSE
GenericFilter filter = new GenericFilterImpl();
try {
filter.init(makeFilterConfig());
}
catch (ServletException e) {
fail(e.getMessage());
}
assertFalse("OncePerRequest should default to false", filter.oncePerRequest);
filter.destroy();
// TRUE
filter = new GenericFilterImpl();
Map<String, String> params = new HashMap<>();
params.put("once-per-request", "true");
try {
filter.init(makeFilterConfig(params));
}
catch (ServletException e) {
fail(e.getMessage());
}
assertTrue("oncePerRequest should be true", filter.oncePerRequest);
filter.destroy();
// TRUE
filter = new GenericFilterImpl();
params = new HashMap<>();
params.put("oncePerRequest", "true");
try {
filter.init(makeFilterConfig(params));
}
catch (ServletException e) {
fail(e.getMessage());
}
assertTrue("oncePerRequest should be true", filter.oncePerRequest);
filter.destroy();
}
@Test
public void testFilterOnlyOnce() {
final GenericFilterImpl filter = new GenericFilterImpl();
filter.setOncePerRequest(true);
try {
filter.init(makeFilterConfig());
}
catch (ServletException e) {
fail(e.getMessage());
}
FilterChain chain = new MyFilterChain(new Filter[] {filter, filter, filter});
try {
chain.doFilter(makeRequest(), makeResponse());
}
catch (IOException | ServletException e) {
fail(e.getMessage());
}
assertEquals("Filter was invoked more than once!", 1, filter.invocationCount);
filter.destroy();
}
@Test
public void testFilterMultiple() {
final GenericFilterImpl filter = new GenericFilterImpl();
try {
filter.init(makeFilterConfig());
}
catch (ServletException e) {
fail(e.getMessage());
}
FilterChain chain = new MyFilterChain(new Filter[] {
filter, filter, filter, filter, filter
});
try {
chain.doFilter(makeRequest(), makeResponse());
}
catch (IOException | ServletException e) {
fail(e.getMessage());
}
assertEquals("Filter was invoked not invoked five times!", 5, filter.invocationCount);
filter.destroy();
}
private static class GenericFilterImpl extends GenericFilter {
int invocationCount;
protected void doFilterImpl(ServletRequest pRequest, ServletResponse pResponse, FilterChain pChain) throws IOException, ServletException {
invocationCount++;
pChain.doFilter(pRequest, pResponse);
}
}
private static class MyFilterChain implements FilterChain {
Filter[] mFilters;
int mCurrentFilter;
public MyFilterChain(Filter[] pFilters) {
if (pFilters == null) {
throw new IllegalArgumentException("filters == null");
}
mFilters = pFilters;
mCurrentFilter = 0;
}
public void doFilter(ServletRequest pRequest, ServletResponse pResponse) throws IOException, ServletException {
if (mCurrentFilter < mFilters.length) {
mFilters[mCurrentFilter++].doFilter(pRequest, pResponse, this);
}
}
}
}
@@ -1,162 +0,0 @@
/*
* Copyright (c) 2013, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.servlet;
import com.twelvemonkeys.util.MapAbstractTest;
import org.junit.Test;
import org.mockito.Mockito;
import javax.servlet.ServletContext;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.mock;
/**
* ServletConfigMapAdapterTestCase
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: ServletAttributesMapAdapterTestCase.java#1 $
*/
public class ServletAttributesMapAdapterContextTest extends MapAbstractTest {
private static final String ATTRIB_VALUE_ETAG = "\"1234567890abcdef\"";
private static final Date ATTRIB_VALUE_DATE = new Date();
private static final List<Integer> ATTRIB_VALUE_FOO = Arrays.asList(1, 2);
@Override
public boolean isTestSerialization() {
return false;
}
@Override
public boolean isAllowNullKey() {
return false; // Makes no sense...
}
@Override
public boolean isAllowNullValue() {
return false; // Should be allowed, but the tests don't handle the put(foo, null) == remove(foo) semantics
}
public Map makeEmptyMap() {
MockServletContextImpl context = mock(MockServletContextImpl.class, Mockito.CALLS_REAL_METHODS);
context.attributes = createAttributes(false);
return new ServletAttributesMapAdapter(context);
}
@Override
public Map makeFullMap() {
MockServletContextImpl context = mock(MockServletContextImpl.class, Mockito.CALLS_REAL_METHODS);
context.attributes = createAttributes(true);
return new ServletAttributesMapAdapter(context);
}
private Map<String, Object> createAttributes(boolean initialValues) {
Map<String, Object> map = new ConcurrentHashMap<>();
if (initialValues) {
String[] sampleKeys = (String[]) getSampleKeys();
for (int i = 0; i < sampleKeys.length; i++) {
map.put(sampleKeys[i], getSampleValues()[i]);
}
}
return map;
}
@Override
public Object[] getSampleKeys() {
return new String[] {"Date", "ETag", "X-Foo"};
}
@Override
public Object[] getSampleValues() {
return new Object[] {ATTRIB_VALUE_DATE, ATTRIB_VALUE_ETAG, ATTRIB_VALUE_FOO};
}
@Override
public Object[] getNewSampleValues() {
// Needs to be same length but different values
return new Object[] {new Date(-1L), "foo/bar", Arrays.asList(2, 3, 4)};
}
@Test
@SuppressWarnings("unchecked")
@Override
public void testMapPutNullValue() {
// Special null semantics
resetFull();
int size = map.size();
String key = getClass().getName() + ".someNewKey";
map.put(key, null);
assertEquals(size, map.size());
assertFalse(map.containsKey(key));
map.put(getSampleKeys()[0], null);
assertEquals(size - 1, map.size());
assertFalse(map.containsKey(getSampleKeys()[0]));
map.remove(getSampleKeys()[1]);
assertEquals(size - 2, map.size());
assertFalse(map.containsKey(getSampleKeys()[1]));
}
private static abstract class MockServletContextImpl implements ServletContext {
Map<String, Object> attributes;
public Object getAttribute(String name) {
return attributes.get(name);
}
public Enumeration getAttributeNames() {
return Collections.enumeration(attributes.keySet());
}
public void setAttribute(String name, Object o) {
if (o == null) {
attributes.remove(name);
}
else {
attributes.put(name, o);
}
}
public void removeAttribute(String name) {
attributes.remove(name);
}
}
}
@@ -1,162 +0,0 @@
/*
* Copyright (c) 2013, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.servlet;
import com.twelvemonkeys.util.MapAbstractTest;
import org.junit.Test;
import org.mockito.Mockito;
import javax.servlet.ServletRequest;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.mock;
/**
* ServletConfigMapAdapterTestCase
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: ServletAttributesMapAdapterTestCase.java#1 $
*/
public class ServletAttributesMapAdapterRequestTest extends MapAbstractTest {
private static final String ATTRIB_VALUE_ETAG = "\"1234567890abcdef\"";
private static final Date ATTRIB_VALUE_DATE = new Date();
private static final List<Integer> ATTRIB_VALUE_FOO = Arrays.asList(1, 2);
@Override
public boolean isTestSerialization() {
return false;
}
@Override
public boolean isAllowNullKey() {
return false; // Makes no sense...
}
@Override
public boolean isAllowNullValue() {
return false; // Should be allowed, but the tests don't handle the put(foo, null) == remove(foo) semantics
}
public Map makeEmptyMap() {
MockServletRequestImpl request = mock(MockServletRequestImpl.class, Mockito.CALLS_REAL_METHODS);
request.attributes = createAttributes(false);
return new ServletAttributesMapAdapter(request);
}
@Override
public Map makeFullMap() {
MockServletRequestImpl request = mock(MockServletRequestImpl.class, Mockito.CALLS_REAL_METHODS);
request.attributes = createAttributes(true);
return new ServletAttributesMapAdapter(request);
}
private Map<String, Object> createAttributes(boolean initialValues) {
Map<String, Object> map = new ConcurrentHashMap<>();
if (initialValues) {
String[] sampleKeys = (String[]) getSampleKeys();
for (int i = 0; i < sampleKeys.length; i++) {
map.put(sampleKeys[i], getSampleValues()[i]);
}
}
return map;
}
@Override
public Object[] getSampleKeys() {
return new String[] {"Date", "ETag", "X-Foo"};
}
@Override
public Object[] getSampleValues() {
return new Object[] {ATTRIB_VALUE_DATE, ATTRIB_VALUE_ETAG, ATTRIB_VALUE_FOO};
}
@Override
public Object[] getNewSampleValues() {
// Needs to be same length but different values
return new Object[] {new Date(-1L), "foo/bar", Arrays.asList(2, 3, 4)};
}
@Test
@SuppressWarnings("unchecked")
@Override
public void testMapPutNullValue() {
// Special null semantics
resetFull();
int size = map.size();
String key = getClass().getName() + ".someNewKey";
map.put(key, null);
assertEquals(size, map.size());
assertFalse(map.containsKey(key));
map.put(getSampleKeys()[0], null);
assertEquals(size - 1, map.size());
assertFalse(map.containsKey(getSampleKeys()[0]));
map.remove(getSampleKeys()[1]);
assertEquals(size - 2, map.size());
assertFalse(map.containsKey(getSampleKeys()[1]));
}
private static abstract class MockServletRequestImpl implements ServletRequest {
Map<String, Object> attributes;
public Object getAttribute(String name) {
return attributes.get(name);
}
public Enumeration getAttributeNames() {
return Collections.enumeration(attributes.keySet());
}
public void setAttribute(String name, Object o) {
if (o == null) {
attributes.remove(name);
}
else {
attributes.put(name, o);
}
}
public void removeAttribute(String name) {
attributes.remove(name);
}
}
}
@@ -1,131 +0,0 @@
/*
* Copyright (c) 2008, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.servlet;
import com.twelvemonkeys.io.NullOutputStream;
import org.junit.Test;
import java.io.PrintWriter;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
/**
* ServletConfigExceptionTestCase
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-servlet/src/test/java/com/twelvemonkeys/servlet/ServletConfigExceptionTestCase.java#2 $
*/
public class ServletConfigExceptionTest {
@Test
public void testThrowCatchPrintStacktrace() {
try {
throw new ServletConfigException("FooBar!");
}
catch (ServletConfigException e) {
e.printStackTrace(new PrintWriter(new NullOutputStream()));
}
}
@Test
public void testThrowCatchGetNoCause() {
try {
throw new ServletConfigException("FooBar!");
}
catch (ServletConfigException e) {
assertNull(e.getRootCause()); // Old API
assertNull(e.getCause());
e.printStackTrace(new PrintWriter(new NullOutputStream()));
}
}
@Test
public void testThrowCatchInitCauseNull() {
try {
ServletConfigException e = new ServletConfigException("FooBar!");
e.initCause(null);
throw e;
}
catch (ServletConfigException e) {
assertNull(e.getRootCause()); // Old API
assertNull(e.getCause());
e.printStackTrace(new PrintWriter(new NullOutputStream()));
}
}
@Test
public void testThrowCatchInitCause() {
//noinspection ThrowableInstanceNeverThrown
Exception cause = new Exception();
try {
ServletConfigException exception = new ServletConfigException("FooBar!");
exception.initCause(cause);
throw exception;
}
catch (ServletConfigException e) {
// NOTE: We don't know how the superclass is implemented, so we assume nothing here
//assertEquals(null, e.getRootCause()); // Old API
assertSame(cause, e.getCause());
e.printStackTrace(new PrintWriter(new NullOutputStream()));
}
}
@Test
public void testThrowCatchGetNullCause() {
try {
throw new ServletConfigException("FooBar!", null);
}
catch (ServletConfigException e) {
assertNull(e.getRootCause()); // Old API
assertNull(e.getCause());
e.printStackTrace(new PrintWriter(new NullOutputStream()));
}
}
@Test
public void testThrowCatchGetCause() {
IllegalStateException cause = new IllegalStateException();
try {
throw new ServletConfigException("FooBar caused by stupid API!", cause);
}
catch (ServletConfigException e) {
assertSame(cause, e.getRootCause()); // Old API
assertSame(cause, e.getCause());
e.printStackTrace(new PrintWriter(new NullOutputStream()));
}
}
}
@@ -1,229 +0,0 @@
/*
* Copyright (c) 2008, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.servlet;
import com.twelvemonkeys.util.MapAbstractTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import javax.servlet.*;
import java.io.InputStream;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
/**
* ServletConfigMapAdapterTestCase
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-servlet/src/test/java/com/twelvemonkeys/servlet/ServletConfigMapAdapterTestCase.java#3 $
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({AbstractServletConfigMapAdapterTest.ServletConfigMapTest.class, AbstractServletConfigMapAdapterTest.FilterConfigMapTest.class, AbstractServletConfigMapAdapterTest.ServletContextMapTest.class})
public final class ServletConfigMapAdapterTest {
}
abstract class AbstractServletConfigMapAdapterTest extends MapAbstractTest {
public boolean isPutAddSupported() {
return false;
}
public boolean isPutChangeSupported() {
return false;
}
public boolean isRemoveSupported() {
return false;
}
public boolean isSetValueSupported() {
return false;
}
private static class TestConfig implements ServletConfig, FilterConfig, ServletContext, Serializable, Cloneable {
Map map = new HashMap();
public String getServletName() {
return "dummy"; // Not needed for this test
}
public String getFilterName() {
return getServletName();
}
public String getServletContextName() {
return getServletName();
}
public ServletContext getServletContext() {
throw new UnsupportedOperationException("Method getSerlvetContext not implemented");
}
public String getInitParameter(String s) {
return (String) map.get(s);
}
public Enumeration getInitParameterNames() {
//noinspection unchecked
return Collections.enumeration(map.keySet());
}
public ServletContext getContext(String uripath) {
throw new UnsupportedOperationException("Method getContext not implemented");
}
public int getMajorVersion() {
throw new UnsupportedOperationException("Method getMajorVersion not implemented");
}
public int getMinorVersion() {
throw new UnsupportedOperationException("Method getMinorVersion not implemented");
}
public String getMimeType(String file) {
throw new UnsupportedOperationException("Method getMimeType not implemented");
}
public Set getResourcePaths(String path) {
throw new UnsupportedOperationException("Method getResourcePaths not implemented");
}
public URL getResource(String path) throws MalformedURLException {
throw new UnsupportedOperationException("Method getResource not implemented");
}
public InputStream getResourceAsStream(String path) {
throw new UnsupportedOperationException("Method getResourceAsStream not implemented");
}
public RequestDispatcher getRequestDispatcher(String path) {
throw new UnsupportedOperationException("Method getRequestDispatcher not implemented");
}
public RequestDispatcher getNamedDispatcher(String name) {
throw new UnsupportedOperationException("Method getNamedDispatcher not implemented");
}
public Servlet getServlet(String name) throws ServletException {
throw new UnsupportedOperationException("Method getServlet not implemented");
}
public Enumeration getServlets() {
throw new UnsupportedOperationException("Method getServlets not implemented");
}
public Enumeration getServletNames() {
throw new UnsupportedOperationException("Method getServletNames not implemented");
}
public void log(String msg) {
throw new UnsupportedOperationException("Method log not implemented");
}
public void log(Exception exception, String msg) {
throw new UnsupportedOperationException("Method log not implemented");
}
public void log(String message, Throwable throwable) {
throw new UnsupportedOperationException("Method log not implemented");
}
public String getRealPath(String path) {
throw new UnsupportedOperationException("Method getRealPath not implemented");
}
public String getServerInfo() {
throw new UnsupportedOperationException("Method getServerInfo not implemented");
}
public Object getAttribute(String name) {
throw new UnsupportedOperationException("Method getAttribute not implemented");
}
public Enumeration getAttributeNames() {
throw new UnsupportedOperationException("Method getAttributeNames not implemented");
}
public void setAttribute(String name, Object object) {
throw new UnsupportedOperationException("Method setAttribute not implemented");
}
public void removeAttribute(String name) {
throw new UnsupportedOperationException("Method removeAttribute not implemented");
}
}
public static final class ServletConfigMapTest extends AbstractServletConfigMapAdapterTest {
public Map makeEmptyMap() {
ServletConfig config = new TestConfig();
return new ServletConfigMapAdapter(config);
}
public Map makeFullMap() {
ServletConfig config = new TestConfig();
addSampleMappings(((TestConfig) config).map);
return new ServletConfigMapAdapter(config);
}
}
public static final class FilterConfigMapTest extends AbstractServletConfigMapAdapterTest {
public Map makeEmptyMap() {
FilterConfig config = new TestConfig();
return new ServletConfigMapAdapter(config);
}
public Map makeFullMap() {
FilterConfig config = new TestConfig();
addSampleMappings(((TestConfig) config).map);
return new ServletConfigMapAdapter(config);
}
}
public static final class ServletContextMapTest extends AbstractServletConfigMapAdapterTest {
public Map makeEmptyMap() {
ServletContext config = new TestConfig();
return new ServletConfigMapAdapter(config);
}
public Map makeFullMap() {
FilterConfig config = new TestConfig();
addSampleMappings(((TestConfig) config).map);
return new ServletConfigMapAdapter(config);
}
}
}
@@ -1,375 +0,0 @@
/*
* Copyright (c) 2008, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.servlet;
import org.junit.Test;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import java.util.Arrays;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
/**
* ServletConfiguratorTestCase
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haraldk$
* @version $Id: ServletConfiguratorTestCase.java,v 1.0 May 2, 2010 3:08:33 PM haraldk Exp$
*/
public class ServletConfiguratorTest {
// TODO: Test error conditions:
// - Missing name = ... or non-bean conforming method
// - Non-accessible? How..?
// - Missing required value
// TODO: Clean up tests to test only one thing at a time
// - Public method
// - Public method with override
// - Public method overridden without annotation
// - Protected method
// - Protected method with override
// - Protected method overridden without annotation
// - Package protected method
// - Package protected method with override
// - Package protected method overridden without annotation
// - Private method
// - Multiple private methods with same signature (should invoke all, as private methods can't be overridden)
@Test
public void testConfigureAnnotatedServlet() throws ServletConfigException {
AnnotatedServlet servlet = mock(AnnotatedServlet.class);
ServletConfig config = mock(ServletConfig.class);
when(config.getServletName()).thenReturn("FooServlet");
when(config.getInitParameterNames()).thenReturn(Collections.enumeration(Arrays.asList("x", "foo", "bar")));
when(config.getInitParameter("x")).thenReturn("99");
when(config.getInitParameter("foo")).thenReturn("Foo");
when(config.getInitParameter("bar")).thenReturn("-1, 2, 0, 42");
ServletConfigurator.configure(servlet, config);
// Verify
verify(servlet, times(1)).setX(99);
verify(servlet, times(1)).setFoo("Foo");
verify(servlet, times(1)).configTheBar(-1, 2, 0, 42);
}
@Test
public void testConfigureAnnotatedFilter() throws ServletConfigException {
AnnotatedServlet servlet = mock(AnnotatedServlet.class);
FilterConfig config = mock(FilterConfig.class);
when(config.getFilterName()).thenReturn("FooFilter");
when(config.getInitParameterNames()).thenReturn(Collections.enumeration(Arrays.asList("x", "foo", "bar")));
when(config.getInitParameter("x")).thenReturn("99");
when(config.getInitParameter("foo")).thenReturn("Foo");
when(config.getInitParameter("bar")).thenReturn("-1, 2, 0, 42");
ServletConfigurator.configure(servlet, config);
// Verify
verify(servlet, times(1)).setX(99);
verify(servlet, times(1)).setFoo("Foo");
verify(servlet, times(1)).configTheBar(-1, 2, 0, 42);
}
@Test
public void testConfigurePrivateMethod() throws ServletConfigException {
AnnotatedServlet servlet = mock(AnnotatedServlet.class);
ServletConfig config = mock(ServletConfig.class);
when(config.getServletName()).thenReturn("FooServlet");
when(config.getInitParameterNames()).thenReturn(Collections.enumeration(Collections.singletonList("private")));
when(config.getInitParameter("private")).thenReturn("99");
ServletConfigurator.configure(servlet, config);
// Verify
assertEquals(servlet.priv, "99");
}
@Test
public void testConfigurePrivateShadowedMethod() throws ServletConfigException {
abstract class SubclassedServlet extends AnnotatedServlet {
@InitParam(name = "package-private")
abstract void setPrivate(String priv);
}
SubclassedServlet servlet = mock(SubclassedServlet.class);
ServletConfig config = mock(ServletConfig.class);
when(config.getServletName()).thenReturn("FooServlet");
when(config.getInitParameterNames()).thenReturn(Collections.enumeration(Collections.singletonList("private")));
when(config.getInitParameter("private")).thenReturn("private");
when(config.getInitParameter("package-private")).thenReturn("package");
ServletConfigurator.configure(servlet, config);
// Verify
assertEquals(servlet.priv, "private");
verify(servlet, times(1)).setPrivate("package");
}
@Test
public void testConfigureSubclassedServlet() throws ServletConfigException {
abstract class SubclassedServlet extends AnnotatedServlet {
@InitParam(name = "flag")
abstract void configureMeToo(boolean flag);
}
SubclassedServlet servlet = mock(SubclassedServlet.class);
ServletConfig config = mock(ServletConfig.class);
when(config.getServletName()).thenReturn("FooServlet");
when(config.getInitParameterNames()).thenReturn(Collections.enumeration(Arrays.asList("x", "foo", "bar", "flag")));
when(config.getInitParameter("x")).thenReturn("99");
when(config.getInitParameter("foo")).thenReturn("Foo");
when(config.getInitParameter("bar")).thenReturn("-1, 2, 0, 42");
when(config.getInitParameter("flag")).thenReturn("true");
ServletConfigurator.configure(servlet, config);
// Verify
verify(servlet, times(1)).setX(99);
verify(servlet, times(1)).setFoo("Foo");
verify(servlet, times(1)).configTheBar(-1, 2, 0, 42);
verify(servlet, times(1)).configureMeToo(true);
}
@Test
public void testConfigureAnnotatedServletWithLispStyle() throws ServletConfigException {
abstract class SubclassedServlet extends AnnotatedServlet {
@InitParam(name = "the-explicit-x")
abstract public void setExplicitX(int x);
@InitParam
abstract public void setTheOtherX(int x);
}
SubclassedServlet servlet = mock(SubclassedServlet.class);
ServletConfig config = mock(ServletConfig.class);
when(config.getServletName()).thenReturn("FooServlet");
when(config.getInitParameterNames()).thenReturn(Collections.enumeration(Arrays.asList("the-explicit-x", "the-other-x")));
when(config.getInitParameter("the-explicit-x")).thenReturn("-1");
when(config.getInitParameter("the-other-x")).thenReturn("42");
ServletConfigurator.configure(servlet, config);
// Verify
verify(servlet, times(1)).setExplicitX(-1);
verify(servlet, times(1)).setTheOtherX(42);
}
@Test
public void testConfigureSubclassedServletWithOverride() throws ServletConfigException {
abstract class SubclassedServlet extends AnnotatedServlet {
@Override
@InitParam(name = "y")
public void setX(int x) {
}
}
SubclassedServlet servlet = mock(SubclassedServlet.class);
ServletConfig config = mock(ServletConfig.class);
when(config.getServletName()).thenReturn("FooServlet");
when(config.getInitParameterNames()).thenReturn(Collections.enumeration(Arrays.asList("x", "y")));
when(config.getInitParameter("x")).thenReturn("99");
when(config.getInitParameter("y")).thenReturn("-66");
ServletConfigurator.configure(servlet, config);
// Verify
verify(servlet, times(1)).setX(-66);
verify(servlet, times(1)).setX(anyInt()); // We don't want multiple invocations, only the overridden method
}
@Test
public void testConfigureSubclassedServletWithOverrideNoParam() throws ServletConfigException {
// NOTE: We must allow overriding the methods without annotation present, in order to allow CGLib/proxies of the class...
abstract class SubclassedServlet extends AnnotatedServlet {
@Override
@InitParam(name = "<THIS PARAMETER DOES NOT EXIST>")
public void setX(int x) {
}
@Override
public void setFoo(String foo) {
}
}
SubclassedServlet servlet = mock(SubclassedServlet.class);
ServletConfig config = mock(ServletConfig.class);
when(config.getServletName()).thenReturn("FooServlet");
when(config.getInitParameterNames()).thenReturn(Collections.enumeration(Arrays.asList("x", "foo")));
when(config.getInitParameter("x")).thenReturn("99");
when(config.getInitParameter("foo")).thenReturn("Foo");
ServletConfigurator.configure(servlet, config);
// Verify
verify(servlet, never()).setX(anyInt());
verify(servlet, times(1)).setFoo("Foo");
verify(servlet, times(1)).setFoo(anyString()); // We don't want multiple invocations
}
// Test interface
@Test
public void testConfigureServletWithInterface() throws ServletConfigException {
abstract class InterfacedServlet implements Servlet, Annotated {
}
InterfacedServlet servlet = mock(InterfacedServlet.class);
ServletConfig config = mock(ServletConfig.class);
when(config.getServletName()).thenReturn("FooServlet");
when(config.getInitParameterNames()).thenReturn(Collections.enumeration(Collections.singletonList("foo")));
when(config.getInitParameter("foo")).thenReturn("Foo");
ServletConfigurator.configure(servlet, config);
// Verify
verify(servlet, times(1)).annotated("Foo");
}
// TODO: Test override/shadow of package protected method outside package
@Test
public void testRequiredParameter() throws ServletConfigException {
abstract class SubclassedServlet extends AnnotatedServlet {
@InitParam(required = true)
abstract void setRequired(String value);
}
SubclassedServlet servlet = mock(SubclassedServlet.class);
ServletConfig config = mock(ServletConfig.class);
when(config.getServletName()).thenReturn("FooServlet");
when(config.getInitParameterNames()).thenReturn(Collections.enumeration(Collections.singletonList("required")));
when(config.getInitParameter("required")).thenReturn("the required value");
ServletConfigurator.configure(servlet, config);
// Verify
verify(servlet, times(1)).setRequired("the required value");
verify(servlet, times(1)).setRequired(anyString()); // We don't want multiple invocations
}
@Test
public void testMissingParameter() throws ServletConfigException {
abstract class SubclassedServlet extends AnnotatedServlet {
@InitParam()
abstract void setNonRequired(String value);
}
SubclassedServlet servlet = mock(SubclassedServlet.class);
ServletConfig config = mock(ServletConfig.class);
when(config.getServletName()).thenReturn("FooServlet");
when(config.getInitParameterNames()).thenReturn(Collections.enumeration(Collections.emptyList()));
ServletConfigurator.configure(servlet, config);
// Verify
verify(servlet, never()).setNonRequired(anyString()); // Simply not configured
}
@Test(expected = ServletConfigException.class)
public void testMissingRequiredParameter() throws ServletConfigException {
abstract class SubclassedServlet extends AnnotatedServlet {
@Override
@InitParam(required = true)
protected abstract void setFoo(String value);
}
SubclassedServlet servlet = mock(SubclassedServlet.class);
ServletConfig config = mock(ServletConfig.class);
when(config.getServletName()).thenReturn("FooServlet");
when(config.getInitParameterNames()).thenReturn(Collections.enumeration(Collections.emptyList()));
ServletConfigurator.configure(servlet, config); // Should throw exception
}
@Test
public void testMissingParameterDefaultValue() throws ServletConfigException {
abstract class SubclassedServlet extends AnnotatedServlet {
@InitParam(defaultValue = "1, 2, 3")
abstract void setNonRequired(int[] value);
}
SubclassedServlet servlet = mock(SubclassedServlet.class);
ServletConfig config = mock(ServletConfig.class);
when(config.getServletName()).thenReturn("FooServlet");
when(config.getInitParameterNames()).thenReturn(Collections.enumeration(Collections.emptyList()));
ServletConfigurator.configure(servlet, config);
// Verify
verify(servlet, times(1)).setNonRequired(new int[] {1, 2, 3});
verify(servlet, times(1)).setNonRequired((int[]) any());
}
public interface Annotated {
@InitParam(name = "foo")
void annotated(String an);
}
public abstract class AnnotatedServlet implements Servlet, Filter {
String priv;
// Implicit name "x"
@InitParam
public abstract void setX(int x);
// Implicit name "foo"
@InitParam
protected abstract void setFoo(String foo);
@InitParam(name = "bar")
abstract void configTheBar(int... bar);
@InitParam(name = "private")
private void setPrivate(String priv) {
this.priv = priv;
}
}
}
@@ -1,125 +0,0 @@
/*
* Copyright (c) 2008, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.servlet;
import com.twelvemonkeys.util.MapAbstractTest;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import static org.mockito.Mockito.when;
/**
* ServletConfigMapAdapterTest
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: ServletHeadersMapAdapterTest.java#1 $
*/
public class ServletHeadersMapAdapterTest extends MapAbstractTest {
private static final List<String> HEADER_VALUE_ETAG = Collections.singletonList("\"1234567890abcdef\"");
private static final List<String> HEADER_VALUE_DATE = Collections.singletonList(new Date().toString());
private static final List<String> HEADER_VALUE_FOO = Arrays.asList("one", "two");
public boolean isPutAddSupported() {
return false;
}
public boolean isPutChangeSupported() {
return false;
}
public boolean isRemoveSupported() {
return false;
}
public boolean isSetValueSupported() {
return false;
}
@Override
public boolean isTestSerialization() {
return false;
}
public Map makeEmptyMap() {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
when(request.getHeaderNames()).thenAnswer(returnEnumeration(Collections.emptyList()));
return new ServletHeadersMapAdapter(request);
}
@Override
public Map makeFullMap() {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
when(request.getHeaderNames()).thenAnswer(returnEnumeration(Arrays.asList(getSampleKeys())));
when(request.getHeaders("Date")).thenAnswer(returnEnumeration(HEADER_VALUE_DATE));
when(request.getHeaders("ETag")).thenAnswer(returnEnumeration(HEADER_VALUE_ETAG));
when(request.getHeaders("X-Foo")).thenAnswer(returnEnumeration(HEADER_VALUE_FOO));
return new ServletHeadersMapAdapter(request);
}
@Override
public Object[] getSampleKeys() {
return new String[] {"Date", "ETag", "X-Foo"};
}
@Override
public Object[] getSampleValues() {
return new Object[] {HEADER_VALUE_DATE, HEADER_VALUE_ETAG, HEADER_VALUE_FOO};
}
@Override
public Object[] getNewSampleValues() {
// Needs to be same length but different values
return new Object[3];
}
protected static <T> ReturnNewEnumeration<T> returnEnumeration(final Collection<T> collection) {
return new ReturnNewEnumeration<>(collection);
}
private static class ReturnNewEnumeration<T> implements Answer<Enumeration<T>> {
private final Collection<T> collection;
private ReturnNewEnumeration(final Collection<T> collection) {
this.collection = collection;
}
public Enumeration<T> answer(InvocationOnMock invocation) throws Throwable {
return Collections.enumeration(collection);
}
}
}
@@ -1,126 +0,0 @@
/*
* Copyright (c) 2008, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.servlet;
import com.twelvemonkeys.util.MapAbstractTest;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import static org.mockito.Mockito.when;
/**
* ServletConfigMapAdapterTest
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-servlet/src/test/java/com/twelvemonkeys/servlet/ServletParametersMapAdapterTest.java#1 $
*/
public class ServletParametersMapAdapterTest extends MapAbstractTest {
private static final List<String> PARAM_VALUE_ETAG = Collections.singletonList("\"1234567890abcdef\"");
private static final List<String> PARAM_VALUE_DATE = Collections.singletonList(new Date().toString());
private static final List<String> PARAM_VALUE_FOO = Arrays.asList("one", "two");
public boolean isPutAddSupported() {
return false;
}
public boolean isPutChangeSupported() {
return false;
}
public boolean isRemoveSupported() {
return false;
}
public boolean isSetValueSupported() {
return false;
}
@Override
public boolean isTestSerialization() {
return false;
}
public Map makeEmptyMap() {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
when(request.getParameterNames()).thenAnswer(returnEnumeration(Collections.emptyList()));
return new ServletParametersMapAdapter(request);
}
@Override
public Map makeFullMap() {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
when(request.getParameterNames()).thenAnswer(returnEnumeration(Arrays.asList("tag", "date", "foo")));
when(request.getParameterValues("date")).thenReturn(PARAM_VALUE_DATE.toArray(new String[PARAM_VALUE_DATE.size()]));
when(request.getParameterValues("tag")).thenReturn(PARAM_VALUE_ETAG.toArray(new String[PARAM_VALUE_ETAG.size()]));
when(request.getParameterValues("foo")).thenReturn(PARAM_VALUE_FOO.toArray(new String[PARAM_VALUE_FOO.size()]));
return new ServletParametersMapAdapter(request);
}
@Override
public Object[] getSampleKeys() {
return new String[] {"date", "tag", "foo"};
}
@Override
public Object[] getSampleValues() {
return new Object[] {PARAM_VALUE_DATE, PARAM_VALUE_ETAG, PARAM_VALUE_FOO};
}
@Override
public Object[] getNewSampleValues() {
// Needs to be same length but different values
return new Object[3];
}
protected static <T> ReturnNewEnumeration<T> returnEnumeration(final Collection<T> collection) {
return new ReturnNewEnumeration<>(collection);
}
private static class ReturnNewEnumeration<T> implements Answer<Enumeration<T>> {
private final Collection<T> collection;
private ReturnNewEnumeration(final Collection<T> collection) {
this.collection = collection;
}
public Enumeration<T> answer(InvocationOnMock invocation) throws Throwable {
return Collections.enumeration(collection);
}
}
}
@@ -1,53 +0,0 @@
/*
* Copyright (c) 2008, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.servlet;
import com.twelvemonkeys.lang.ObjectAbstractTest;
import javax.servlet.ServletResponse;
/**
* ServletResponseAbsrtactTestCase
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-servlet/src/test/java/com/twelvemonkeys/servlet/ServletResponseAbsrtactTestCase.java#1 $
*/
public abstract class ServletResponseAbsrtactTest extends ObjectAbstractTest {
protected Object makeObject() {
return makeServletResponse();
}
protected abstract ServletResponse makeServletResponse();
// TODO: Implement
}
@@ -1,115 +0,0 @@
package com.twelvemonkeys.servlet;
import com.twelvemonkeys.io.OutputStreamAbstractTest;
import org.junit.Test;
import javax.servlet.Filter;
import javax.servlet.ServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import static org.junit.Assert.assertEquals;
/**
* TrimWhiteSpaceFilterTestCase
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-servlet/src/test/java/com/twelvemonkeys/servlet/TrimWhiteSpaceFilterTestCase.java#1 $
*/
public class TrimWhiteSpaceFilterTest extends FilterAbstractTest {
protected Filter makeFilter() {
return new TrimWhiteSpaceFilter();
}
public static final class TrimWSFilterOutputStreamTest extends OutputStreamAbstractTest {
protected OutputStream makeObject() {
// NOTE: ByteArrayOutputStream does not implement flush or close...
return makeOutputStream(new ByteArrayOutputStream(16));
}
protected OutputStream makeOutputStream(OutputStream pWrapped) {
return new TrimWhiteSpaceFilter.TrimWSFilterOutputStream(pWrapped);
}
@Test
public void testTrimWSOnlyWS() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(64);
OutputStream trim = makeOutputStream(out);
String input = " \n\n\t \t" + (char) 0x0a + ' ' + (char) 0x0d + "\r ";
trim.write(input.getBytes());
trim.flush();
trim.close();
assertEquals("Should be trimmed", "\"\"", '"' + new String(out.toByteArray()) + '"');
}
@Test
public void testTrimWSLeading() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(64);
OutputStream trim = makeOutputStream(out);
byte[] input = " \n<?xml version=\"1.0\"?>\n\t <not-really-well-formed/> \t".getBytes();
String trimmed = "<?xml version=\"1.0\"?>\n<not-really-well-formed/> "; // TODO: This is pr spec (the trailing space). But probably quite stupid...
trim.write(input);
trim.flush();
trim.close();
assertEquals("Should be trimmed", '"' + trimmed + '"', '"' + new String(out.toByteArray()) + '"');
}
@Test
public void testTrimWSOffsetLength() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(64);
OutputStream trim = makeOutputStream(out);
// Kindly generated by http://lipsum.org/ :-)
byte[] input = (" \n\tLorem ipsum dolor sit amet, consectetuer adipiscing elit.\n\r\n\r" +
"Etiam arcu neque, \n\rmalesuada blandit,\t\n\r\n\r\n\n\n\r\n\r\r\n\n\t rutrum quis, molestie at, diam.\n" +
" Nulla elementum elementum eros.\n \t\t\n\r" +
"Ut rhoncus, turpis in pellentesque volutpat, sapien sem accumsan augue, a scelerisque nibh erat vel magna.\n" +
" Phasellus diam orci, dignissim et, gravida vitae, venenatis eu, elit.\n" +
"\t\t\tSuspendisse dictum enim at nisl. Integer magna erat, viverra sit amet, consectetuer nec, accumsan ut, mi.\n" +
"\n\r\r\r\n\rNunc ultricies \n\n\n consectetuer mauris. " +
"Nulla lectus mauris, viverra ac, pulvinar a, commodo quis, nulla.\n " +
"Ut eget nulla. In est dolor, convallis \t non, tincidunt \tvestibulum, porttitor et, eros.\n " +
"\t\t \t \n\rDonec vehicula ultrices nisl.").getBytes();
String trimmed = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\n" +
"Etiam arcu neque, malesuada blandit,\trutrum quis, molestie at, diam.\n" +
"Nulla elementum elementum eros.\n" +
"Ut rhoncus, turpis in pellentesque volutpat, sapien sem accumsan augue, a scelerisque nibh erat vel magna.\n" +
"Phasellus diam orci, dignissim et, gravida vitae, venenatis eu, elit.\n" +
"Suspendisse dictum enim at nisl. Integer magna erat, viverra sit amet, consectetuer nec, accumsan ut, mi.\n" +
"Nunc ultricies consectetuer mauris. Nulla lectus mauris, viverra ac, pulvinar a, commodo quis, nulla.\n" +
"Ut eget nulla. In est dolor, convallis non, tincidunt vestibulum, porttitor et, eros.\n" +
"Donec vehicula ultrices nisl.";
int chunkLenght = 5;
int bytesLeft = input.length;
while (bytesLeft > chunkLenght) {
trim.write(input, input.length - bytesLeft, chunkLenght);
bytesLeft -= chunkLenght;
}
trim.write(input, input.length - bytesLeft, bytesLeft);
trim.flush();
trim.close();
assertEquals("Should be trimmed", '"' + trimmed + '"', '"' + new String(out.toByteArray()) + '"');
}
// TODO: Test that we DON'T remove too much...
}
public static final class TrimWSServletResponseWrapperTest extends ServletResponseAbsrtactTest {
protected ServletResponse makeServletResponse() {
return new TrimWhiteSpaceFilter.TrimWSServletResponseWrapper(new MockServletResponse());
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,508 +0,0 @@
/*
* Copyright (c) 2011, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.servlet.image;
import com.twelvemonkeys.io.FileUtil;
import com.twelvemonkeys.servlet.OutputStreamAdapter;
import com.twelvemonkeys.util.StringTokenIterator;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* ImageFilterTest
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haraldk$
* @version $Id: ImageFilterTest.java,v 1.0 07.04.11 14.14 haraldk Exp$
*/
public class ImageFilterTest {
@Test
public void passThroughIfNotTrigger() throws ServletException, IOException {
// Filter init & setup
ServletContext context = mock(ServletContext.class);
FilterConfig filterConfig = mock(FilterConfig.class);
when(filterConfig.getFilterName()).thenReturn("dummy");
when(filterConfig.getServletContext()).thenReturn(context);
when(filterConfig.getInitParameterNames()).thenReturn(new StringTokenIterator("foo, bar"));
DummyFilter filter = new DummyFilter() {
@Override
protected boolean trigger(ServletRequest pRequest) {
return false;
}
};
filter.init(filterConfig);
// Request/response setup
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
// Execute
filter.doFilter(request, response, chain);
// Verifications
verify(chain).doFilter(request, response);
verify(response, never()).getOutputStream();
verify(response, never()).getWriter();
}
@Test
public void normalFilter() throws ServletException, IOException {
// Filter init & setup
ServletContext context = mock(ServletContext.class);
FilterConfig filterConfig = mock(FilterConfig.class);
when(filterConfig.getFilterName()).thenReturn("dummy");
when(filterConfig.getServletContext()).thenReturn(context);
when(filterConfig.getInitParameterNames()).thenReturn(new StringTokenIterator("foo, bar"));
DummyFilter filter = new DummyFilter();
filter.init(filterConfig);
// Request/response setup
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ServletOutputStream out = spy(new OutputStreamAdapter(stream));
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(response.getOutputStream()).thenReturn(out);
FilterChain chain = mock(FilterChain.class);
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) throws Throwable {
HttpServletResponse response = (HttpServletResponse) invocation.getArguments()[1];
response.setContentType("image/png");
response.setContentLength(104417);
InputStream stream = getClass().getResourceAsStream("/com/twelvemonkeys/servlet/image/12monkeys-splash.png");
assertNotNull("Missing test resource", stream);
FileUtil.copy(stream, response.getOutputStream());
return null;
}
}).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
// Execute
filter.doFilter(request, response, chain);
// Verifications
int length = stream.size();
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
verify(response).setContentType("image/png");
verify(response, atMost(1)).setContentLength(length); // setContentLength not implemented, avoid future bugs
verify(out, atLeastOnce()).flush();
// Extra verification here, until we come up with something better
assertTrue(
String.format("Unlikely length for PNG (please run manual check): %s bytes, expected about 85000 bytes", length),
length >= 60000 && length <= 120000
);
}
@Test
public void filterNoContent() throws ServletException, IOException {
// Filter init & setup
ServletContext context = mock(ServletContext.class);
FilterConfig filterConfig = mock(FilterConfig.class);
when(filterConfig.getFilterName()).thenReturn("dummy");
when(filterConfig.getServletContext()).thenReturn(context);
when(filterConfig.getInitParameterNames()).thenReturn(new StringTokenIterator("foo, bar"));
DummyFilter filter = new DummyFilter();
filter.init(filterConfig);
// Request/response setup
ServletOutputStream out = mock(ServletOutputStream.class);
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(response.getOutputStream()).thenReturn(out);
FilterChain chain = mock(FilterChain.class);
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) throws Throwable {
HttpServletResponse response = (HttpServletResponse) invocation.getArguments()[1];
response.setContentType("image/x-imaginary");
return null;
}
}).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
// Execute
filter.doFilter(request, response, chain);
// Verifications
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
verify(response).setContentType("image/x-imaginary");
verify(out, atLeastOnce()).flush();
}
@Test
public void triggerWhenTriggerParamsNull() throws ServletException {
// Filter init & setup
ServletContext context = mock(ServletContext.class);
FilterConfig filterConfig = mock(FilterConfig.class);
when(filterConfig.getFilterName()).thenReturn("dummy");
when(filterConfig.getServletContext()).thenReturn(context);
when(filterConfig.getInitParameterNames()).thenReturn(new StringTokenIterator("foo, bar"));
DummyFilter filter = new DummyFilter();
filter.init(filterConfig);
// Execute/Verifications
assertTrue(filter.trigger(mock(HttpServletRequest.class)));
}
@Test
public void triggerWithTriggerParams() throws ServletException {
// Filter init & setup
ServletContext context = mock(ServletContext.class);
FilterConfig filterConfig = mock(FilterConfig.class);
when(filterConfig.getFilterName()).thenReturn("dummy");
when(filterConfig.getServletContext()).thenReturn(context);
when(filterConfig.getInitParameterNames()).thenReturn(new StringTokenIterator("triggerParams"));
when(filterConfig.getInitParameter("triggerParams")).thenReturn("foo");
DummyFilter filter = new DummyFilter();
filter.init(filterConfig);
// Request/response setup
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getParameter("foo")).thenReturn("doit");
// Execute/Verifications
assertTrue(filter.trigger(request));
}
@Test
public void dontTriggerWithoutTriggerParams() throws ServletException {
// Filter init & setup
ServletContext context = mock(ServletContext.class);
FilterConfig filterConfig = mock(FilterConfig.class);
when(filterConfig.getFilterName()).thenReturn("dummy");
when(filterConfig.getServletContext()).thenReturn(context);
when(filterConfig.getInitParameterNames()).thenReturn(new StringTokenIterator("triggerParams"));
when(filterConfig.getInitParameter("triggerParams")).thenReturn("foo");
DummyFilter filter = new DummyFilter();
filter.init(filterConfig);
// Request/response setup
HttpServletRequest request = mock(HttpServletRequest.class);
// Execute/Verifications
assertFalse(filter.trigger(request));
}
@Test
public void testChaining() throws ServletException, IOException {
// Filter init & setup
ServletContext context = mock(ServletContext.class);
FilterConfig fooConfig = mock(FilterConfig.class);
when(fooConfig.getFilterName()).thenReturn("foo");
when(fooConfig.getServletContext()).thenReturn(context);
when(fooConfig.getInitParameterNames()).thenReturn(new StringTokenIterator(""));
final AtomicReference<BufferedImage> imageRef = new AtomicReference<BufferedImage>();
final AtomicReference<ImageServletResponse> responseRef = new AtomicReference<ImageServletResponse>();
DummyFilter fooFilter = new DummyFilter() {
@Override
protected RenderedImage doFilter(BufferedImage image, ServletRequest request, ImageServletResponse response) throws IOException {
// NOTE: Post-filtering, this method is run after barFilter.doFilter
assertEquals(imageRef.get(), image);
assertEquals(responseRef.get(), response);
return image;
}
};
fooFilter.init(fooConfig);
FilterConfig barConfig = mock(FilterConfig.class);
when(barConfig.getFilterName()).thenReturn("bar");
when(barConfig.getServletContext()).thenReturn(context);
when(barConfig.getInitParameterNames()).thenReturn(new StringTokenIterator(""));
final DummyFilter barFilter = new DummyFilter() {
@Override
protected RenderedImage doFilter(BufferedImage image, ServletRequest request, ImageServletResponse response) throws IOException {
// NOTE: Post-filtering, this method is run before fooFilter.doFilter
Graphics2D graphics = image.createGraphics();
try {
graphics.drawRect(10, 10, 100, 100);
}
finally {
graphics.dispose();
}
// Store references for later, make sure this is first and only set.
assertTrue(imageRef.compareAndSet(null, image));
assertTrue(responseRef.compareAndSet(null, response));
return image;
}
};
barFilter.init(barConfig);
// Request/response setup
ServletOutputStream out = mock(ServletOutputStream.class);
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(response.getOutputStream()).thenReturn(out);
FilterChain chain = mock(FilterChain.class);
final AtomicBoolean first = new AtomicBoolean(false);
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) throws Throwable {
HttpServletRequest request = (HttpServletRequest) invocation.getArguments()[0];
HttpServletResponse response = (HttpServletResponse) invocation.getArguments()[1];
// Fake chaining here..
if (first.compareAndSet(false, true)) {
barFilter.doFilter(request, response, (FilterChain) invocation.getMock());
return null;
}
// Otherwise, fake servlet/file response
response.setContentType("image/gif");
InputStream stream = getClass().getResourceAsStream("/com/twelvemonkeys/servlet/image/tux.gif");
assertNotNull("Missing test resource", stream);
FileUtil.copy(stream, response.getOutputStream());
return null;
}
}).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
// Execute
fooFilter.doFilter(request, response, chain);
// Verifications
verify(chain, times(2)).doFilter(any(ServletRequest.class), any(ImageServletResponse.class));
verify(response).setContentType("image/gif");
verify(out, atLeastOnce()).flush();
// NOTE:
// We verify that the image is the same in both ImageFilter implementations, to make sure the image is only
// decoded once, then encoded once.
// But this test is not necessarily 100% reliable...
}
@Test(expected = ServletException.class)
public void passThroughIfNotTriggerException() throws ServletException, IOException {
// Filter init & setup
ServletContext context = mock(ServletContext.class);
FilterConfig filterConfig = mock(FilterConfig.class);
when(filterConfig.getFilterName()).thenReturn("dummy");
when(filterConfig.getServletContext()).thenReturn(context);
when(filterConfig.getInitParameterNames()).thenReturn(new StringTokenIterator("foo, bar"));
DummyFilter filter = new DummyFilter() {
@Override
protected boolean trigger(ServletRequest pRequest) {
return false;
}
};
filter.init(filterConfig);
// Request/response setup
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
doThrow(new ServletException("Something went terribly wrong. Take shelter.")).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
// Execute
try {
filter.doFilter(request, response, chain);
}
finally {
// Verifications
verify(chain).doFilter(request, response);
verify(response, never()).getOutputStream();
verify(response, never()).getWriter();
}
}
@Test(expected = ServletException.class)
public void normalFilterException() throws ServletException, IOException {
// Filter init & setup
ServletContext context = mock(ServletContext.class);
FilterConfig filterConfig = mock(FilterConfig.class);
when(filterConfig.getFilterName()).thenReturn("dummy");
when(filterConfig.getServletContext()).thenReturn(context);
when(filterConfig.getInitParameterNames()).thenReturn(new StringTokenIterator("foo, bar"));
DummyFilter filter = new DummyFilter();
filter.init(filterConfig);
// Request/response setup
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ServletOutputStream out = spy(new OutputStreamAdapter(stream));
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(response.getOutputStream()).thenReturn(out);
FilterChain chain = mock(FilterChain.class);
doThrow(new ServletException("Something went terribly wrong. Take shelter.")).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
// Execute
try {
filter.doFilter(request, response, chain);
}
finally {
// Verifications
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
}
}
@Test
public void passThroughIfNotTriggerSendError() throws ServletException, IOException {
// Filter init & setup
ServletContext context = mock(ServletContext.class);
FilterConfig filterConfig = mock(FilterConfig.class);
when(filterConfig.getFilterName()).thenReturn("dummy");
when(filterConfig.getServletContext()).thenReturn(context);
when(filterConfig.getInitParameterNames()).thenReturn(new StringTokenIterator("foo, bar"));
DummyFilter filter = new DummyFilter() {
@Override
protected boolean trigger(ServletRequest pRequest) {
return false;
}
};
filter.init(filterConfig);
// Request/response setup
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) throws Throwable {
HttpServletResponse response = (HttpServletResponse) invocation.getArguments()[1];
response.sendError(HttpServletResponse.SC_FORBIDDEN, "I'm afraid I can't do that.");
return null;
}
}).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
// Execute
filter.doFilter(request, response, chain);
// Verifications
verify(chain).doFilter(request, response);
verify(response, never()).getOutputStream();
verify(response, never()).getWriter();
}
@Test
public void normalFilterSendError() throws ServletException, IOException {
// Filter init & setup
ServletContext context = mock(ServletContext.class);
FilterConfig filterConfig = mock(FilterConfig.class);
when(filterConfig.getFilterName()).thenReturn("dummy");
when(filterConfig.getServletContext()).thenReturn(context);
when(filterConfig.getInitParameterNames()).thenReturn(new StringTokenIterator("foo, bar"));
DummyFilter filter = new DummyFilter();
filter.init(filterConfig);
// Request/response setup
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ServletOutputStream out = spy(new OutputStreamAdapter(stream));
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(response.getOutputStream()).thenReturn(out);
FilterChain chain = mock(FilterChain.class);
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) throws Throwable {
HttpServletResponse response = (HttpServletResponse) invocation.getArguments()[1];
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "I've just picked up a fault in the AE35 unit.");
return null;
}
}).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
// Execute
filter.doFilter(request, response, chain);
// Verifications
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
verify(response, atMost(1)).setContentLength(stream.size()); // setContentLength not implemented, avoid future bugs
verify(out, atLeastOnce()).flush();
}
private static class DummyFilter extends ImageFilter {
@Override
protected RenderedImage doFilter(BufferedImage image, ServletRequest request, ImageServletResponse response) throws IOException {
return image;
}
}
}
@@ -1,365 +0,0 @@
/*
* Copyright (c) 2008, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.servlet.image.aoi;
import org.junit.Test;
import java.awt.*;
import static org.junit.Assert.assertEquals;
/**
* @author <a href="mailto:erlend@escenic.com">Erlend Hamnaberg</a>
* @version $Revision: $
*/
public class AreaOfInterestTest {
private static final Dimension SQUARE_200_200 = new Dimension(200, 200);
private static final Dimension PORTRAIT_100_200 = new Dimension(100, 200);
private static final Dimension LANDSCAPE_200_100 = new Dimension(200, 100);
private static final Dimension SQUARE_100_100 = new Dimension(100, 100);
// -----------------------------------------------------------------------------------------------------------------
// Absolute AOI
// -----------------------------------------------------------------------------------------------------------------
@Test
public void testGetAOIAbsolute() {
assertEquals(new Rectangle(10, 10, 100, 100), new DefaultAreaOfInterest(SQUARE_200_200).getAOI(10, 10, 100, 100));
}
@Test
public void testGetAOIAbsoluteOverflowX() {
assertEquals(new Rectangle(10, 10, 90, 100), new DefaultAreaOfInterest(PORTRAIT_100_200).getAOI(10, 10, 100, 100));
}
@Test
public void testGetAOIAbsoluteOverflowW() {
assertEquals(new Rectangle(0, 10, 100, 100), new DefaultAreaOfInterest(PORTRAIT_100_200).getAOI(0, 10, 110, 100));
}
@Test
public void testGetAOIAbsoluteOverflowY() {
assertEquals(new Rectangle(10, 10, 100, 90), new DefaultAreaOfInterest(LANDSCAPE_200_100).getAOI(10, 10, 100, 100));
}
@Test
public void testGetAOIAbsoluteOverflowH() {
assertEquals(new Rectangle(10, 0, 100, 100), new DefaultAreaOfInterest(LANDSCAPE_200_100).getAOI(10, 0, 100, 110));
}
// -----------------------------------------------------------------------------------------------------------------
// Uniform AOI centered
// -----------------------------------------------------------------------------------------------------------------
@Test
public void testGetAOIUniformCenteredS2SUp() {
assertEquals(new Rectangle(0, 0, 100, 100), new UniformAreaOfInterest(SQUARE_100_100).getAOI(-1, -1, 333, 333));
}
@Test
public void testGetAOIUniformCenteredS2SDown() {
assertEquals(new Rectangle(0, 0, 100, 100), new UniformAreaOfInterest(SQUARE_100_100).getAOI(-1, -1, 33, 33));
}
@Test
public void testGetAOIUniformCenteredS2SNormalized() {
assertEquals(new Rectangle(0, 0, 100, 100), new UniformAreaOfInterest(SQUARE_100_100).getAOI(-1, -1, 100, 100));
}
@Test
public void testGetAOIUniformCenteredS2W() {
assertEquals(new Rectangle(0, 25, 100, 50), new UniformAreaOfInterest(SQUARE_100_100).getAOI(-1, -1, 200, 100));
}
@Test
public void testGetAOIUniformCenteredS2WNormalized() {
assertEquals(new Rectangle(0, 25, 100, 50), new UniformAreaOfInterest(SQUARE_100_100).getAOI(-1, -1, 100, 50));
}
@Test
public void testGetAOIUniformCenteredS2N() {
assertEquals(new Rectangle(25, 0, 50, 100), new UniformAreaOfInterest(SQUARE_100_100).getAOI(-1, -1, 100, 200));
}
@Test
public void testGetAOIUniformCenteredS2NNormalized() {
assertEquals(new Rectangle(25, 0, 50, 100), new UniformAreaOfInterest(SQUARE_100_100).getAOI(-1, -1, 50, 100));
}
@Test
public void testGetAOIUniformCenteredW2S() {
assertEquals(new Rectangle(50, 0, 100, 100), new UniformAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 333, 333));
}
@Test
public void testGetAOIUniformCenteredW2SNormalized() {
assertEquals(new Rectangle(50, 0, 100, 100), new UniformAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 100, 100));
}
@Test
public void testGetAOIUniformCenteredW2W() {
assertEquals(new Rectangle(0, 0, 200, 100), new UniformAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 100, 50));
}
@Test
public void testGetAOIUniformCenteredW2WW() {
assertEquals(new Rectangle(0, 25, 200, 50), new UniformAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 200, 50));
}
@Test
public void testGetAOIUniformCenteredW2WN() {
assertEquals(new Rectangle(25, 0, 150, 100), new UniformAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 75, 50));
}
@Test
public void testGetAOIUniformCenteredW2WNNormalized() {
assertEquals(new Rectangle(25, 0, 150, 100), new UniformAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 150, 100));
}
@Test
public void testGetAOIUniformCenteredW2WNormalized() {
assertEquals(new Rectangle(0, 0, 200, 100), new UniformAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 200, 100));
}
@Test
public void testGetAOIUniformCenteredW2N() {
assertEquals(new Rectangle(75, 0, 50, 100), new UniformAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 100, 200));
}
@Test
public void testGetAOIUniformCenteredW2NNormalized() {
assertEquals(new Rectangle(75, 0, 50, 100), new UniformAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 50, 100));
}
@Test
public void testGetAOIUniformCenteredN2S() {
assertEquals(new Rectangle(0, 50, 100, 100), new UniformAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 333, 333));
}
@Test
public void testGetAOIUniformCenteredN2SNormalized() {
assertEquals(new Rectangle(0, 50, 100, 100), new UniformAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 100, 100));
}
@Test
public void testGetAOIUniformCenteredN2W() {
assertEquals(new Rectangle(0, 75, 100, 50), new UniformAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 200, 100));
}
@Test
public void testGetAOIUniformCenteredN2WNormalized() {
assertEquals(new Rectangle(0, 75, 100, 50), new UniformAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 100, 50));
}
@Test
public void testGetAOIUniformCenteredN2N() {
assertEquals(new Rectangle(0, 0, 100, 200), new UniformAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 50, 100));
}
@Test
public void testGetAOIUniformCenteredN2NN() {
assertEquals(new Rectangle(25, 0, 50, 200), new UniformAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 25, 100));
}
@Test
public void testGetAOIUniformCenteredN2NW() {
assertEquals(new Rectangle(0, 33, 100, 133), new UniformAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 75, 100));
}
@Test
public void testGetAOIUniformCenteredN2NWNormalized() {
assertEquals(new Rectangle(0, 37, 100, 125), new UniformAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 100, 125));
}
@Test
public void testGetAOIUniformCenteredN2NNormalized() {
assertEquals(new Rectangle(0, 0, 100, 200), new UniformAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 100, 200));
}
// -----------------------------------------------------------------------------------------------------------------
// Absolute AOI centered
// -----------------------------------------------------------------------------------------------------------------
@Test
public void testGetAOICenteredS2SUp() {
assertEquals(new Rectangle(0, 0, 100, 100), new DefaultAreaOfInterest(SQUARE_100_100).getAOI(-1, -1, 333, 333));
}
@Test
public void testGetAOICenteredS2SDown() {
assertEquals(new Rectangle(33, 33, 33, 33), new DefaultAreaOfInterest(SQUARE_100_100).getAOI(-1, -1, 33, 33));
}
@Test
public void testGetAOICenteredS2SSame() {
assertEquals(new Rectangle(0, 0, 100, 100), new DefaultAreaOfInterest(SQUARE_100_100).getAOI(-1, -1, 100, 100));
}
@Test
public void testGetAOICenteredS2WOverflow() {
assertEquals(new Rectangle(0, 0, 100, 100), new DefaultAreaOfInterest(SQUARE_100_100).getAOI(-1, -1, 200, 100));
}
@Test
public void testGetAOICenteredS2W() {
assertEquals(new Rectangle(40, 45, 20, 10), new DefaultAreaOfInterest(SQUARE_100_100).getAOI(-1, -1, 20, 10));
}
@Test
public void testGetAOICenteredS2WMax() {
assertEquals(new Rectangle(0, 25, 100, 50), new DefaultAreaOfInterest(SQUARE_100_100).getAOI(-1, -1, 100, 50));
}
@Test
public void testGetAOICenteredS2NOverflow() {
assertEquals(new Rectangle(0, 0, 100, 100), new DefaultAreaOfInterest(SQUARE_100_100).getAOI(-1, -1, 100, 200));
}
@Test
public void testGetAOICenteredS2N() {
assertEquals(new Rectangle(45, 40, 10, 20), new DefaultAreaOfInterest(SQUARE_100_100).getAOI(-1, -1, 10, 20));
}
@Test
public void testGetAOICenteredS2NMax() {
assertEquals(new Rectangle(25, 0, 50, 100), new DefaultAreaOfInterest(SQUARE_100_100).getAOI(-1, -1, 50, 100));
}
@Test
public void testGetAOICenteredW2SOverflow() {
assertEquals(new Rectangle(0, 0, 200, 100), new DefaultAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 333, 333));
}
@Test
public void testGetAOICenteredW2S() {
assertEquals(new Rectangle(75, 25, 50, 50), new DefaultAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 50, 50));
}
@Test
public void testGetAOICenteredW2SMax() {
assertEquals(new Rectangle(50, 0, 100, 100), new DefaultAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 100, 100));
}
@Test
public void testGetAOICenteredW2WOverflow() {
assertEquals(new Rectangle(0, 0, 200, 100), new DefaultAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 300, 200));
}
@Test
public void testGetAOICenteredW2W() {
assertEquals(new Rectangle(50, 25, 100, 50), new DefaultAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 100, 50));
}
@Test
public void testGetAOICenteredW2WW() {
assertEquals(new Rectangle(10, 40, 180, 20), new DefaultAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 180, 20));
}
@Test
public void testGetAOICenteredW2WN() {
assertEquals(new Rectangle(62, 25, 75, 50), new DefaultAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 75, 50));
}
@Test
public void testGetAOICenteredW2WSame() {
assertEquals(new Rectangle(0, 0, 200, 100), new DefaultAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 200, 100));
}
@Test
public void testGetAOICenteredW2NOverflow() {
assertEquals(new Rectangle(50, 0, 100, 100), new DefaultAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 100, 200));
}
@Test
public void testGetAOICenteredW2N() {
assertEquals(new Rectangle(83, 25, 33, 50), new DefaultAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 33, 50));
}
@Test
public void testGetAOICenteredW2NMax() {
assertEquals(new Rectangle(75, 0, 50, 100), new DefaultAreaOfInterest(LANDSCAPE_200_100).getAOI(-1, -1, 50, 100));
}
@Test
public void testGetAOICenteredN2S() {
assertEquals(new Rectangle(33, 83, 33, 33), new DefaultAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 33, 33));
}
@Test
public void testGetAOICenteredN2SMax() {
assertEquals(new Rectangle(0, 50, 100, 100), new DefaultAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 100, 100));
}
@Test
public void testGetAOICenteredN2WOverflow() {
assertEquals(new Rectangle(0, 50, 100, 100), new DefaultAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 200, 100));
}
@Test
public void testGetAOICenteredN2W() {
assertEquals(new Rectangle(40, 95, 20, 10), new DefaultAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 20, 10));
}
@Test
public void testGetAOICenteredN2WMax() {
assertEquals(new Rectangle(0, 75, 100, 50), new DefaultAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 100, 50));
}
@Test
public void testGetAOICenteredN2N() {
assertEquals(new Rectangle(45, 90, 10, 20), new DefaultAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 10, 20));
}
@Test
public void testGetAOICenteredN2NSame() {
assertEquals(new Rectangle(0, 0, 100, 200), new DefaultAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 100, 200));
}
@Test
public void testGetAOICenteredN2NN() {
assertEquals(new Rectangle(37, 50, 25, 100), new DefaultAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 25, 100));
}
@Test
public void testGetAOICenteredN2NW() {
assertEquals(new Rectangle(12, 50, 75, 100), new DefaultAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 75, 100));
}
@Test
public void testGetAOICenteredN2NWMax() {
assertEquals(new Rectangle(0, 37, 100, 125), new DefaultAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 100, 125));
}
@Test
public void testGetAOICenteredN2NMax() {
assertEquals(new Rectangle(0, 0, 100, 200), new DefaultAreaOfInterest(PORTRAIT_100_200).getAOI(-1, -1, 100, 200));
}
}